blob: f397cf712ce1df71f98d2ad2b2d0011e9cc71b34 [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>
Elliott Hughes70323e82024-03-15 19:10:40 +000028#include <inttypes.h>
JP Abgralldb7da582011-09-18 12:57:32 -070029#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070030#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070031#include <string.h>
Joel Scherpelz01cc5492017-06-16 10:45:14 +090032#include <string>
33#include <vector>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070034
35#include <sys/socket.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38#include <sys/wait.h>
39
40#include <linux/netlink.h>
41#include <linux/rtnetlink.h>
42#include <linux/pkt_sched.h>
43
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090044#include "android-base/stringprintf.h"
Lorenzo Colitti13debb82016-03-27 17:46:30 +090045#include "android-base/strings.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070046#define LOG_TAG "BandwidthController"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070047#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080048#include <log/log.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049
Joel Scherpelz01cc5492017-06-16 10:45:14 +090050#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070051#include "BandwidthController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070052#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090053#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080054#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090055#include "NetdConstants.h"
Lorenzo Colitti67a19cf2022-06-16 00:19:29 +090056#include "android/net/INetd.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070057
JP Abgralldb7da582011-09-18 12:57:32 -070058/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090059#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090060const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
61const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
62const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
63const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
64const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +090065const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090066
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090067auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090068
Joel Scherpelzd59526a2017-06-28 16:24:09 +090069using android::base::Join;
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -080070using android::base::StartsWith;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090071using android::base::StringAppendF;
72using android::base::StringPrintf;
Luke Huange64fa382018-07-24 16:38:22 +080073using android::net::FirewallController;
Lorenzo Colitti67a19cf2022-06-16 00:19:29 +090074using android::net::INetd::CLAT_MARK;
Luke Huange64fa382018-07-24 16:38:22 +080075using android::netdutils::StatusOr;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090076using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090077
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090078namespace {
79
80const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090081const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090082
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070083/**
84 * Some comments about the rules:
85 * * Ordering
86 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080087 * E.g. "-I bw_INPUT -i rmnet0 -j costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070088 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070089 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070090 *
91 * * global quota vs per interface quota
92 * - global quota for all costly interfaces uses a single costly chain:
93 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070094 * iptables -N bw_costly_shared
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080095 * iptables -I bw_INPUT -i iface0 -j bw_costly_shared
96 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_shared
JP Abgrall7e51cde2013-07-03 13:33:05 -070097 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080098 * -j REJECT --reject-with icmp-net-prohibited
99 * iptables -A bw_costly_shared -j bw_penalty_box
100 * iptables -A bw_penalty_box -j bw_happy_box
101 * iptables -A bw_happy_box -j bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700102 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700103 * . adding a new iface to this, E.g.:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800104 * iptables -I bw_INPUT -i iface1 -j bw_costly_shared
105 * iptables -I bw_OUTPUT -o iface1 -j bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700106 *
107 * - quota per interface. This is achieve by having "costly" chains per quota.
108 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700109 * iptables -N bw_costly_iface0
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800110 * iptables -I bw_INPUT -i iface0 -j bw_costly_iface0
111 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_iface0
JP Abgrall7e51cde2013-07-03 13:33:05 -0700112 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800113 * -j REJECT --reject-with icmp-port-unreachable
114 * iptables -A bw_costly_iface0 -j bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700115 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900116 * * Penalty box, happy box and data saver.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900117 * - bw_penalty box is a denylist of apps that are rejected.
118 * - bw_happy_box is an allowlist of apps. It always includes all system apps
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900119 * - bw_data_saver implements data usage restrictions.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900120 * - Via the UI the user can add and remove apps from the allowlist and
121 * denylist, and turn on/off data saver.
122 * - The denylist takes precedence over the allowlist and the allowlist
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900123 * takes precedence over data saver.
124 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700125 * * bw_penalty_box handling:
126 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900127 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700128 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800129 * -j REJECT --reject-with icmp-port-unreachable
JP Abgralle4788732013-07-02 20:28:45 -0700130 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700131 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900132 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700133 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700134 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800135 * -j RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900136 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900137 * * bw_data_saver handling:
138 * - The bw_data_saver comes after the happy box.
139 * Enable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800140 * iptables -R 1 bw_data_saver -j REJECT --reject-with icmp-port-unreachable
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900141 * Disable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800142 * iptables -R 1 bw_data_saver -j RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700143 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900144
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900145const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900146
147static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900148 /*
149 * Cleanup rules.
150 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
151 * to allow coexistance.
152 */
153 "*filter",
154 ":bw_INPUT -",
155 ":bw_OUTPUT -",
156 ":bw_FORWARD -",
157 ":bw_happy_box -",
158 ":bw_penalty_box -",
159 ":bw_data_saver -",
160 ":bw_costly_shared -",
161 ":bw_global_alert -",
162 "COMMIT",
163 "*raw",
164 ":bw_raw_PREROUTING -",
165 "COMMIT",
166 "*mangle",
167 ":bw_mangle_POSTROUTING -",
168 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700169
Benedict Wongb9baf262017-12-03 15:43:08 -0800170static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
171
172/**
173 * Basic commands for creation of hooks into data accounting and data boxes.
174 *
175 * Included in these commands are rules to prevent the double-counting of IPsec
176 * packets. The general overview is as follows:
177 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
178 * completely accurate, and count only the outer packet. As such, the inner
179 * packet must be ignored, which is done through the use of two rules: use
180 * of the policy module (for tunnel mode), and VTI interface checks (for
181 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
182 * ipsec*
183 * > Outbound UID billing can always be done with the outer packets, due to the
184 * ability to always find the correct UID (based on the skb->sk). As such,
185 * the inner packets should be ignored based on the policy module, or the
186 * output interface if a VTI (ipsec+)
187 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
188 * opened the encap socket, and as such, should be billed as early as
189 * possible (for transport mode; tunnel mode usage should be billed to
190 * sending/receiving application). Due to the inner packet being
191 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
192 * has to be applied to prevent counting a second time.
193 * > Inbound ESP has no socket, and as such must be accounted later. ESP
194 * protocol packets are skipped via a blanket rule.
195 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
196 * ignore rule in the input chain would actually break the INPUT chain;
197 * Those rules are designed to ignore inner packets, and in the tunnel
198 * mode UDP, or any ESP case, we would not have billed the outer packet.
199 *
200 * See go/ipsec-data-accounting for more information.
201 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800202
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100203std::vector<std::string> getBasicAccountingCommands() {
204 // clang-format off
Yabin Cui169c9dc2020-04-29 10:37:03 -0700205 std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700206 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900207
Chirayu Desai545ae8c2021-01-05 03:24:48 +0530208 "-A bw_INPUT -j bw_global_alert", "-A bw_INPUT -j bw_penalty_box",
Chenbo Feng703798e2018-06-15 17:07:59 -0700209 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
210 "-A bw_INPUT -p esp -j RETURN",
211 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
212 uidBillingMask),
Chenbo Feng703798e2018-06-15 17:07:59 -0700213 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Chirayu Desai545ae8c2021-01-05 03:24:48 +0530214 "-A bw_OUTPUT -j bw_global_alert", "-A bw_OUTPUT -j bw_penalty_box",
215 "-A bw_FORWARD -j bw_penalty_box",
216 "-A bw_costly_shared -j bw_happy_box",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100217 ("-I bw_penalty_box -m bpf --object-pinned " XT_BPF_DENYLIST_PROG_PATH " -j REJECT"),
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100218 "-A bw_happy_box -j bw_data_saver",
Chenbo Feng703798e2018-06-15 17:07:59 -0700219 "-A bw_data_saver -j RETURN",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100220 ("-I bw_happy_box -m bpf --object-pinned " XT_BPF_ALLOWLIST_PROG_PATH " -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700221 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700222
Chenbo Feng703798e2018-06-15 17:07:59 -0700223 "*raw",
Hungming Chenba815952022-04-01 19:57:45 +0800224 // Drop duplicate ingress clat packets
225 StringPrintf("-A bw_raw_PREROUTING -m mark --mark 0x%x -j DROP", CLAT_MARK),
Chenbo Feng703798e2018-06-15 17:07:59 -0700226 // Prevents IPSec double counting (Tunnel mode and Transport mode,
227 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700228 ("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700229 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700230 // This is ingress interface accounting. There is no need to do anything specific
231 // for 464xlat here, because we only ever account 464xlat traffic on the clat
232 // interface and later correct for overhead (+20 bytes/packet).
233 //
234 // Note: eBPF offloaded packets never hit base interface's ip6tables, and non
Maciej Żenczykowski7219cfe2022-04-11 17:17:11 -0700235 // offloaded packets are dropped up above due to being marked with CLAT_MARK
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700236 //
237 // Hence we will never double count and additional corrections are not needed.
238 // We can simply take the sum of base and stacked (+20B/pkt) interface counts.
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100239 ("-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700240 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700241
Chenbo Feng703798e2018-06-15 17:07:59 -0700242 "*mangle",
243 // Prevents IPSec double counting (Tunnel mode and Transport mode,
244 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700245 ("-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700246 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700247 // Clear the uid billing done (egress) mark before sending this packet
248 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700249 // This is egress interface accounting: we account 464xlat traffic only on
250 // the clat interface (as offloaded packets never hit base interface's ip6tables)
251 // and later sum base and stacked with overhead (+20B/pkt) in higher layers
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100252 ("-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700253 COMMIT_AND_CLOSE};
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100254 // clang-format on
Chenbo Feng5ed17992018-03-13 21:30:49 -0700255 return ipt_basic_accounting_commands;
256}
257
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900258} // namespace
259
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900260BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700261}
262
JP Abgrall0e540ec2013-08-26 15:13:10 -0700263void BandwidthController::flushCleanTables(bool doClean) {
264 /* Flush and remove the bw_costly_<iface> tables */
265 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700266
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900267 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900268 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700269}
JP Abgrall0031cea2012-04-17 16:38:23 -0700270
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900271int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700272 /* flush+clean is allowed to fail */
273 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700274 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700275}
276
Luke Huangf44a3c12018-09-07 12:10:12 +0800277int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700278 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900279 mSharedQuotaIfaces.clear();
280 mQuotaIfaces.clear();
281 mGlobalAlertBytes = 0;
Patrick Rohrbe4fc0c2024-04-12 13:13:30 -0700282 mSharedQuotaBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700283
JP Abgrall0e540ec2013-08-26 15:13:10 -0700284 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700285
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100286 std::string commands = Join(getBasicAccountingCommands(), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900287 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700288}
289
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900290std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
291 std::string cmd;
292 const char *chainName = "bw_data_saver";
293 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
294 std::string criticalCommands = enable ?
295 FirewallController::makeCriticalCommands(target, chainName) : "";
296 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900297 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900298 ":%s -\n"
299 "%s"
300 "-A %s%s\n"
301 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
302 return cmd;
303}
304
305int BandwidthController::enableDataSaver(bool enable) {
306 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
307 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
308 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900309}
310
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900311int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700312 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700313 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900314 constexpr char cost[] = "shared";
315 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700316
JP Abgrall8a932722011-07-13 19:17:35 -0700317 if (!maxBytes) {
318 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000319 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700320 return -1;
321 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700322 if (!isIfaceName(iface))
323 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700324
325 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900326 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700327 }
328
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900329 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700330
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900331 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900332 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
333 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800334 "*filter",
335 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain),
336 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(), chain),
337 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain),
338 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900339 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900340 if (mSharedQuotaIfaces.empty()) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800341 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900342 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900343 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900344 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900345
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900346 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900347 if (res) {
348 ALOGE("Failed set quota rule");
349 removeInterfaceSharedQuota(iface);
350 return -1;
351 }
352 mSharedQuotaBytes = maxBytes;
353 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700354 }
355
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900356 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900357 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700358 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900359 ALOGE("Failed update quota for %s", cost);
360 removeInterfaceSharedQuota(iface);
361 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700362 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900363 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700364 }
365 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700366}
367
JP Abgrall8a932722011-07-13 19:17:35 -0700368/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900369int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900370 constexpr char cost[] = "shared";
371 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700372
JP Abgrall69261cb2014-06-19 18:35:24 -0700373 if (!isIfaceName(iface))
374 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700375
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900376 auto it = mSharedQuotaIfaces.find(iface);
377
378 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900379 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700380 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700381 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700382
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900383 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800384 "*filter",
385 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain),
386 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain),
387 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain),
388 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900389 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900390 if (mSharedQuotaIfaces.size() == 1) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800391 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900392 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700393 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900394 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900395
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900396 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
397 ALOGE("Failed to remove shared quota on %s", iface.c_str());
398 return -1;
399 }
400
401 int res = 0;
402 mSharedQuotaIfaces.erase(it);
403 if (mSharedQuotaIfaces.empty()) {
404 mSharedQuotaBytes = 0;
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900405 }
406
407 return res;
408
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700409}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700410
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900411int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900412 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700413
Luke Huang531f5d32018-08-03 15:19:05 +0800414 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700415
JP Abgrall8a932722011-07-13 19:17:35 -0700416 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000417 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800418 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700419 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700420 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700421 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700422 }
423
JP Abgrall0dad7c22011-06-24 11:58:14 -0700424 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900425 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700426
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900427 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800428 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900429 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900430 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800431 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700432 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900433 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900434 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700435 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700436
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900437 const std::string chain = "bw_costly_" + iface;
438 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
439 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800440 "*filter",
441 StringPrintf(":%s -", chain.c_str()),
Chirayu Desai545ae8c2021-01-05 03:24:48 +0530442 StringPrintf("-A %s -j bw_happy_box", chain.c_str()),
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800443 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain.c_str()),
444 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(),
445 chain.c_str()),
446 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
447 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
448 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT", chain.c_str(),
449 maxBytes, cost.c_str()),
450 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900451 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900452 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900453 ALOGE("Failed set quota rule");
454 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800455 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900456 }
457
458 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
459 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700460}
461
JP Abgrall8a932722011-07-13 19:17:35 -0700462int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
463 return getInterfaceQuota("shared", bytes);
464}
465
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900466int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900467 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900468 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700469
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900470 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700471
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900472 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
473 if (!isOk(file)) {
474 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700475 return -1;
476 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900477 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
478 if (!isOk(rv)) {
479 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
480 return -1;
481 }
482 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
483 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700484}
485
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900486int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800487 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700488
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900489 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700490
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900491 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900492 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800493 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700494 }
495
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900496 const std::string chain = "bw_costly_" + iface;
497 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800498 "*filter",
499 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain.c_str()),
500 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain.c_str()),
501 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
502 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
503 StringPrintf("-F %s", chain.c_str()),
504 StringPrintf("-X %s", chain.c_str()),
505 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900506 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900507
508 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700509
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900510 if (res == 0) {
511 mQuotaIfaces.erase(it);
512 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700513
Luke Huang531f5d32018-08-03 15:19:05 +0800514 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700515}
JP Abgrall8a932722011-07-13 19:17:35 -0700516
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900517int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900518 const auto& sys = android::netdutils::sSyscalls.get();
519 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700520
JP Abgrall69261cb2014-06-19 18:35:24 -0700521 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900522 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800523 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700524 }
525
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900526 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
527 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800528 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900529 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800530 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700531 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900532 // TODO: should we propagate this error?
533 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700534 return 0;
535}
536
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900537int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
538 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900539 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900540 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700541
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900542 // TODO: consider using an alternate template for the delete that does not include the --quota
543 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900544
Luke Huangae038f82018-11-05 11:17:31 +0900545 /*
546 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
547 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
548 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
549 */
550 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900551 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900552 StringAppendF(&alertQuotaCmd, "COMMIT\n");
553
554 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700555}
556
557int BandwidthController::setGlobalAlert(int64_t bytes) {
558 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700559
560 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000561 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800562 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700563 }
Luke Huang19b49c52018-10-22 12:12:05 +0900564
565 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900566 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700567 res = updateQuota(alertName, bytes);
568 } else {
569 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800570 if (res) {
571 res = -EREMOTEIO;
572 }
JP Abgrall8a932722011-07-13 19:17:35 -0700573 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900574 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700575 return res;
576}
577
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900578int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700579
580 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700581
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900582 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000583 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700584 return -1;
585 }
Luke Huang19b49c52018-10-22 12:12:05 +0900586
587 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900588 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900589 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700590 return res;
591}
592
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900593int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700594 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900595 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800596 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700597 }
598
JP Abgrall8a932722011-07-13 19:17:35 -0700599 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000600 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800601 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700602 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900603 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700604
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900605 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000606 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800607 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700608 }
609
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900610 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700611}
612
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900613int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700614 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900615 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800616 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700617 }
618
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900619 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700620
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900621 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900622 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800623 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700624 }
625
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900626 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700627}
628
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900629int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
630 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700631 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700632
JP Abgrall69261cb2014-06-19 18:35:24 -0700633 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900634 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800635 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700636 }
637
JP Abgrall8a932722011-07-13 19:17:35 -0700638 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000639 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800640 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700641 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900642
643 std::string alertName = costName + "Alert";
644 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700645 if (*alertBytes) {
646 res = updateQuota(alertName, *alertBytes);
647 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900648 std::vector<std::string> commands = {
649 "*filter\n",
650 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
651 "COMMIT\n"
652 };
653 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
654 if (res) {
655 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800656 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900657 }
JP Abgrall8a932722011-07-13 19:17:35 -0700658 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900659 if (res == 0) {
660 *alertBytes = bytes;
661 }
JP Abgrall8a932722011-07-13 19:17:35 -0700662 return res;
663}
664
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900665int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700666 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900667 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800668 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700669 }
670
JP Abgrall8a932722011-07-13 19:17:35 -0700671 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900672 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800673 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700674 }
675
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900676 std::string alertName = costName + "Alert";
677 std::string chainName = "bw_costly_" + costName;
678 std::vector<std::string> commands = {
679 "*filter\n",
680 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
681 "COMMIT\n"
682 };
683 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
684 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800685 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900686 }
JP Abgrall8a932722011-07-13 19:17:35 -0700687
688 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900689 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700690}
JP Abgralldb7da582011-09-18 12:57:32 -0700691
JP Abgrall0e540ec2013-08-26 15:13:10 -0700692void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900693 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
694 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700695
696 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900697 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
698 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700699 return;
700 }
701 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900702 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700703}
704
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900705void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
706 std::stringstream stream(ruleList);
707 std::string rule;
708 std::vector<std::string> clearCommands = { "*filter" };
709 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700710
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900711 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
712 while (std::getline(stream, rule, '\n')) {
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800713 if (!StartsWith(rule, NEW_CHAIN_COMMAND)) continue;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900714 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
715 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
716
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800717 if (!StartsWith(chainName, "bw_costly_") || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700718 continue;
719 }
720
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900721 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700722 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900723 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700724 }
725 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900726
727 if (clearCommands.size() == 1) {
728 // No rules found.
729 return;
730 }
731
732 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900733 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700734}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900735
736inline const char *BandwidthController::opToString(IptOp op) {
737 switch (op) {
738 case IptOpInsert:
739 return "-I";
740 case IptOpDelete:
741 return "-D";
742 }
743}
744
745inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
746 /*
747 * Must be careful what one rejects with, as upper layer protocols will just
748 * keep on hammering the device until the number of retries are done.
749 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
750 */
751 switch (jumpHandling) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900752 case IptJumpReject:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800753 return " -j REJECT";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900754 case IptJumpReturn:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800755 return " -j RETURN";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900756 }
757}