blob: 8dba75a5ee10a9d1b0962535a1f8218e07f8ef56 [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 Colittid0178562022-06-16 00:19:29 +090058#include "android/net/INetd.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;
Lorenzo Colittid0178562022-06-16 00:19:29 +090077using android::net::INetd::CLAT_MARK;
Luke Huange64fa382018-07-24 16:38:22 +080078using android::netdutils::StatusOr;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090079using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090080
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090081namespace {
82
83const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090084const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090085
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070086/**
87 * Some comments about the rules:
88 * * Ordering
89 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080090 * E.g. "-I bw_INPUT -i rmnet0 -j costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070091 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070092 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070093 *
94 * * global quota vs per interface quota
95 * - global quota for all costly interfaces uses a single costly chain:
96 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070097 * iptables -N bw_costly_shared
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080098 * iptables -I bw_INPUT -i iface0 -j bw_costly_shared
99 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_shared
JP Abgrall7e51cde2013-07-03 13:33:05 -0700100 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800101 * -j REJECT --reject-with icmp-net-prohibited
102 * iptables -A bw_costly_shared -j bw_penalty_box
103 * iptables -A bw_penalty_box -j bw_happy_box
104 * iptables -A bw_happy_box -j bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700105 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700106 * . adding a new iface to this, E.g.:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800107 * iptables -I bw_INPUT -i iface1 -j bw_costly_shared
108 * iptables -I bw_OUTPUT -o iface1 -j bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700109 *
110 * - quota per interface. This is achieve by having "costly" chains per quota.
111 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700112 * iptables -N bw_costly_iface0
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800113 * iptables -I bw_INPUT -i iface0 -j bw_costly_iface0
114 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_iface0
JP Abgrall7e51cde2013-07-03 13:33:05 -0700115 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800116 * -j REJECT --reject-with icmp-port-unreachable
117 * iptables -A bw_costly_iface0 -j bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700118 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900119 * * Penalty box, happy box and data saver.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900120 * - bw_penalty box is a denylist of apps that are rejected.
121 * - bw_happy_box is an allowlist of apps. It always includes all system apps
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900122 * - bw_data_saver implements data usage restrictions.
Lorenzo Colitticdd79f12020-07-30 12:03:40 +0900123 * - Via the UI the user can add and remove apps from the allowlist and
124 * denylist, and turn on/off data saver.
125 * - The denylist takes precedence over the allowlist and the allowlist
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900126 * takes precedence over data saver.
127 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700128 * * bw_penalty_box handling:
129 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900130 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700131 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800132 * -j REJECT --reject-with icmp-port-unreachable
JP Abgralle4788732013-07-02 20:28:45 -0700133 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700134 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900135 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700136 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700137 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800138 * -j RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900139 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900140 * * bw_data_saver handling:
141 * - The bw_data_saver comes after the happy box.
142 * Enable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800143 * iptables -R 1 bw_data_saver -j REJECT --reject-with icmp-port-unreachable
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900144 * Disable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800145 * iptables -R 1 bw_data_saver -j RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700146 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900147
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900148const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900149
150static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900151 /*
152 * Cleanup rules.
153 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
154 * to allow coexistance.
155 */
156 "*filter",
157 ":bw_INPUT -",
158 ":bw_OUTPUT -",
159 ":bw_FORWARD -",
160 ":bw_happy_box -",
161 ":bw_penalty_box -",
162 ":bw_data_saver -",
163 ":bw_costly_shared -",
164 ":bw_global_alert -",
165 "COMMIT",
166 "*raw",
167 ":bw_raw_PREROUTING -",
168 "COMMIT",
169 "*mangle",
170 ":bw_mangle_POSTROUTING -",
171 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700172
Benedict Wongb9baf262017-12-03 15:43:08 -0800173static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
174
175/**
176 * Basic commands for creation of hooks into data accounting and data boxes.
177 *
178 * Included in these commands are rules to prevent the double-counting of IPsec
179 * packets. The general overview is as follows:
180 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
181 * completely accurate, and count only the outer packet. As such, the inner
182 * packet must be ignored, which is done through the use of two rules: use
183 * of the policy module (for tunnel mode), and VTI interface checks (for
184 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
185 * ipsec*
186 * > Outbound UID billing can always be done with the outer packets, due to the
187 * ability to always find the correct UID (based on the skb->sk). As such,
188 * the inner packets should be ignored based on the policy module, or the
189 * output interface if a VTI (ipsec+)
190 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
191 * opened the encap socket, and as such, should be billed as early as
192 * possible (for transport mode; tunnel mode usage should be billed to
193 * sending/receiving application). Due to the inner packet being
194 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
195 * has to be applied to prevent counting a second time.
196 * > Inbound ESP has no socket, and as such must be accounted later. ESP
197 * protocol packets are skipped via a blanket rule.
198 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
199 * ignore rule in the input chain would actually break the INPUT chain;
200 * Those rules are designed to ignore inner packets, and in the tunnel
201 * mode UDP, or any ESP case, we would not have billed the outer packet.
202 *
203 * See go/ipsec-data-accounting for more information.
204 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800205
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100206std::vector<std::string> getBasicAccountingCommands() {
207 // clang-format off
Yabin Cui169c9dc2020-04-29 10:37:03 -0700208 std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700209 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900210
211 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700212 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
213 "-A bw_INPUT -p esp -j RETURN",
214 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
215 uidBillingMask),
Chenbo Feng703798e2018-06-15 17:07:59 -0700216 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Luke Huangae038f82018-11-05 11:17:31 +0900217 "-A bw_OUTPUT -j bw_global_alert",
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800218 "-A bw_costly_shared -j bw_penalty_box",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100219 ("-I bw_penalty_box -m bpf --object-pinned " XT_BPF_DENYLIST_PROG_PATH " -j REJECT"),
220 "-A bw_penalty_box -j bw_happy_box",
221 "-A bw_happy_box -j bw_data_saver",
Chenbo Feng703798e2018-06-15 17:07:59 -0700222 "-A bw_data_saver -j RETURN",
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100223 ("-I bw_happy_box -m bpf --object-pinned " XT_BPF_ALLOWLIST_PROG_PATH " -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700224 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700225
Chenbo Feng703798e2018-06-15 17:07:59 -0700226 "*raw",
Hungming Chenba815952022-04-01 19:57:45 +0800227 // Drop duplicate ingress clat packets
228 StringPrintf("-A bw_raw_PREROUTING -m mark --mark 0x%x -j DROP", CLAT_MARK),
Chenbo Feng703798e2018-06-15 17:07:59 -0700229 // Prevents IPSec double counting (Tunnel mode and Transport mode,
230 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700231 ("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700232 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700233 // This is ingress interface accounting. There is no need to do anything specific
234 // for 464xlat here, because we only ever account 464xlat traffic on the clat
235 // interface and later correct for overhead (+20 bytes/packet).
236 //
237 // Note: eBPF offloaded packets never hit base interface's ip6tables, and non
Maciej Żenczykowski7219cfe2022-04-11 17:17:11 -0700238 // offloaded packets are dropped up above due to being marked with CLAT_MARK
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700239 //
240 // Hence we will never double count and additional corrections are not needed.
241 // We can simply take the sum of base and stacked (+20B/pkt) interface counts.
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100242 ("-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700243 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700244
Chenbo Feng703798e2018-06-15 17:07:59 -0700245 "*mangle",
246 // Prevents IPSec double counting (Tunnel mode and Transport mode,
247 // respectively)
Maciej Żenczykowski2c794482020-04-21 18:22:31 -0700248 ("-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700249 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700250 // Clear the uid billing done (egress) mark before sending this packet
251 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
Maciej Żenczykowski9fcfb702020-05-26 02:26:03 -0700252 // This is egress interface accounting: we account 464xlat traffic only on
253 // the clat interface (as offloaded packets never hit base interface's ip6tables)
254 // and later sum base and stacked with overhead (+20B/pkt) in higher layers
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100255 ("-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH),
Chenbo Feng703798e2018-06-15 17:07:59 -0700256 COMMIT_AND_CLOSE};
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100257 // clang-format on
Chenbo Feng5ed17992018-03-13 21:30:49 -0700258 return ipt_basic_accounting_commands;
259}
260
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900261} // namespace
262
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900263BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700264}
265
JP Abgrall0e540ec2013-08-26 15:13:10 -0700266void BandwidthController::flushCleanTables(bool doClean) {
267 /* Flush and remove the bw_costly_<iface> tables */
268 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700269
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900270 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900271 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700272}
JP Abgrall0031cea2012-04-17 16:38:23 -0700273
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900274int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700275 /* flush+clean is allowed to fail */
276 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700277 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700278}
279
Luke Huangf44a3c12018-09-07 12:10:12 +0800280int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700281 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900282 mSharedQuotaIfaces.clear();
283 mQuotaIfaces.clear();
284 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900285 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700286
JP Abgrall0e540ec2013-08-26 15:13:10 -0700287 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700288
Patrick Rohr03e3f7b2020-12-29 16:09:33 +0100289 std::string commands = Join(getBasicAccountingCommands(), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900290 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700291}
292
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900293int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700294
295 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700296 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700297}
298
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900299std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
300 std::string cmd;
301 const char *chainName = "bw_data_saver";
302 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
303 std::string criticalCommands = enable ?
304 FirewallController::makeCriticalCommands(target, chainName) : "";
305 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900306 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900307 ":%s -\n"
308 "%s"
309 "-A %s%s\n"
310 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
311 return cmd;
312}
313
314int BandwidthController::enableDataSaver(bool enable) {
315 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
316 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
317 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900318}
319
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900320int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700321 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700322 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900323 constexpr char cost[] = "shared";
324 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700325
JP Abgrall8a932722011-07-13 19:17:35 -0700326 if (!maxBytes) {
327 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000328 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700329 return -1;
330 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700331 if (!isIfaceName(iface))
332 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700333
334 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900335 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700336 }
337
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900338 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700339
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900340 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900341 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
342 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800343 "*filter",
344 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain),
345 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(), chain),
346 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain),
347 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900348 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900349 if (mSharedQuotaIfaces.empty()) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800350 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900351 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900352 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900353 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900354
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900355 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900356 if (res) {
357 ALOGE("Failed set quota rule");
358 removeInterfaceSharedQuota(iface);
359 return -1;
360 }
361 mSharedQuotaBytes = maxBytes;
362 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700363 }
364
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900365 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900366 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700367 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900368 ALOGE("Failed update quota for %s", cost);
369 removeInterfaceSharedQuota(iface);
370 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700371 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900372 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700373 }
374 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700375}
376
JP Abgrall8a932722011-07-13 19:17:35 -0700377/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900378int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900379 constexpr char cost[] = "shared";
380 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700381
JP Abgrall69261cb2014-06-19 18:35:24 -0700382 if (!isIfaceName(iface))
383 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700384
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900385 auto it = mSharedQuotaIfaces.find(iface);
386
387 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900388 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700389 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700390 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700391
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900392 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800393 "*filter",
394 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain),
395 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain),
396 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain),
397 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900398 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900399 if (mSharedQuotaIfaces.size() == 1) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800400 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900401 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700402 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900403 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900404
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900405 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
406 ALOGE("Failed to remove shared quota on %s", iface.c_str());
407 return -1;
408 }
409
410 int res = 0;
411 mSharedQuotaIfaces.erase(it);
412 if (mSharedQuotaIfaces.empty()) {
413 mSharedQuotaBytes = 0;
414 if (mSharedAlertBytes) {
415 res = removeSharedAlert();
416 if (res == 0) {
417 mSharedAlertBytes = 0;
418 }
419 }
420 }
421
422 return res;
423
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700424}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700425
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900426int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900427 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700428
Luke Huang531f5d32018-08-03 15:19:05 +0800429 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700430
JP Abgrall8a932722011-07-13 19:17:35 -0700431 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000432 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800433 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700434 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700435 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700436 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700437 }
438
JP Abgrall0dad7c22011-06-24 11:58:14 -0700439 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900440 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700441
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900442 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800443 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900444 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900445 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800446 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700447 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900448 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900449 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700450 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700451
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900452 const std::string chain = "bw_costly_" + iface;
453 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
454 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800455 "*filter",
456 StringPrintf(":%s -", chain.c_str()),
457 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
458 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain.c_str()),
459 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(),
460 chain.c_str()),
461 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
462 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
463 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT", chain.c_str(),
464 maxBytes, cost.c_str()),
465 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900466 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900467 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900468 ALOGE("Failed set quota rule");
469 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800470 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900471 }
472
473 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
474 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700475}
476
JP Abgrall8a932722011-07-13 19:17:35 -0700477int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
478 return getInterfaceQuota("shared", bytes);
479}
480
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900481int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900482 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900483 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700484
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900485 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700486
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900487 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
488 if (!isOk(file)) {
489 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700490 return -1;
491 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900492 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
493 if (!isOk(rv)) {
494 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
495 return -1;
496 }
497 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
498 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700499}
500
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900501int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800502 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700503
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900504 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700505
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900506 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900507 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800508 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700509 }
510
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900511 const std::string chain = "bw_costly_" + iface;
512 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800513 "*filter",
514 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain.c_str()),
515 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain.c_str()),
516 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
517 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
518 StringPrintf("-F %s", chain.c_str()),
519 StringPrintf("-X %s", chain.c_str()),
520 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900521 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900522
523 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700524
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900525 if (res == 0) {
526 mQuotaIfaces.erase(it);
527 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700528
Luke Huang531f5d32018-08-03 15:19:05 +0800529 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700530}
JP Abgrall8a932722011-07-13 19:17:35 -0700531
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900532int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900533 const auto& sys = android::netdutils::sSyscalls.get();
534 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700535
JP Abgrall69261cb2014-06-19 18:35:24 -0700536 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900537 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800538 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700539 }
540
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900541 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
542 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800543 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900544 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800545 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700546 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900547 // TODO: should we propagate this error?
548 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700549 return 0;
550}
551
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900552int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
553 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900554 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900555 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700556
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900557 // TODO: consider using an alternate template for the delete that does not include the --quota
558 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900559
Luke Huangae038f82018-11-05 11:17:31 +0900560 /*
561 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
562 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
563 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
564 */
565 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900566 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900567 StringAppendF(&alertQuotaCmd, "COMMIT\n");
568
569 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700570}
571
572int BandwidthController::setGlobalAlert(int64_t bytes) {
573 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700574
575 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000576 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800577 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700578 }
Luke Huang19b49c52018-10-22 12:12:05 +0900579
580 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900581 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700582 res = updateQuota(alertName, bytes);
583 } else {
584 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800585 if (res) {
586 res = -EREMOTEIO;
587 }
JP Abgrall8a932722011-07-13 19:17:35 -0700588 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900589 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700590 return res;
591}
592
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900593int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700594
595 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700596
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900597 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000598 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700599 return -1;
600 }
Luke Huang19b49c52018-10-22 12:12:05 +0900601
602 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900603 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900604 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700605 return res;
606}
607
608int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900609 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000610 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700611 return -1;
612 }
613 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000614 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700615 return -1;
616 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900617 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700618}
619
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900620int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900621 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700622}
623
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900624int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700625 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900626 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800627 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700628 }
629
JP Abgrall8a932722011-07-13 19:17:35 -0700630 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000631 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800632 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700633 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900634 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700635
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900636 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000637 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800638 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700639 }
640
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900641 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700642}
643
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900644int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700645 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900646 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800647 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700648 }
649
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900650 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700651
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900652 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900653 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800654 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700655 }
656
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900657 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700658}
659
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900660int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
661 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700662 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700663
JP Abgrall69261cb2014-06-19 18:35:24 -0700664 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900665 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800666 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700667 }
668
JP Abgrall8a932722011-07-13 19:17:35 -0700669 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000670 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800671 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700672 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900673
674 std::string alertName = costName + "Alert";
675 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700676 if (*alertBytes) {
677 res = updateQuota(alertName, *alertBytes);
678 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900679 std::vector<std::string> commands = {
680 "*filter\n",
681 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
682 "COMMIT\n"
683 };
684 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
685 if (res) {
686 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800687 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900688 }
JP Abgrall8a932722011-07-13 19:17:35 -0700689 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900690 if (res == 0) {
691 *alertBytes = bytes;
692 }
JP Abgrall8a932722011-07-13 19:17:35 -0700693 return res;
694}
695
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900696int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700697 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900698 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800699 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700700 }
701
JP Abgrall8a932722011-07-13 19:17:35 -0700702 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900703 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800704 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700705 }
706
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900707 std::string alertName = costName + "Alert";
708 std::string chainName = "bw_costly_" + costName;
709 std::vector<std::string> commands = {
710 "*filter\n",
711 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
712 "COMMIT\n"
713 };
714 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
715 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800716 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900717 }
JP Abgrall8a932722011-07-13 19:17:35 -0700718
719 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900720 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700721}
JP Abgralldb7da582011-09-18 12:57:32 -0700722
JP Abgrall0e540ec2013-08-26 15:13:10 -0700723void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900724 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
725 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700726
727 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900728 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
729 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700730 return;
731 }
732 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900733 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700734}
735
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900736void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
737 std::stringstream stream(ruleList);
738 std::string rule;
739 std::vector<std::string> clearCommands = { "*filter" };
740 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700741
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900742 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
743 while (std::getline(stream, rule, '\n')) {
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800744 if (!StartsWith(rule, NEW_CHAIN_COMMAND)) continue;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900745 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
746 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
747
Maciej Żenczykowski6857fa52021-01-14 13:41:17 -0800748 if (!StartsWith(chainName, "bw_costly_") || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700749 continue;
750 }
751
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900752 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700753 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900754 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700755 }
756 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900757
758 if (clearCommands.size() == 1) {
759 // No rules found.
760 return;
761 }
762
763 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900764 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700765}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900766
767inline const char *BandwidthController::opToString(IptOp op) {
768 switch (op) {
769 case IptOpInsert:
770 return "-I";
771 case IptOpDelete:
772 return "-D";
773 }
774}
775
776inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
777 /*
778 * Must be careful what one rejects with, as upper layer protocols will just
779 * keep on hammering the device until the number of retries are done.
780 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
781 */
782 switch (jumpHandling) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900783 case IptJumpReject:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800784 return " -j REJECT";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900785 case IptJumpReturn:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800786 return " -j RETURN";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900787 }
788}