blob: ffedaf6730e7ee44f67b8bc86411970104c4ec6f [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"
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
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900259std::vector<std::string> toStrVec(int num, char* strs[]) {
260 std::vector<std::string> tmp;
261 for (int i = 0; i < num; ++i) {
262 tmp.emplace_back(strs[i]);
263 }
264 return tmp;
265}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900266
267} // namespace
268
Chenbo Fenga121e202018-03-19 11:51:54 -0700269bool BandwidthController::getBpfStatsStatus() {
270 bool useBpf = (access(XT_BPF_INGRESS_PROG_PATH, F_OK) != -1) &&
271 (access(XT_BPF_EGRESS_PROG_PATH, F_OK) != -1);
272 // TODO: remove this when xt_bpf kernel support is ready
273 useBpf = false;
274 return useBpf;
275}
276
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900277BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700278}
279
JP Abgrall0e540ec2013-08-26 15:13:10 -0700280void BandwidthController::flushCleanTables(bool doClean) {
281 /* Flush and remove the bw_costly_<iface> tables */
282 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700283
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900284 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900285 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700286}
JP Abgrall0031cea2012-04-17 16:38:23 -0700287
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900288int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700289 /* flush+clean is allowed to fail */
290 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700291 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700292}
293
294int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700295 char value[PROPERTY_VALUE_MAX];
296
297 if (!force) {
298 property_get("persist.bandwidth.enable", value, "1");
299 if (!strcmp(value, "0"))
300 return 0;
301 }
JP Abgrall8a932722011-07-13 19:17:35 -0700302
JP Abgralldb7da582011-09-18 12:57:32 -0700303 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900304 mSharedQuotaIfaces.clear();
305 mQuotaIfaces.clear();
306 mGlobalAlertBytes = 0;
307 mGlobalAlertTetherCount = 0;
308 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700309
JP Abgrall0e540ec2013-08-26 15:13:10 -0700310 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700311
312 std::string commands = Join(getBasicAccountingCommands(), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900313 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700314}
315
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900316int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700317
318 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700319 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700320}
321
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900322std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
323 std::string cmd;
324 const char *chainName = "bw_data_saver";
325 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
326 std::string criticalCommands = enable ?
327 FirewallController::makeCriticalCommands(target, chainName) : "";
328 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900329 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900330 ":%s -\n"
331 "%s"
332 "-A %s%s\n"
333 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
334 return cmd;
335}
336
337int BandwidthController::enableDataSaver(bool enable) {
338 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
339 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
340 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900341}
342
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700343int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900344 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
345 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700346}
347
348int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900349 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
350 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700351}
352
JP Abgralle4788732013-07-02 20:28:45 -0700353int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900354 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
355 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700356}
357
358int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900359 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
360 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700361}
362
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900363int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
364 const std::string& chain, IptJumpOp jumpHandling,
365 IptOp op) {
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900366 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900367 for (const auto& appStrUid : appStrUids) {
368 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
369 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700370 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900371 StringAppendF(&cmd, "COMMIT\n");
372 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700373}
374
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900375int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700376 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700377 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900378 constexpr char cost[] = "shared";
379 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700380
JP Abgrall8a932722011-07-13 19:17:35 -0700381 if (!maxBytes) {
382 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000383 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700384 return -1;
385 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700386 if (!isIfaceName(iface))
387 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700388
389 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900390 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700391 }
392
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900393 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700394
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900395 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900396 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
397 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900398 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900399 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
400 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900401 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900402 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
403 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900404 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900405 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
406 " --name %s --jump REJECT",
407 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900408 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900409 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900410
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900411 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900412 if (res) {
413 ALOGE("Failed set quota rule");
414 removeInterfaceSharedQuota(iface);
415 return -1;
416 }
417 mSharedQuotaBytes = maxBytes;
418 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700419 }
420
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900421 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900422 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700423 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900424 ALOGE("Failed update quota for %s", cost);
425 removeInterfaceSharedQuota(iface);
426 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700427 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900428 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700429 }
430 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700431}
432
JP Abgrall8a932722011-07-13 19:17:35 -0700433/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900434int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900435 constexpr char cost[] = "shared";
436 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700437
JP Abgrall69261cb2014-06-19 18:35:24 -0700438 if (!isIfaceName(iface))
439 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700440
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900441 auto it = mSharedQuotaIfaces.find(iface);
442
443 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900444 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700445 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700446 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700447
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900448 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900449 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900450 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
451 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900452 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900453 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
454 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900455 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900456 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
457 " --name %s --jump REJECT",
458 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700459 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900460 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900461
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900462 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
463 ALOGE("Failed to remove shared quota on %s", iface.c_str());
464 return -1;
465 }
466
467 int res = 0;
468 mSharedQuotaIfaces.erase(it);
469 if (mSharedQuotaIfaces.empty()) {
470 mSharedQuotaBytes = 0;
471 if (mSharedAlertBytes) {
472 res = removeSharedAlert();
473 if (res == 0) {
474 mSharedAlertBytes = 0;
475 }
476 }
477 }
478
479 return res;
480
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700481}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700482
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900483int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900484 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700485
JP Abgrall69261cb2014-06-19 18:35:24 -0700486 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700487 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700488
JP Abgrall8a932722011-07-13 19:17:35 -0700489 if (!maxBytes) {
490 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000491 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700492 return -1;
493 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700494 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700495 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700496 }
497
JP Abgrall0dad7c22011-06-24 11:58:14 -0700498 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900499 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700500
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900501 if (it != mQuotaIfaces.end()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900502 if (updateQuota(cost, maxBytes) != 0) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900503 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900504 removeInterfaceQuota(iface);
505 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700506 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900507 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900508 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700509 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700510
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900511 const std::string chain = "bw_costly_" + iface;
512 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
513 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900514 "*filter",
515 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900516 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
517 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
518 chain.c_str()),
519 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
520 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900521 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900522 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
523 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
524 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900525 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900526 };
527
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900528 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900529 ALOGE("Failed set quota rule");
530 removeInterfaceQuota(iface);
531 return -1;
532 }
533
534 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
535 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700536}
537
JP Abgrall8a932722011-07-13 19:17:35 -0700538int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
539 return getInterfaceQuota("shared", bytes);
540}
541
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900542int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900543 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900544 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700545
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900546 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700547
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900548 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
549 if (!isOk(file)) {
550 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700551 return -1;
552 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900553 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
554 if (!isOk(rv)) {
555 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
556 return -1;
557 }
558 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
559 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700560}
561
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900562int BandwidthController::removeInterfaceQuota(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700563 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700564 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700565
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900566 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700567
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900568 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900569 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700570 return -1;
571 }
572
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900573 const std::string chain = "bw_costly_" + iface;
574 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900575 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900576 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
577 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900578 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900579 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
580 StringPrintf("-F %s", chain.c_str()),
581 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900582 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900583 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900584
585 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700586
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900587 if (res == 0) {
588 mQuotaIfaces.erase(it);
589 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700590
591 return res;
592}
JP Abgrall8a932722011-07-13 19:17:35 -0700593
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900594int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900595 const auto& sys = android::netdutils::sSyscalls.get();
596 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700597
JP Abgrall69261cb2014-06-19 18:35:24 -0700598 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900599 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700600 return -1;
601 }
602
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900603 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
604 if (!isOk(file)) {
605 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700606 return -1;
607 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900608 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700609 return 0;
610}
611
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900612int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
613 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900614 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900615 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700616
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900617 // TODO: consider using an alternate template for the delete that does not include the --quota
618 // value. This code works because the --quota value is ignored by deletes
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900619 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
620 alertName.c_str());
621 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
622 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900623 StringAppendF(&alertQuotaCmd, "COMMIT\n");
624
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900625 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700626}
627
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900628int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
629 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900630 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900631 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900632 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
633 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900634 StringAppendF(&alertQuotaCmd, "COMMIT\n");
635
636 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700637}
638
639int BandwidthController::setGlobalAlert(int64_t bytes) {
640 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700641 int res = 0;
642
643 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000644 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700645 return -1;
646 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900647 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700648 res = updateQuota(alertName, bytes);
649 } else {
650 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900651 if (mGlobalAlertTetherCount) {
652 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700653 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
654 }
JP Abgrall8a932722011-07-13 19:17:35 -0700655 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900656 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700657 return res;
658}
659
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900660int BandwidthController::setGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700661 const char *alertName = ALERT_GLOBAL_NAME;
662 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700663
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900664 mGlobalAlertTetherCount++;
665 ALOGV("setGlobalAlertInForwardChain(): %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700666
667 /*
668 * If there is no globalAlert active we are done.
669 * If there is an active globalAlert but this is not the 1st
670 * tether, we are also done.
671 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900672 if (!mGlobalAlertBytes || mGlobalAlertTetherCount != 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700673 return 0;
674 }
675
676 /* We only add the rule if this was the 1st tether added. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900677 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700678 return res;
679}
680
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900681int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700682
683 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700684 int res = 0;
685
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900686 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000687 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700688 return -1;
689 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900690 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
691 if (mGlobalAlertTetherCount) {
692 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700693 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900694 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700695 return res;
696}
697
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900698int BandwidthController::removeGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700699 int res = 0;
700 const char *alertName = ALERT_GLOBAL_NAME;
701
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900702 if (!mGlobalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000703 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700704 return -1;
705 }
706
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900707 mGlobalAlertTetherCount--;
JP Abgrallc6c67342011-10-07 16:28:54 -0700708 /*
709 * If there is no globalAlert active we are done.
710 * If there is an active globalAlert but there are more
711 * tethers, we are also done.
712 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900713 if (!mGlobalAlertBytes || mGlobalAlertTetherCount >= 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700714 return 0;
715 }
716
717 /* We only detete the rule if this was the last tether removed. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900718 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700719 return res;
720}
721
JP Abgrall8a932722011-07-13 19:17:35 -0700722int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900723 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000724 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700725 return -1;
726 }
727 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000728 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700729 return -1;
730 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900731 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700732}
733
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900734int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900735 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700736}
737
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900738int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700739 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900740 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700741 return -1;
742 }
743
JP Abgrall8a932722011-07-13 19:17:35 -0700744 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000745 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700746 return -1;
747 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900748 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700749
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900750 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000751 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700752 return -1;
753 }
754
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900755 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700756}
757
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900758int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700759 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900760 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700761 return -1;
762 }
763
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900764 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700765
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900766 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900767 ALOGE("No prior alert set for interface %s", iface.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700768 return -1;
769 }
770
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900771 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700772}
773
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900774int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
775 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700776 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700777
JP Abgrall69261cb2014-06-19 18:35:24 -0700778 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900779 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700780 return -1;
781 }
782
JP Abgrall8a932722011-07-13 19:17:35 -0700783 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000784 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700785 return -1;
786 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900787
788 std::string alertName = costName + "Alert";
789 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700790 if (*alertBytes) {
791 res = updateQuota(alertName, *alertBytes);
792 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900793 std::vector<std::string> commands = {
794 "*filter\n",
795 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
796 "COMMIT\n"
797 };
798 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
799 if (res) {
800 ALOGE("Failed to set costly alert for %s", costName.c_str());
801 }
JP Abgrall8a932722011-07-13 19:17:35 -0700802 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900803 if (res == 0) {
804 *alertBytes = bytes;
805 }
JP Abgrall8a932722011-07-13 19:17:35 -0700806 return res;
807}
808
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900809int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700810 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900811 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700812 return -1;
813 }
814
JP Abgrall8a932722011-07-13 19:17:35 -0700815 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900816 ALOGE("No prior alert set for %s alert", costName.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700817 return -1;
818 }
819
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900820 std::string alertName = costName + "Alert";
821 std::string chainName = "bw_costly_" + costName;
822 std::vector<std::string> commands = {
823 "*filter\n",
824 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
825 "COMMIT\n"
826 };
827 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
828 ALOGE("Failed to remove costly alert %s", costName.c_str());
829 return -1;
830 }
JP Abgrall8a932722011-07-13 19:17:35 -0700831
832 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900833 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700834}
JP Abgralldb7da582011-09-18 12:57:32 -0700835
JP Abgrall0e540ec2013-08-26 15:13:10 -0700836void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900837 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
838 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700839
840 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900841 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
842 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700843 return;
844 }
845 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900846 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700847}
848
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900849void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
850 std::stringstream stream(ruleList);
851 std::string rule;
852 std::vector<std::string> clearCommands = { "*filter" };
853 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700854
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900855 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
856 while (std::getline(stream, rule, '\n')) {
857 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
858 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
859 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
860
861 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700862 continue;
863 }
864
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900865 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700866 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900867 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700868 }
869 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900870
871 if (clearCommands.size() == 1) {
872 // No rules found.
873 return;
874 }
875
876 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900877 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700878}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900879
880inline const char *BandwidthController::opToString(IptOp op) {
881 switch (op) {
882 case IptOpInsert:
883 return "-I";
884 case IptOpDelete:
885 return "-D";
886 }
887}
888
889inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
890 /*
891 * Must be careful what one rejects with, as upper layer protocols will just
892 * keep on hammering the device until the number of retries are done.
893 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
894 */
895 switch (jumpHandling) {
896 case IptJumpNoAdd:
897 return "";
898 case IptJumpReject:
899 return " --jump REJECT";
900 case IptJumpReturn:
901 return " --jump RETURN";
902 }
903}