blob: d74602701617de09dd437c0c09da510d4711392c [file] [log] [blame]
JP Abgrall4a5f5ca2011-06-15 18:37:39 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
JP Abgralle4788732013-07-02 20:28:45 -070017// #define LOG_NDEBUG 0
JP Abgralldb7da582011-09-18 12:57:32 -070018
19/*
20 * The CommandListener, FrameworkListener don't allow for
21 * multiple calls in parallel to reach the BandwidthController.
22 * If they ever were to allow it, then netd/ would need some tweaking.
23 */
24
Joel Scherpelz01cc5492017-06-16 10:45:14 +090025#include <ctype.h>
JP Abgrall8a932722011-07-13 19:17:35 -070026#include <errno.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070027#include <fcntl.h>
JP Abgralldb7da582011-09-18 12:57:32 -070028#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070029#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070030#include <string.h>
Joel Scherpelz01cc5492017-06-16 10:45:14 +090031#include <string>
32#include <vector>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070033
Matthew Leach2a54d962013-01-14 15:07:12 +000034#define __STDC_FORMAT_MACROS 1
35#include <inttypes.h>
36
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070037#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <sys/wait.h>
41
42#include <linux/netlink.h>
43#include <linux/rtnetlink.h>
44#include <linux/pkt_sched.h>
45
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090046#include "android-base/stringprintf.h"
Lorenzo Colitti13debb82016-03-27 17:46:30 +090047#include "android-base/strings.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070048#define LOG_TAG "BandwidthController"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080050#include <log/log.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070051
Joel Scherpelz01cc5492017-06-16 10:45:14 +090052#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070053#include "BandwidthController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070054#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090055#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080056#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090057#include "NetdConstants.h"
Chenbo Feng95892f32018-06-07 14:52:02 -070058#include "TrafficController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070059#include "bpf/BpfUtils.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070060
JP Abgralldb7da582011-09-18 12:57:32 -070061/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090062#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090063const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
64const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
65const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
66const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
67const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +090068const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090069
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090070auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090071
Joel Scherpelzd59526a2017-06-28 16:24:09 +090072using android::base::Join;
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;
Chenbo Feng95892f32018-06-07 14:52:02 -070076using android::net::gCtls;
Chenbo Feng95892f32018-06-07 14:52:02 -070077using android::netdutils::Status;
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
Joel Scherpelzbcad6612017-05-30 10:55:11 +090086const char NAUGHTY_CHAIN[] = "bw_penalty_box";
87const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070088
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070089/**
90 * Some comments about the rules:
91 * * Ordering
92 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080093 * E.g. "-I bw_INPUT -i rmnet0 -j costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070094 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070095 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070096 *
97 * * global quota vs per interface quota
98 * - global quota for all costly interfaces uses a single costly chain:
99 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700100 * iptables -N bw_costly_shared
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800101 * iptables -I bw_INPUT -i iface0 -j bw_costly_shared
102 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_shared
JP Abgrall7e51cde2013-07-03 13:33:05 -0700103 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800104 * -j REJECT --reject-with icmp-net-prohibited
105 * iptables -A bw_costly_shared -j bw_penalty_box
106 * iptables -A bw_penalty_box -j bw_happy_box
107 * iptables -A bw_happy_box -j bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700108 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700109 * . adding a new iface to this, E.g.:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800110 * iptables -I bw_INPUT -i iface1 -j bw_costly_shared
111 * iptables -I bw_OUTPUT -o iface1 -j bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700112 *
113 * - quota per interface. This is achieve by having "costly" chains per quota.
114 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700115 * iptables -N bw_costly_iface0
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800116 * iptables -I bw_INPUT -i iface0 -j bw_costly_iface0
117 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_iface0
JP Abgrall7e51cde2013-07-03 13:33:05 -0700118 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800119 * -j REJECT --reject-with icmp-port-unreachable
120 * iptables -A bw_costly_iface0 -j bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700121 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900122 * * Penalty box, happy box and data saver.
123 * - bw_penalty box is a blacklist of apps that are rejected.
124 * - bw_happy_box is a whitelist of apps. It always includes all system apps
125 * - bw_data_saver implements data usage restrictions.
126 * - Via the UI the user can add and remove apps from the whitelist and
127 * blacklist, and turn on/off data saver.
128 * - The blacklist takes precedence over the whitelist and the whitelist
129 * takes precedence over data saver.
130 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700131 * * bw_penalty_box handling:
132 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900133 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700134 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800135 * -j REJECT --reject-with icmp-port-unreachable
JP Abgralle4788732013-07-02 20:28:45 -0700136 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700137 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900138 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700139 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700140 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800141 * -j RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900142 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900143 * * bw_data_saver handling:
144 * - The bw_data_saver comes after the happy box.
145 * Enable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800146 * iptables -R 1 bw_data_saver -j REJECT --reject-with icmp-port-unreachable
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900147 * Disable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800148 * iptables -R 1 bw_data_saver -j RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700149 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900150
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900151const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Chenbo Feng703798e2018-06-15 17:07:59 -0700152const std::string HAPPY_BOX_MATCH_WHITELIST_COMMAND =
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800153 StringPrintf("-I bw_happy_box -m owner --uid-owner %d-%d -j RETURN", 0, MAX_SYSTEM_UID);
Chenbo Feng703798e2018-06-15 17:07:59 -0700154const std::string BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND = StringPrintf(
155 "-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
156const std::string BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND = StringPrintf(
157 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900158
159static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900160 /*
161 * Cleanup rules.
162 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
163 * to allow coexistance.
164 */
165 "*filter",
166 ":bw_INPUT -",
167 ":bw_OUTPUT -",
168 ":bw_FORWARD -",
169 ":bw_happy_box -",
170 ":bw_penalty_box -",
171 ":bw_data_saver -",
172 ":bw_costly_shared -",
173 ":bw_global_alert -",
174 "COMMIT",
175 "*raw",
176 ":bw_raw_PREROUTING -",
177 "COMMIT",
178 "*mangle",
179 ":bw_mangle_POSTROUTING -",
180 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700181
Benedict Wongb9baf262017-12-03 15:43:08 -0800182static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
183
184/**
185 * Basic commands for creation of hooks into data accounting and data boxes.
186 *
187 * Included in these commands are rules to prevent the double-counting of IPsec
188 * packets. The general overview is as follows:
189 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
190 * completely accurate, and count only the outer packet. As such, the inner
191 * packet must be ignored, which is done through the use of two rules: use
192 * of the policy module (for tunnel mode), and VTI interface checks (for
193 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
194 * ipsec*
195 * > Outbound UID billing can always be done with the outer packets, due to the
196 * ability to always find the correct UID (based on the skb->sk). As such,
197 * the inner packets should be ignored based on the policy module, or the
198 * output interface if a VTI (ipsec+)
199 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
200 * opened the encap socket, and as such, should be billed as early as
201 * possible (for transport mode; tunnel mode usage should be billed to
202 * sending/receiving application). Due to the inner packet being
203 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
204 * has to be applied to prevent counting a second time.
205 * > Inbound ESP has no socket, and as such must be accounted later. ESP
206 * protocol packets are skipped via a blanket rule.
207 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
208 * ignore rule in the input chain would actually break the INPUT chain;
209 * Those rules are designed to ignore inner packets, and in the tunnel
210 * mode UDP, or any ESP case, we would not have billed the outer packet.
211 *
212 * See go/ipsec-data-accounting for more information.
213 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800214
Treehugger Robotf580db22020-04-30 00:42:33 +0000215std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
216 std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700217 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900218
219 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700220 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
221 "-A bw_INPUT -p esp -j RETURN",
222 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
223 uidBillingMask),
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000224 // This is ingress application UID xt_qtaguid (pre-ebpf) accounting,
225 // for bpf this is handled out of cgroup hooks instead.
Chenbo Feng44c0f442018-07-10 16:54:30 -0700226 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700227 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900228
Luke Huangae038f82018-11-05 11:17:31 +0900229 "-A bw_OUTPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700230 // Prevents IPSec double counting (Tunnel mode and Transport mode,
231 // respectively)
Maciej Żenczykowskiece434a2020-04-22 09:43:39 +0000232 ("-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700233 "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000234 // This is egress application UID xt_qtaguid (pre-ebpf) accounting,
235 // for bpf this is handled out of cgroup hooks instead.
Chenbo Feng44c0f442018-07-10 16:54:30 -0700236 useBpf ? "" : "-A bw_OUTPUT -m owner --socket-exists",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900237
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800238 "-A bw_costly_shared -j bw_penalty_box",
Chenbo Feng703798e2018-06-15 17:07:59 -0700239 useBpf ? BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND : "",
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800240 "-A bw_penalty_box -j bw_happy_box", "-A bw_happy_box -j bw_data_saver",
Chenbo Feng703798e2018-06-15 17:07:59 -0700241 "-A bw_data_saver -j RETURN",
242 useBpf ? BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND : HAPPY_BOX_MATCH_WHITELIST_COMMAND,
243 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700244
Chenbo Feng703798e2018-06-15 17:07:59 -0700245 "*raw",
246 // Prevents IPSec double counting (Tunnel mode and Transport mode,
247 // respectively)
Maciej Żenczykowskiece434a2020-04-22 09:43:39 +0000248 ("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700249 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000250 // This is ingress interface accounting. There is no need to do anything specific
251 // for 464xlat here, because we only ever account 464xlat traffic on the clat
252 // interface and later correct for overhead (+20 bytes/packet).
253 //
254 // Note: eBPF offloaded packets never hit base interface's ip6tables, and non
255 // offloaded packets (which when using xt_qtaguid means all packets, because
256 // clat eBPF offload does not work on xt_qtaguid devices) are dropped in
257 // clat_raw_PREROUTING.
258 //
259 // Hence we will never double count and additional corrections are not needed.
260 // We can simply take the sum of base and stacked (+20B/pkt) interface counts.
Maciej Żenczykowskic5d4a2f2020-05-25 19:50:51 +0000261 useBpf ? "-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH
Chenbo Feng44c0f442018-07-10 16:54:30 -0700262 : "-A bw_raw_PREROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700263 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700264
Chenbo Feng703798e2018-06-15 17:07:59 -0700265 "*mangle",
266 // Prevents IPSec double counting (Tunnel mode and Transport mode,
267 // respectively)
Maciej Żenczykowskiece434a2020-04-22 09:43:39 +0000268 ("-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700269 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000270 // Clear the uid billing done (egress) mark before sending this packet
271 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
272 // Packets from the clat daemon have already been counted on egress through the
273 // stacked v4-* interface.
Maciej Żenczykowskie408f882020-05-28 03:22:23 +0000274 "-A bw_mangle_POSTROUTING -m owner --uid-owner clat -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000275 // This is egress interface accounting: we account 464xlat traffic only on
276 // the clat interface (as offloaded packets never hit base interface's ip6tables)
277 // and later sum base and stacked with overhead (+20B/pkt) in higher layers
Maciej Żenczykowskic5d4a2f2020-05-25 19:50:51 +0000278 useBpf ? "-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000279 : "-A bw_mangle_POSTROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700280 COMMIT_AND_CLOSE};
Chenbo Feng5ed17992018-03-13 21:30:49 -0700281 return ipt_basic_accounting_commands;
282}
283
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900284std::vector<std::string> toStrVec(int num, const char* const strs[]) {
285 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900286}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900287
288} // namespace
289
Chenbo Feng44c0f442018-07-10 16:54:30 -0700290void BandwidthController::setBpfEnabled(bool isEnabled) {
291 mBpfSupported = isEnabled;
Chenbo Fenga121e202018-03-19 11:51:54 -0700292}
293
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900294BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700295}
296
JP Abgrall0e540ec2013-08-26 15:13:10 -0700297void BandwidthController::flushCleanTables(bool doClean) {
298 /* Flush and remove the bw_costly_<iface> tables */
299 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700300
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900301 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900302 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700303}
JP Abgrall0031cea2012-04-17 16:38:23 -0700304
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900305int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700306 /* flush+clean is allowed to fail */
307 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700308 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700309}
310
Luke Huangf44a3c12018-09-07 12:10:12 +0800311int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700312 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900313 mSharedQuotaIfaces.clear();
314 mQuotaIfaces.clear();
315 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900316 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700317
JP Abgrall0e540ec2013-08-26 15:13:10 -0700318 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700319
Chenbo Feng95892f32018-06-07 14:52:02 -0700320 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900321 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700322}
323
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900324int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700325
326 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700327 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700328}
329
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900330std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
331 std::string cmd;
332 const char *chainName = "bw_data_saver";
333 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
334 std::string criticalCommands = enable ?
335 FirewallController::makeCriticalCommands(target, chainName) : "";
336 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900337 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900338 ":%s -\n"
339 "%s"
340 "-A %s%s\n"
341 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
342 return cmd;
343}
344
345int BandwidthController::enableDataSaver(bool enable) {
346 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
347 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
348 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900349}
350
Luke Huang531f5d32018-08-03 15:19:05 +0800351// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900352int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900353 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
354 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700355}
356
Luke Huang531f5d32018-08-03 15:19:05 +0800357// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900358int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900359 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
360 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700361}
362
Luke Huang531f5d32018-08-03 15:19:05 +0800363// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900364int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900365 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
366 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700367}
368
Luke Huang531f5d32018-08-03 15:19:05 +0800369// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900370int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900371 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
372 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700373}
374
Luke Huang531f5d32018-08-03 15:19:05 +0800375int BandwidthController::addNaughtyApps(const std::vector<std::string>& appStrUid) {
376 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpInsert);
377}
378
379int BandwidthController::removeNaughtyApps(const std::vector<std::string>& appStrUid) {
380 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpDelete);
381}
382
383int BandwidthController::addNiceApps(const std::vector<std::string>& appStrUid) {
384 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpInsert);
385}
386
387int BandwidthController::removeNiceApps(const std::vector<std::string>& appStrUid) {
388 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpDelete);
389}
390
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900391int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
392 const std::string& chain, IptJumpOp jumpHandling,
393 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700394 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700395 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
396 if (!isOk(status)) {
397 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700398 }
399 return status.code();
400 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900401 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900402 for (const auto& appStrUid : appStrUids) {
403 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
404 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700405 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900406 StringAppendF(&cmd, "COMMIT\n");
407 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700408}
409
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900410int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700411 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700412 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900413 constexpr char cost[] = "shared";
414 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700415
JP Abgrall8a932722011-07-13 19:17:35 -0700416 if (!maxBytes) {
417 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000418 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700419 return -1;
420 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700421 if (!isIfaceName(iface))
422 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700423
424 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900425 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700426 }
427
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900428 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700429
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900430 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900431 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
432 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800433 "*filter",
434 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain),
435 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(), chain),
436 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain),
437 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900438 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900439 if (mSharedQuotaIfaces.empty()) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800440 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900441 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900442 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900443 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900444
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900445 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900446 if (res) {
447 ALOGE("Failed set quota rule");
448 removeInterfaceSharedQuota(iface);
449 return -1;
450 }
451 mSharedQuotaBytes = maxBytes;
452 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700453 }
454
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900455 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900456 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700457 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900458 ALOGE("Failed update quota for %s", cost);
459 removeInterfaceSharedQuota(iface);
460 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700461 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900462 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700463 }
464 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700465}
466
JP Abgrall8a932722011-07-13 19:17:35 -0700467/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900468int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900469 constexpr char cost[] = "shared";
470 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700471
JP Abgrall69261cb2014-06-19 18:35:24 -0700472 if (!isIfaceName(iface))
473 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700474
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900475 auto it = mSharedQuotaIfaces.find(iface);
476
477 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900478 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700479 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700480 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700481
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900482 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800483 "*filter",
484 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain),
485 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain),
486 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain),
487 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900488 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900489 if (mSharedQuotaIfaces.size() == 1) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800490 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900491 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700492 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900493 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900494
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900495 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
496 ALOGE("Failed to remove shared quota on %s", iface.c_str());
497 return -1;
498 }
499
500 int res = 0;
501 mSharedQuotaIfaces.erase(it);
502 if (mSharedQuotaIfaces.empty()) {
503 mSharedQuotaBytes = 0;
504 if (mSharedAlertBytes) {
505 res = removeSharedAlert();
506 if (res == 0) {
507 mSharedAlertBytes = 0;
508 }
509 }
510 }
511
512 return res;
513
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700514}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700515
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900516int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900517 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700518
Luke Huang531f5d32018-08-03 15:19:05 +0800519 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700520
JP Abgrall8a932722011-07-13 19:17:35 -0700521 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000522 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800523 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700524 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700525 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700526 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700527 }
528
JP Abgrall0dad7c22011-06-24 11:58:14 -0700529 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900530 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700531
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900532 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800533 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900534 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900535 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800536 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700537 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900538 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900539 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700540 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700541
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900542 const std::string chain = "bw_costly_" + iface;
543 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
544 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800545 "*filter",
546 StringPrintf(":%s -", chain.c_str()),
547 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
548 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain.c_str()),
549 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(),
550 chain.c_str()),
551 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
552 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
553 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT", chain.c_str(),
554 maxBytes, cost.c_str()),
555 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900556 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900557 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900558 ALOGE("Failed set quota rule");
559 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800560 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900561 }
562
563 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
564 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700565}
566
JP Abgrall8a932722011-07-13 19:17:35 -0700567int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
568 return getInterfaceQuota("shared", bytes);
569}
570
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900571int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900572 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900573 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700574
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900575 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700576
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900577 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
578 if (!isOk(file)) {
579 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700580 return -1;
581 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900582 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
583 if (!isOk(rv)) {
584 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
585 return -1;
586 }
587 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
588 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700589}
590
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900591int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800592 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700593
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900594 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700595
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900596 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900597 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800598 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700599 }
600
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900601 const std::string chain = "bw_costly_" + iface;
602 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800603 "*filter",
604 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain.c_str()),
605 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain.c_str()),
606 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
607 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
608 StringPrintf("-F %s", chain.c_str()),
609 StringPrintf("-X %s", chain.c_str()),
610 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900611 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900612
613 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700614
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900615 if (res == 0) {
616 mQuotaIfaces.erase(it);
617 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700618
Luke Huang531f5d32018-08-03 15:19:05 +0800619 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700620}
JP Abgrall8a932722011-07-13 19:17:35 -0700621
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900622int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900623 const auto& sys = android::netdutils::sSyscalls.get();
624 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700625
JP Abgrall69261cb2014-06-19 18:35:24 -0700626 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900627 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800628 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700629 }
630
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900631 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
632 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800633 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900634 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800635 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700636 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900637 // TODO: should we propagate this error?
638 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700639 return 0;
640}
641
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900642int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
643 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900644 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900645 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700646
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900647 // TODO: consider using an alternate template for the delete that does not include the --quota
648 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900649
Luke Huangae038f82018-11-05 11:17:31 +0900650 /*
651 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
652 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
653 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
654 */
655 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900656 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900657 StringAppendF(&alertQuotaCmd, "COMMIT\n");
658
659 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700660}
661
662int BandwidthController::setGlobalAlert(int64_t bytes) {
663 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700664
665 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000666 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800667 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700668 }
Luke Huang19b49c52018-10-22 12:12:05 +0900669
670 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900671 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700672 res = updateQuota(alertName, bytes);
673 } else {
674 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800675 if (res) {
676 res = -EREMOTEIO;
677 }
JP Abgrall8a932722011-07-13 19:17:35 -0700678 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900679 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700680 return res;
681}
682
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900683int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700684
685 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700686
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900687 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000688 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700689 return -1;
690 }
Luke Huang19b49c52018-10-22 12:12:05 +0900691
692 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900693 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900694 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700695 return res;
696}
697
698int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900699 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000700 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700701 return -1;
702 }
703 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000704 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700705 return -1;
706 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900707 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700708}
709
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900710int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900711 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700712}
713
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900714int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700715 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900716 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800717 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700718 }
719
JP Abgrall8a932722011-07-13 19:17:35 -0700720 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000721 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800722 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700723 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900724 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700725
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900726 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000727 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800728 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700729 }
730
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900731 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700732}
733
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900734int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700735 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900736 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800737 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700738 }
739
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900740 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700741
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900742 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900743 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800744 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700745 }
746
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900747 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700748}
749
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900750int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
751 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700752 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700753
JP Abgrall69261cb2014-06-19 18:35:24 -0700754 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900755 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800756 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700757 }
758
JP Abgrall8a932722011-07-13 19:17:35 -0700759 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000760 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800761 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700762 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900763
764 std::string alertName = costName + "Alert";
765 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700766 if (*alertBytes) {
767 res = updateQuota(alertName, *alertBytes);
768 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900769 std::vector<std::string> commands = {
770 "*filter\n",
771 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
772 "COMMIT\n"
773 };
774 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
775 if (res) {
776 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800777 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900778 }
JP Abgrall8a932722011-07-13 19:17:35 -0700779 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900780 if (res == 0) {
781 *alertBytes = bytes;
782 }
JP Abgrall8a932722011-07-13 19:17:35 -0700783 return res;
784}
785
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900786int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700787 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900788 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800789 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700790 }
791
JP Abgrall8a932722011-07-13 19:17:35 -0700792 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900793 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800794 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700795 }
796
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900797 std::string alertName = costName + "Alert";
798 std::string chainName = "bw_costly_" + costName;
799 std::vector<std::string> commands = {
800 "*filter\n",
801 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
802 "COMMIT\n"
803 };
804 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
805 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800806 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900807 }
JP Abgrall8a932722011-07-13 19:17:35 -0700808
809 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900810 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700811}
JP Abgralldb7da582011-09-18 12:57:32 -0700812
JP Abgrall0e540ec2013-08-26 15:13:10 -0700813void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900814 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
815 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700816
817 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900818 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
819 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700820 return;
821 }
822 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900823 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700824}
825
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900826void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
827 std::stringstream stream(ruleList);
828 std::string rule;
829 std::vector<std::string> clearCommands = { "*filter" };
830 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700831
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900832 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
833 while (std::getline(stream, rule, '\n')) {
834 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
835 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
836 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
837
838 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700839 continue;
840 }
841
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900842 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700843 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900844 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700845 }
846 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900847
848 if (clearCommands.size() == 1) {
849 // No rules found.
850 return;
851 }
852
853 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900854 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700855}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900856
857inline const char *BandwidthController::opToString(IptOp op) {
858 switch (op) {
859 case IptOpInsert:
860 return "-I";
861 case IptOpDelete:
862 return "-D";
863 }
864}
865
866inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
867 /*
868 * Must be careful what one rejects with, as upper layer protocols will just
869 * keep on hammering the device until the number of retries are done.
870 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
871 */
872 switch (jumpHandling) {
873 case IptJumpNoAdd:
874 return "";
875 case IptJumpReject:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800876 return " -j REJECT";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900877 case IptJumpReturn:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800878 return " -j RETURN";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900879 }
880}