blob: 438dbb8d25e741345590d1da0ada98d081f9b541 [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"
Lorenzo Colitti67a19cf2022-06-16 00:19:29 +090058#include "android/net/INetd.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070059
JP Abgralldb7da582011-09-18 12:57:32 -070060/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090061#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090062const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
63const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
64const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
65const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
66const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +090067const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
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;
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -080072using android::base::StartsWith;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090073using android::base::StringAppendF;
74using android::base::StringPrintf;
Luke Huange64fa382018-07-24 16:38:22 +080075using android::net::FirewallController;
Lorenzo Colitti67a19cf2022-06-16 00:19:29 +090076using android::net::INetd::CLAT_MARK;
Luke Huange64fa382018-07-24 16:38:22 +080077using android::netdutils::StatusOr;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090078using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090079
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090080namespace {
81
82const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090083const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090084
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070085/**
86 * Some comments about the rules:
87 * * Ordering
88 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080089 * E.g. "-I bw_INPUT -i rmnet0 -j costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070090 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070091 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070092 *
93 * * global quota vs per interface quota
94 * - global quota for all costly interfaces uses a single costly chain:
95 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070096 * iptables -N bw_costly_shared
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080097 * iptables -I bw_INPUT -i iface0 -j bw_costly_shared
98 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_shared
JP Abgrall7e51cde2013-07-03 13:33:05 -070099 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800100 * -j REJECT --reject-with icmp-net-prohibited
101 * iptables -A bw_costly_shared -j bw_penalty_box
102 * iptables -A bw_penalty_box -j bw_happy_box
103 * iptables -A bw_happy_box -j bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700104 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700105 * . adding a new iface to this, E.g.:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800106 * iptables -I bw_INPUT -i iface1 -j bw_costly_shared
107 * iptables -I bw_OUTPUT -o iface1 -j bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700108 *
109 * - quota per interface. This is achieve by having "costly" chains per quota.
110 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700111 * iptables -N bw_costly_iface0
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800112 * iptables -I bw_INPUT -i iface0 -j bw_costly_iface0
113 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_iface0
JP Abgrall7e51cde2013-07-03 13:33:05 -0700114 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800115 * -j REJECT --reject-with icmp-port-unreachable
116 * iptables -A bw_costly_iface0 -j bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700117 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900118 * * Penalty box, happy box and data saver.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900119 * - bw_penalty box is a denylist of apps that are rejected.
120 * - bw_happy_box is an allowlist of apps. It always includes all system apps
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900121 * - bw_data_saver implements data usage restrictions.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900122 * - Via the UI the user can add and remove apps from the allowlist and
123 * denylist, and turn on/off data saver.
124 * - The denylist takes precedence over the allowlist and the allowlist
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900125 * takes precedence over data saver.
126 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700127 * * bw_penalty_box handling:
128 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900129 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700130 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800131 * -j REJECT --reject-with icmp-port-unreachable
JP Abgralle4788732013-07-02 20:28:45 -0700132 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700133 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900134 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700135 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700136 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800137 * -j RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900138 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900139 * * bw_data_saver handling:
140 * - The bw_data_saver comes after the happy box.
141 * Enable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800142 * iptables -R 1 bw_data_saver -j REJECT --reject-with icmp-port-unreachable
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900143 * Disable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800144 * iptables -R 1 bw_data_saver -j RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700145 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900146
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900147const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900148
149static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900150 /*
151 * Cleanup rules.
152 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
153 * to allow coexistance.
154 */
155 "*filter",
156 ":bw_INPUT -",
157 ":bw_OUTPUT -",
158 ":bw_FORWARD -",
159 ":bw_happy_box -",
160 ":bw_penalty_box -",
161 ":bw_data_saver -",
162 ":bw_costly_shared -",
163 ":bw_global_alert -",
164 "COMMIT",
165 "*raw",
166 ":bw_raw_PREROUTING -",
167 "COMMIT",
168 "*mangle",
169 ":bw_mangle_POSTROUTING -",
170 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700171
Benedict Wongb9baf262017-12-03 15:43:08 -0800172static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
173
174/**
175 * Basic commands for creation of hooks into data accounting and data boxes.
176 *
177 * Included in these commands are rules to prevent the double-counting of IPsec
178 * packets. The general overview is as follows:
179 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
180 * completely accurate, and count only the outer packet. As such, the inner
181 * packet must be ignored, which is done through the use of two rules: use
182 * of the policy module (for tunnel mode), and VTI interface checks (for
183 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
184 * ipsec*
185 * > Outbound UID billing can always be done with the outer packets, due to the
186 * ability to always find the correct UID (based on the skb->sk). As such,
187 * the inner packets should be ignored based on the policy module, or the
188 * output interface if a VTI (ipsec+)
189 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
190 * opened the encap socket, and as such, should be billed as early as
191 * possible (for transport mode; tunnel mode usage should be billed to
192 * sending/receiving application). Due to the inner packet being
193 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
194 * has to be applied to prevent counting a second time.
195 * > Inbound ESP has no socket, and as such must be accounted later. ESP
196 * protocol packets are skipped via a blanket rule.
197 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
198 * ignore rule in the input chain would actually break the INPUT chain;
199 * Those rules are designed to ignore inner packets, and in the tunnel
200 * mode UDP, or any ESP case, we would not have billed the outer packet.
201 *
202 * See go/ipsec-data-accounting for more information.
203 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800204
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100205std::vector<std::string> getBasicAccountingCommands() {
206 // clang-format off
Yabin Cui169c9dc2020-04-29 10:37:03 -0700207 std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700208 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900209
210 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700211 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
212 "-A bw_INPUT -p esp -j RETURN",
213 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
214 uidBillingMask),
Chenbo Feng703798e2018-06-15 17:07:59 -0700215 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Luke Huangae038f82018-11-05 11:17:31 +0900216 "-A bw_OUTPUT -j bw_global_alert",
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800217 "-A bw_costly_shared -j bw_penalty_box",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100218 ("-I bw_penalty_box -m bpf --object-pinned " XT_BPF_DENYLIST_PROG_PATH " -j REJECT"),
219 "-A bw_penalty_box -j bw_happy_box",
220 "-A bw_happy_box -j bw_data_saver",
Chenbo Feng703798e2018-06-15 17:07:59 -0700221 "-A bw_data_saver -j RETURN",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100222 ("-I bw_happy_box -m bpf --object-pinned " XT_BPF_ALLOWLIST_PROG_PATH " -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700223 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700224
Chenbo Feng703798e2018-06-15 17:07:59 -0700225 "*raw",
Hungming Chenba815952022-04-01 19:57:45 +0800226 // Drop duplicate ingress clat packets
227 StringPrintf("-A bw_raw_PREROUTING -m mark --mark 0x%x -j DROP", CLAT_MARK),
Chenbo Feng703798e2018-06-15 17:07:59 -0700228 // Prevents IPSec double counting (Tunnel mode and Transport mode,
229 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700230 ("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700231 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700232 // This is ingress interface accounting. There is no need to do anything specific
233 // for 464xlat here, because we only ever account 464xlat traffic on the clat
234 // interface and later correct for overhead (+20 bytes/packet).
235 //
236 // Note: eBPF offloaded packets never hit base interface's ip6tables, and non
Maciej Żenczykowski7219cfe2022-04-11 17:17:11 -0700237 // offloaded packets are dropped up above due to being marked with CLAT_MARK
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700238 //
239 // Hence we will never double count and additional corrections are not needed.
240 // We can simply take the sum of base and stacked (+20B/pkt) interface counts.
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100241 ("-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700242 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700243
Chenbo Feng703798e2018-06-15 17:07:59 -0700244 "*mangle",
245 // Prevents IPSec double counting (Tunnel mode and Transport mode,
246 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700247 ("-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700248 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700249 // Clear the uid billing done (egress) mark before sending this packet
250 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700251 // This is egress interface accounting: we account 464xlat traffic only on
252 // the clat interface (as offloaded packets never hit base interface's ip6tables)
253 // and later sum base and stacked with overhead (+20B/pkt) in higher layers
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100254 ("-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700255 COMMIT_AND_CLOSE};
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100256 // clang-format on
Chenbo Feng5ed17992018-03-13 21:30:49 -0700257 return ipt_basic_accounting_commands;
258}
259
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900260} // namespace
261
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900262BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700263}
264
JP Abgrall0e540ec2013-08-26 15:13:10 -0700265void BandwidthController::flushCleanTables(bool doClean) {
266 /* Flush and remove the bw_costly_<iface> tables */
267 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700268
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900269 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900270 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700271}
JP Abgrall0031cea2012-04-17 16:38:23 -0700272
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900273int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700274 /* flush+clean is allowed to fail */
275 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700276 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700277}
278
Luke Huangf44a3c12018-09-07 12:10:12 +0800279int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700280 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900281 mSharedQuotaIfaces.clear();
282 mQuotaIfaces.clear();
283 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900284 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700285
JP Abgrall0e540ec2013-08-26 15:13:10 -0700286 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700287
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100288 std::string commands = Join(getBasicAccountingCommands(), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900289 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700290}
291
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900292int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700293
294 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700295 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700296}
297
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900298std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
299 std::string cmd;
300 const char *chainName = "bw_data_saver";
301 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
302 std::string criticalCommands = enable ?
303 FirewallController::makeCriticalCommands(target, chainName) : "";
304 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900305 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900306 ":%s -\n"
307 "%s"
308 "-A %s%s\n"
309 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
310 return cmd;
311}
312
313int BandwidthController::enableDataSaver(bool enable) {
314 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
315 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
316 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900317}
318
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900319int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700320 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700321 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900322 constexpr char cost[] = "shared";
323 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700324
JP Abgrall8a932722011-07-13 19:17:35 -0700325 if (!maxBytes) {
326 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000327 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700328 return -1;
329 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700330 if (!isIfaceName(iface))
331 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700332
333 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900334 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700335 }
336
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900337 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700338
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900339 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900340 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
341 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800342 "*filter",
343 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain),
344 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(), chain),
345 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain),
346 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900347 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900348 if (mSharedQuotaIfaces.empty()) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800349 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900350 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900351 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900352 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900353
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900354 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900355 if (res) {
356 ALOGE("Failed set quota rule");
357 removeInterfaceSharedQuota(iface);
358 return -1;
359 }
360 mSharedQuotaBytes = maxBytes;
361 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700362 }
363
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900364 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900365 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700366 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900367 ALOGE("Failed update quota for %s", cost);
368 removeInterfaceSharedQuota(iface);
369 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700370 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900371 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700372 }
373 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700374}
375
JP Abgrall8a932722011-07-13 19:17:35 -0700376/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900377int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
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 Abgrall69261cb2014-06-19 18:35:24 -0700381 if (!isIfaceName(iface))
382 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700383
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900384 auto it = mSharedQuotaIfaces.find(iface);
385
386 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900387 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700388 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700389 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700390
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900391 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800392 "*filter",
393 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain),
394 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain),
395 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain),
396 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900397 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900398 if (mSharedQuotaIfaces.size() == 1) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800399 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900400 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700401 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900402 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900403
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900404 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
405 ALOGE("Failed to remove shared quota on %s", iface.c_str());
406 return -1;
407 }
408
409 int res = 0;
410 mSharedQuotaIfaces.erase(it);
411 if (mSharedQuotaIfaces.empty()) {
412 mSharedQuotaBytes = 0;
413 if (mSharedAlertBytes) {
414 res = removeSharedAlert();
415 if (res == 0) {
416 mSharedAlertBytes = 0;
417 }
418 }
419 }
420
421 return res;
422
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700423}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700424
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900425int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900426 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700427
Luke Huang531f5d32018-08-03 15:19:05 +0800428 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700429
JP Abgrall8a932722011-07-13 19:17:35 -0700430 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000431 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800432 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700433 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700434 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700435 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700436 }
437
JP Abgrall0dad7c22011-06-24 11:58:14 -0700438 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900439 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700440
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900441 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800442 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900443 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900444 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800445 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700446 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900447 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900448 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700449 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700450
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900451 const std::string chain = "bw_costly_" + iface;
452 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
453 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800454 "*filter",
455 StringPrintf(":%s -", chain.c_str()),
456 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
457 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain.c_str()),
458 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(),
459 chain.c_str()),
460 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
461 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
462 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT", chain.c_str(),
463 maxBytes, cost.c_str()),
464 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900465 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900466 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900467 ALOGE("Failed set quota rule");
468 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800469 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900470 }
471
472 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
473 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700474}
475
JP Abgrall8a932722011-07-13 19:17:35 -0700476int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
477 return getInterfaceQuota("shared", bytes);
478}
479
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900480int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900481 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900482 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700483
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900484 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700485
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900486 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
487 if (!isOk(file)) {
488 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700489 return -1;
490 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900491 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
492 if (!isOk(rv)) {
493 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
494 return -1;
495 }
496 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
497 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700498}
499
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900500int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800501 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700502
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900503 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700504
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900505 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900506 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800507 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700508 }
509
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900510 const std::string chain = "bw_costly_" + iface;
511 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800512 "*filter",
513 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain.c_str()),
514 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain.c_str()),
515 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
516 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
517 StringPrintf("-F %s", chain.c_str()),
518 StringPrintf("-X %s", chain.c_str()),
519 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900520 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900521
522 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700523
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900524 if (res == 0) {
525 mQuotaIfaces.erase(it);
526 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700527
Luke Huang531f5d32018-08-03 15:19:05 +0800528 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700529}
JP Abgrall8a932722011-07-13 19:17:35 -0700530
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900531int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900532 const auto& sys = android::netdutils::sSyscalls.get();
533 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700534
JP Abgrall69261cb2014-06-19 18:35:24 -0700535 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900536 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800537 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700538 }
539
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900540 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
541 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800542 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900543 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800544 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700545 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900546 // TODO: should we propagate this error?
547 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700548 return 0;
549}
550
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900551int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
552 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900553 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900554 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700555
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900556 // TODO: consider using an alternate template for the delete that does not include the --quota
557 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900558
Luke Huangae038f82018-11-05 11:17:31 +0900559 /*
560 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
561 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
562 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
563 */
564 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900565 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900566 StringAppendF(&alertQuotaCmd, "COMMIT\n");
567
568 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700569}
570
571int BandwidthController::setGlobalAlert(int64_t bytes) {
572 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700573
574 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000575 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800576 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700577 }
Luke Huang19b49c52018-10-22 12:12:05 +0900578
579 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900580 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700581 res = updateQuota(alertName, bytes);
582 } else {
583 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800584 if (res) {
585 res = -EREMOTEIO;
586 }
JP Abgrall8a932722011-07-13 19:17:35 -0700587 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900588 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700589 return res;
590}
591
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900592int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700593
594 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700595
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900596 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000597 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700598 return -1;
599 }
Luke Huang19b49c52018-10-22 12:12:05 +0900600
601 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900602 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900603 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700604 return res;
605}
606
607int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900608 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000609 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700610 return -1;
611 }
612 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000613 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700614 return -1;
615 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900616 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700617}
618
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900619int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900620 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700621}
622
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900623int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700624 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900625 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800626 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700627 }
628
JP Abgrall8a932722011-07-13 19:17:35 -0700629 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000630 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800631 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700632 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900633 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700634
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900635 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000636 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800637 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700638 }
639
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900640 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700641}
642
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900643int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700644 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900645 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800646 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700647 }
648
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900649 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700650
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900651 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900652 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800653 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700654 }
655
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900656 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700657}
658
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900659int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
660 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700661 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700662
JP Abgrall69261cb2014-06-19 18:35:24 -0700663 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900664 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800665 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700666 }
667
JP Abgrall8a932722011-07-13 19:17:35 -0700668 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000669 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800670 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700671 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900672
673 std::string alertName = costName + "Alert";
674 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700675 if (*alertBytes) {
676 res = updateQuota(alertName, *alertBytes);
677 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900678 std::vector<std::string> commands = {
679 "*filter\n",
680 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
681 "COMMIT\n"
682 };
683 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
684 if (res) {
685 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800686 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900687 }
JP Abgrall8a932722011-07-13 19:17:35 -0700688 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900689 if (res == 0) {
690 *alertBytes = bytes;
691 }
JP Abgrall8a932722011-07-13 19:17:35 -0700692 return res;
693}
694
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900695int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700696 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900697 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800698 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700699 }
700
JP Abgrall8a932722011-07-13 19:17:35 -0700701 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900702 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800703 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700704 }
705
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900706 std::string alertName = costName + "Alert";
707 std::string chainName = "bw_costly_" + costName;
708 std::vector<std::string> commands = {
709 "*filter\n",
710 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
711 "COMMIT\n"
712 };
713 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
714 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800715 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900716 }
JP Abgrall8a932722011-07-13 19:17:35 -0700717
718 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900719 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700720}
JP Abgralldb7da582011-09-18 12:57:32 -0700721
JP Abgrall0e540ec2013-08-26 15:13:10 -0700722void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900723 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
724 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700725
726 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900727 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
728 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700729 return;
730 }
731 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900732 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700733}
734
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900735void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
736 std::stringstream stream(ruleList);
737 std::string rule;
738 std::vector<std::string> clearCommands = { "*filter" };
739 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700740
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900741 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
742 while (std::getline(stream, rule, '\n')) {
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800743 if (!StartsWith(rule, NEW_CHAIN_COMMAND)) continue;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900744 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
745 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
746
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800747 if (!StartsWith(chainName, "bw_costly_") || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700748 continue;
749 }
750
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900751 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700752 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900753 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700754 }
755 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900756
757 if (clearCommands.size() == 1) {
758 // No rules found.
759 return;
760 }
761
762 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900763 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700764}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900765
766inline const char *BandwidthController::opToString(IptOp op) {
767 switch (op) {
768 case IptOpInsert:
769 return "-I";
770 case IptOpDelete:
771 return "-D";
772 }
773}
774
775inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
776 /*
777 * Must be careful what one rejects with, as upper layer protocols will just
778 * keep on hammering the device until the number of retries are done.
779 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
780 */
781 switch (jumpHandling) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900782 case IptJumpReject:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800783 return " -j REJECT";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900784 case IptJumpReturn:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800785 return " -j RETURN";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900786 }
787}