blob: 1b46234a52cf52a7b5edbab8be42b082a4dc6df1 [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>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070051
Joel Scherpelz01cc5492017-06-16 10:45:14 +090052#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070053#include "BandwidthController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070054#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090055#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080056#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090057#include "NetdConstants.h"
Chenbo Feng95892f32018-06-07 14:52:02 -070058#include "TrafficController.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";
Luke Huangae038f82018-11-05 11:17:31 +090068const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090069
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090070auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090071
Joel Scherpelzd59526a2017-06-28 16:24:09 +090072using android::base::Join;
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -080073using android::base::StartsWith;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090074using android::base::StringAppendF;
75using android::base::StringPrintf;
Luke Huange64fa382018-07-24 16:38:22 +080076using android::net::FirewallController;
Chenbo Feng95892f32018-06-07 14:52:02 -070077using android::net::gCtls;
Chenbo Feng95892f32018-06-07 14:52:02 -070078using android::netdutils::Status;
Luke Huange64fa382018-07-24 16:38:22 +080079using android::netdutils::StatusOr;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090080using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090081
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090082namespace {
83
84const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090085const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090086
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.
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080091 * E.g. "-I bw_INPUT -i rmnet0 -j 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
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080099 * iptables -I bw_INPUT -i iface0 -j bw_costly_shared
100 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_shared
JP Abgrall7e51cde2013-07-03 13:33:05 -0700101 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800102 * -j REJECT --reject-with icmp-net-prohibited
103 * iptables -A bw_costly_shared -j bw_penalty_box
104 * iptables -A bw_penalty_box -j bw_happy_box
105 * iptables -A bw_happy_box -j 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.:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800108 * iptables -I bw_INPUT -i iface1 -j bw_costly_shared
109 * iptables -I bw_OUTPUT -o iface1 -j 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
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800114 * iptables -I bw_INPUT -i iface0 -j bw_costly_iface0
115 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_iface0
JP Abgrall7e51cde2013-07-03 13:33:05 -0700116 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800117 * -j REJECT --reject-with icmp-port-unreachable
118 * iptables -A bw_costly_iface0 -j 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.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900121 * - bw_penalty box is a denylist of apps that are rejected.
122 * - bw_happy_box is an allowlist of apps. It always includes all system apps
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900123 * - bw_data_saver implements data usage restrictions.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900124 * - Via the UI the user can add and remove apps from the allowlist and
125 * denylist, and turn on/off data saver.
126 * - The denylist takes precedence over the allowlist and the allowlist
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900127 * 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 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800133 * -j REJECT --reject-with icmp-port-unreachable
JP Abgralle4788732013-07-02 20:28:45 -0700134 *
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 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800139 * -j 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:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800144 * iptables -R 1 bw_data_saver -j REJECT --reject-with icmp-port-unreachable
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900145 * Disable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800146 * iptables -R 1 bw_data_saver -j 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 Colitticdd79f12020-07-30 12:03:40 +0900150const std::string BPF_PENALTY_BOX_MATCH_DENYLIST_COMMAND = StringPrintf(
151 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_DENYLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900152
153static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900154 /*
155 * Cleanup rules.
156 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
157 * to allow coexistance.
158 */
159 "*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 ":bw_global_alert -",
168 "COMMIT",
169 "*raw",
170 ":bw_raw_PREROUTING -",
171 "COMMIT",
172 "*mangle",
173 ":bw_mangle_POSTROUTING -",
174 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700175
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
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100209std::vector<std::string> getBasicAccountingCommands() {
210 // clang-format off
Yabin Cui169c9dc2020-04-29 10:37:03 -0700211 std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700212 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900213
214 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700215 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
216 "-A bw_INPUT -p esp -j RETURN",
217 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
218 uidBillingMask),
Chenbo Feng703798e2018-06-15 17:07:59 -0700219 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Luke Huangae038f82018-11-05 11:17:31 +0900220 "-A bw_OUTPUT -j bw_global_alert",
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800221 "-A bw_costly_shared -j bw_penalty_box",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100222 ("-I bw_penalty_box -m bpf --object-pinned " XT_BPF_DENYLIST_PROG_PATH " -j REJECT"),
223 "-A bw_penalty_box -j bw_happy_box",
224 "-A bw_happy_box -j bw_data_saver",
Chenbo Feng703798e2018-06-15 17:07:59 -0700225 "-A bw_data_saver -j RETURN",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100226 ("-I bw_happy_box -m bpf --object-pinned " XT_BPF_ALLOWLIST_PROG_PATH " -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700227 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700228
Chenbo Feng703798e2018-06-15 17:07:59 -0700229 "*raw",
230 // Prevents IPSec double counting (Tunnel mode and Transport mode,
231 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700232 ("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700233 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700234 // This is ingress interface accounting. There is no need to do anything specific
235 // for 464xlat here, because we only ever account 464xlat traffic on the clat
236 // interface and later correct for overhead (+20 bytes/packet).
237 //
238 // Note: eBPF offloaded packets never hit base interface's ip6tables, and non
239 // offloaded packets (which when using xt_qtaguid means all packets, because
240 // clat eBPF offload does not work on xt_qtaguid devices) are dropped in
241 // clat_raw_PREROUTING.
242 //
243 // Hence we will never double count and additional corrections are not needed.
244 // We can simply take the sum of base and stacked (+20B/pkt) interface counts.
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100245 ("-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700246 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700247
Chenbo Feng703798e2018-06-15 17:07:59 -0700248 "*mangle",
249 // Prevents IPSec double counting (Tunnel mode and Transport mode,
250 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700251 ("-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700252 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700253 // Clear the uid billing done (egress) mark before sending this packet
254 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
255 // Packets from the clat daemon have already been counted on egress through the
256 // stacked v4-* interface.
Maciej Żenczykowski9071aa62020-05-27 18:14:05 -0700257 "-A bw_mangle_POSTROUTING -m owner --uid-owner clat -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700258 // This is egress interface accounting: we account 464xlat traffic only on
259 // the clat interface (as offloaded packets never hit base interface's ip6tables)
260 // and later sum base and stacked with overhead (+20B/pkt) in higher layers
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100261 ("-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700262 COMMIT_AND_CLOSE};
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100263 // clang-format on
Chenbo Feng5ed17992018-03-13 21:30:49 -0700264 return ipt_basic_accounting_commands;
265}
266
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900267} // namespace
268
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900269BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700270}
271
JP Abgrall0e540ec2013-08-26 15:13:10 -0700272void BandwidthController::flushCleanTables(bool doClean) {
273 /* Flush and remove the bw_costly_<iface> tables */
274 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700275
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900276 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900277 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700278}
JP Abgrall0031cea2012-04-17 16:38:23 -0700279
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900280int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700281 /* flush+clean is allowed to fail */
282 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700283 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700284}
285
Luke Huangf44a3c12018-09-07 12:10:12 +0800286int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700287 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900288 mSharedQuotaIfaces.clear();
289 mQuotaIfaces.clear();
290 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900291 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700292
JP Abgrall0e540ec2013-08-26 15:13:10 -0700293 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700294
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100295 std::string commands = Join(getBasicAccountingCommands(), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900296 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700297}
298
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900299int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700300
301 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700302 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700303}
304
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900305std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
306 std::string cmd;
307 const char *chainName = "bw_data_saver";
308 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
309 std::string criticalCommands = enable ?
310 FirewallController::makeCriticalCommands(target, chainName) : "";
311 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900312 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900313 ":%s -\n"
314 "%s"
315 "-A %s%s\n"
316 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
317 return cmd;
318}
319
320int BandwidthController::enableDataSaver(bool enable) {
321 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
322 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
323 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900324}
325
Patrick Rohr79203972020-12-29 18:16:35 +0100326int BandwidthController::addNaughtyApps(const std::vector<uint32_t>& appUids) {
Patrick Rohr7db39b92020-12-29 19:41:33 +0100327 return manipulateSpecialApps(appUids, PENALTY_BOX_MATCH, IptOpInsert);
Luke Huang531f5d32018-08-03 15:19:05 +0800328}
329
Patrick Rohr79203972020-12-29 18:16:35 +0100330int BandwidthController::removeNaughtyApps(const std::vector<uint32_t>& appUids) {
Patrick Rohr7db39b92020-12-29 19:41:33 +0100331 return manipulateSpecialApps(appUids, PENALTY_BOX_MATCH, IptOpDelete);
Luke Huang531f5d32018-08-03 15:19:05 +0800332}
333
Patrick Rohr79203972020-12-29 18:16:35 +0100334int BandwidthController::addNiceApps(const std::vector<uint32_t>& appUids) {
Patrick Rohr7db39b92020-12-29 19:41:33 +0100335 return manipulateSpecialApps(appUids, HAPPY_BOX_MATCH, IptOpInsert);
Luke Huang531f5d32018-08-03 15:19:05 +0800336}
337
Patrick Rohr79203972020-12-29 18:16:35 +0100338int BandwidthController::removeNiceApps(const std::vector<uint32_t>& appUids) {
Patrick Rohr7db39b92020-12-29 19:41:33 +0100339 return manipulateSpecialApps(appUids, HAPPY_BOX_MATCH, IptOpDelete);
Luke Huang531f5d32018-08-03 15:19:05 +0800340}
341
Patrick Rohr79203972020-12-29 18:16:35 +0100342int BandwidthController::manipulateSpecialApps(const std::vector<uint32_t>& appUids,
Patrick Rohr7db39b92020-12-29 19:41:33 +0100343 UidOwnerMatchType matchType, IptOp op) {
344 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appUids, matchType, op);
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100345 if (!isOk(status)) {
346 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700347 }
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100348 return status.code();
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700349}
350
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900351int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700352 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700353 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900354 constexpr char cost[] = "shared";
355 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700356
JP Abgrall8a932722011-07-13 19:17:35 -0700357 if (!maxBytes) {
358 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000359 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700360 return -1;
361 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700362 if (!isIfaceName(iface))
363 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700364
365 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900366 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700367 }
368
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900369 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700370
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900371 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900372 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
373 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800374 "*filter",
375 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain),
376 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(), chain),
377 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain),
378 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900379 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900380 if (mSharedQuotaIfaces.empty()) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800381 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900382 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900383 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900384 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900385
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900386 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900387 if (res) {
388 ALOGE("Failed set quota rule");
389 removeInterfaceSharedQuota(iface);
390 return -1;
391 }
392 mSharedQuotaBytes = maxBytes;
393 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700394 }
395
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900396 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900397 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700398 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900399 ALOGE("Failed update quota for %s", cost);
400 removeInterfaceSharedQuota(iface);
401 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700402 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900403 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700404 }
405 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700406}
407
JP Abgrall8a932722011-07-13 19:17:35 -0700408/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900409int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900410 constexpr char cost[] = "shared";
411 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700412
JP Abgrall69261cb2014-06-19 18:35:24 -0700413 if (!isIfaceName(iface))
414 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700415
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900416 auto it = mSharedQuotaIfaces.find(iface);
417
418 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900419 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700420 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700421 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700422
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900423 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800424 "*filter",
425 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain),
426 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain),
427 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain),
428 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900429 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900430 if (mSharedQuotaIfaces.size() == 1) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800431 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900432 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700433 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900434 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900435
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900436 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
437 ALOGE("Failed to remove shared quota on %s", iface.c_str());
438 return -1;
439 }
440
441 int res = 0;
442 mSharedQuotaIfaces.erase(it);
443 if (mSharedQuotaIfaces.empty()) {
444 mSharedQuotaBytes = 0;
445 if (mSharedAlertBytes) {
446 res = removeSharedAlert();
447 if (res == 0) {
448 mSharedAlertBytes = 0;
449 }
450 }
451 }
452
453 return res;
454
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700455}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700456
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900457int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900458 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700459
Luke Huang531f5d32018-08-03 15:19:05 +0800460 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700461
JP Abgrall8a932722011-07-13 19:17:35 -0700462 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000463 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800464 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700465 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700466 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700467 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700468 }
469
JP Abgrall0dad7c22011-06-24 11:58:14 -0700470 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900471 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700472
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900473 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800474 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900475 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900476 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800477 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700478 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900479 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900480 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700481 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700482
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900483 const std::string chain = "bw_costly_" + iface;
484 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
485 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800486 "*filter",
487 StringPrintf(":%s -", chain.c_str()),
488 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
489 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain.c_str()),
490 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(),
491 chain.c_str()),
492 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
493 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
494 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT", chain.c_str(),
495 maxBytes, cost.c_str()),
496 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900497 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900498 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900499 ALOGE("Failed set quota rule");
500 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800501 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900502 }
503
504 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
505 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700506}
507
JP Abgrall8a932722011-07-13 19:17:35 -0700508int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
509 return getInterfaceQuota("shared", bytes);
510}
511
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900512int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900513 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900514 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700515
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900516 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700517
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900518 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
519 if (!isOk(file)) {
520 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700521 return -1;
522 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900523 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
524 if (!isOk(rv)) {
525 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
526 return -1;
527 }
528 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
529 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700530}
531
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900532int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800533 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700534
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900535 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700536
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900537 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900538 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800539 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700540 }
541
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900542 const std::string chain = "bw_costly_" + iface;
543 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800544 "*filter",
545 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain.c_str()),
546 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain.c_str()),
547 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
548 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
549 StringPrintf("-F %s", chain.c_str()),
550 StringPrintf("-X %s", chain.c_str()),
551 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900552 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900553
554 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700555
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900556 if (res == 0) {
557 mQuotaIfaces.erase(it);
558 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700559
Luke Huang531f5d32018-08-03 15:19:05 +0800560 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700561}
JP Abgrall8a932722011-07-13 19:17:35 -0700562
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900563int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900564 const auto& sys = android::netdutils::sSyscalls.get();
565 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700566
JP Abgrall69261cb2014-06-19 18:35:24 -0700567 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900568 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800569 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700570 }
571
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900572 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
573 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800574 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900575 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800576 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700577 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900578 // TODO: should we propagate this error?
579 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700580 return 0;
581}
582
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900583int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
584 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900585 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900586 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700587
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900588 // TODO: consider using an alternate template for the delete that does not include the --quota
589 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900590
Luke Huangae038f82018-11-05 11:17:31 +0900591 /*
592 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
593 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
594 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
595 */
596 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900597 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900598 StringAppendF(&alertQuotaCmd, "COMMIT\n");
599
600 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700601}
602
603int BandwidthController::setGlobalAlert(int64_t bytes) {
604 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700605
606 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000607 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800608 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700609 }
Luke Huang19b49c52018-10-22 12:12:05 +0900610
611 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900612 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700613 res = updateQuota(alertName, bytes);
614 } else {
615 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800616 if (res) {
617 res = -EREMOTEIO;
618 }
JP Abgrall8a932722011-07-13 19:17:35 -0700619 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900620 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700621 return res;
622}
623
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900624int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700625
626 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700627
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900628 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000629 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700630 return -1;
631 }
Luke Huang19b49c52018-10-22 12:12:05 +0900632
633 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900634 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900635 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700636 return res;
637}
638
639int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900640 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000641 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700642 return -1;
643 }
644 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000645 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700646 return -1;
647 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900648 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700649}
650
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900651int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900652 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700653}
654
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900655int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700656 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900657 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800658 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700659 }
660
JP Abgrall8a932722011-07-13 19:17:35 -0700661 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000662 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800663 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700664 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900665 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700666
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900667 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000668 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800669 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700670 }
671
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900672 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700673}
674
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900675int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700676 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900677 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800678 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700679 }
680
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900681 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700682
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900683 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900684 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800685 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700686 }
687
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900688 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700689}
690
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900691int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
692 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700693 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700694
JP Abgrall69261cb2014-06-19 18:35:24 -0700695 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900696 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800697 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700698 }
699
JP Abgrall8a932722011-07-13 19:17:35 -0700700 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000701 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800702 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700703 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900704
705 std::string alertName = costName + "Alert";
706 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700707 if (*alertBytes) {
708 res = updateQuota(alertName, *alertBytes);
709 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900710 std::vector<std::string> commands = {
711 "*filter\n",
712 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
713 "COMMIT\n"
714 };
715 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
716 if (res) {
717 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800718 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900719 }
JP Abgrall8a932722011-07-13 19:17:35 -0700720 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900721 if (res == 0) {
722 *alertBytes = bytes;
723 }
JP Abgrall8a932722011-07-13 19:17:35 -0700724 return res;
725}
726
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900727int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700728 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900729 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800730 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700731 }
732
JP Abgrall8a932722011-07-13 19:17:35 -0700733 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900734 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800735 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700736 }
737
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900738 std::string alertName = costName + "Alert";
739 std::string chainName = "bw_costly_" + costName;
740 std::vector<std::string> commands = {
741 "*filter\n",
742 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
743 "COMMIT\n"
744 };
745 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
746 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800747 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900748 }
JP Abgrall8a932722011-07-13 19:17:35 -0700749
750 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900751 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700752}
JP Abgralldb7da582011-09-18 12:57:32 -0700753
JP Abgrall0e540ec2013-08-26 15:13:10 -0700754void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900755 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
756 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700757
758 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900759 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
760 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700761 return;
762 }
763 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900764 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700765}
766
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900767void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
768 std::stringstream stream(ruleList);
769 std::string rule;
770 std::vector<std::string> clearCommands = { "*filter" };
771 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700772
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900773 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
774 while (std::getline(stream, rule, '\n')) {
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800775 if (!StartsWith(rule, NEW_CHAIN_COMMAND)) continue;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900776 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
777 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
778
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800779 if (!StartsWith(chainName, "bw_costly_") || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700780 continue;
781 }
782
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900783 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700784 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900785 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700786 }
787 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900788
789 if (clearCommands.size() == 1) {
790 // No rules found.
791 return;
792 }
793
794 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900795 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700796}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900797
798inline const char *BandwidthController::opToString(IptOp op) {
799 switch (op) {
800 case IptOpInsert:
801 return "-I";
802 case IptOpDelete:
803 return "-D";
804 }
805}
806
807inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
808 /*
809 * Must be careful what one rejects with, as upper layer protocols will just
810 * keep on hammering the device until the number of retries are done.
811 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
812 */
813 switch (jumpHandling) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900814 case IptJumpReject:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800815 return " -j REJECT";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900816 case IptJumpReturn:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800817 return " -j RETURN";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900818 }
819}