blob: f13488946cd2eff7fed147db1812da4868d681e8 [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"
Uldiniadb198ec92018-03-01 08:54:00 -050058#include "RouteController.h"
Chenbo Feng95892f32018-06-07 14:52:02 -070059#include "TrafficController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070060#include "bpf/BpfUtils.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070061
JP Abgralldb7da582011-09-18 12:57:32 -070062/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090063#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090064const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
65const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
66const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
67const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
68const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +090069const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090070
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090071auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090072
Joel Scherpelzd59526a2017-06-28 16:24:09 +090073using android::base::Join;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090074using android::base::StringAppendF;
75using android::base::StringPrintf;
Luke Huange64fa382018-07-24 16:38:22 +080076using android::net::FirewallController;
Chenbo Feng95892f32018-06-07 14:52:02 -070077using android::net::gCtls;
Chenbo Feng95892f32018-06-07 14:52:02 -070078using android::netdutils::Status;
Luke Huange64fa382018-07-24 16:38:22 +080079using android::netdutils::StatusOr;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090080using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090081
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090082namespace {
83
84const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090085const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090086
Joel Scherpelzbcad6612017-05-30 10:55:11 +090087const char NAUGHTY_CHAIN[] = "bw_penalty_box";
88const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070089
Uldiniadb198ec92018-03-01 08:54:00 -050090// Must match RESTRICT_USECASE_* definitions in
91// frameworks/base/services/core/java/com/android/server/NetworkManagementService.java
92const std::array<std::string, UID_MAX_IF_BLACKLIST> APP_RESTRICT_USE_CASES =
93 { "cellular", "vpn", "wifi" };
94
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070095/**
96 * Some comments about the rules:
97 * * Ordering
98 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -080099 * E.g. "-I bw_INPUT -i rmnet0 -j costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -0700100 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -0700101 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700102 *
103 * * global quota vs per interface quota
104 * - global quota for all costly interfaces uses a single costly chain:
105 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700106 * iptables -N bw_costly_shared
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800107 * iptables -I bw_INPUT -i iface0 -j bw_costly_shared
108 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_shared
JP Abgrall7e51cde2013-07-03 13:33:05 -0700109 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800110 * -j REJECT --reject-with icmp-net-prohibited
111 * iptables -A bw_costly_shared -j bw_penalty_box
112 * iptables -A bw_penalty_box -j bw_happy_box
113 * iptables -A bw_happy_box -j bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700114 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700115 * . adding a new iface to this, E.g.:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800116 * iptables -I bw_INPUT -i iface1 -j bw_costly_shared
117 * iptables -I bw_OUTPUT -o iface1 -j bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700118 *
119 * - quota per interface. This is achieve by having "costly" chains per quota.
120 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700121 * iptables -N bw_costly_iface0
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800122 * iptables -I bw_INPUT -i iface0 -j bw_costly_iface0
123 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_iface0
JP Abgrall7e51cde2013-07-03 13:33:05 -0700124 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800125 * -j REJECT --reject-with icmp-port-unreachable
126 * iptables -A bw_costly_iface0 -j bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700127 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900128 * * Penalty box, happy box and data saver.
129 * - bw_penalty box is a blacklist of apps that are rejected.
130 * - bw_happy_box is a whitelist of apps. It always includes all system apps
131 * - bw_data_saver implements data usage restrictions.
132 * - Via the UI the user can add and remove apps from the whitelist and
133 * blacklist, and turn on/off data saver.
134 * - The blacklist takes precedence over the whitelist and the whitelist
135 * takes precedence over data saver.
136 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700137 * * bw_penalty_box handling:
138 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900139 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700140 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800141 * -j REJECT --reject-with icmp-port-unreachable
JP Abgralle4788732013-07-02 20:28:45 -0700142 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700143 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900144 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700145 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700146 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800147 * -j RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900148 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900149 * * bw_data_saver handling:
150 * - The bw_data_saver comes after the happy box.
151 * Enable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800152 * iptables -R 1 bw_data_saver -j REJECT --reject-with icmp-port-unreachable
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900153 * Disable data saver:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800154 * iptables -R 1 bw_data_saver -j RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700155 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900156
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900157const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Chenbo Feng703798e2018-06-15 17:07:59 -0700158const std::string HAPPY_BOX_MATCH_WHITELIST_COMMAND =
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800159 StringPrintf("-I bw_happy_box -m owner --uid-owner %d-%d -j RETURN", 0, MAX_SYSTEM_UID);
Chenbo Feng703798e2018-06-15 17:07:59 -0700160const std::string BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND = StringPrintf(
161 "-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
162const std::string BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND = StringPrintf(
163 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900164
165static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900166 /*
167 * Cleanup rules.
168 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
169 * to allow coexistance.
170 */
171 "*filter",
172 ":bw_INPUT -",
173 ":bw_OUTPUT -",
174 ":bw_FORWARD -",
175 ":bw_happy_box -",
176 ":bw_penalty_box -",
177 ":bw_data_saver -",
178 ":bw_costly_shared -",
179 ":bw_global_alert -",
180 "COMMIT",
181 "*raw",
182 ":bw_raw_PREROUTING -",
183 "COMMIT",
184 "*mangle",
185 ":bw_mangle_POSTROUTING -",
186 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700187
Benedict Wongb9baf262017-12-03 15:43:08 -0800188static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
189
190/**
191 * Basic commands for creation of hooks into data accounting and data boxes.
192 *
193 * Included in these commands are rules to prevent the double-counting of IPsec
194 * packets. The general overview is as follows:
195 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
196 * completely accurate, and count only the outer packet. As such, the inner
197 * packet must be ignored, which is done through the use of two rules: use
198 * of the policy module (for tunnel mode), and VTI interface checks (for
199 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
200 * ipsec*
201 * > Outbound UID billing can always be done with the outer packets, due to the
202 * ability to always find the correct UID (based on the skb->sk). As such,
203 * the inner packets should be ignored based on the policy module, or the
204 * output interface if a VTI (ipsec+)
205 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
206 * opened the encap socket, and as such, should be billed as early as
207 * possible (for transport mode; tunnel mode usage should be billed to
208 * sending/receiving application). Due to the inner packet being
209 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
210 * has to be applied to prevent counting a second time.
211 * > Inbound ESP has no socket, and as such must be accounted later. ESP
212 * protocol packets are skipped via a blanket rule.
213 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
214 * ignore rule in the input chain would actually break the INPUT chain;
215 * Those rules are designed to ignore inner packets, and in the tunnel
216 * mode UDP, or any ESP case, we would not have billed the outer packet.
217 *
218 * See go/ipsec-data-accounting for more information.
219 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800220
Treehugger Robotf580db22020-04-30 00:42:33 +0000221std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
222 std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700223 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900224
225 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700226 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
227 "-A bw_INPUT -p esp -j RETURN",
228 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
229 uidBillingMask),
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000230 // This is ingress application UID xt_qtaguid (pre-ebpf) accounting,
231 // for bpf this is handled out of cgroup hooks instead.
Chenbo Feng44c0f442018-07-10 16:54:30 -0700232 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700233 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900234
Luke Huangae038f82018-11-05 11:17:31 +0900235 "-A bw_OUTPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700236 // Prevents IPSec double counting (Tunnel mode and Transport mode,
237 // respectively)
Maciej Żenczykowskied20ec32020-05-28 03:22:28 +0000238 useBpf ? "" : "-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
239 useBpf ? "" : "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
240 // Don't count clat traffic, as it has already been counted (and subject to
241 // costly / happy_box / data_saver / penalty_box etc. based on the real UID)
242 // on the stacked interface.
243 useBpf ? "" : "-A bw_OUTPUT -m owner --uid-owner clat -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000244 // This is egress application UID xt_qtaguid (pre-ebpf) accounting,
245 // for bpf this is handled out of cgroup hooks instead.
Chenbo Feng44c0f442018-07-10 16:54:30 -0700246 useBpf ? "" : "-A bw_OUTPUT -m owner --socket-exists",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900247
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800248 "-A bw_costly_shared -j bw_penalty_box",
Chenbo Feng703798e2018-06-15 17:07:59 -0700249 useBpf ? BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND : "",
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800250 "-A bw_penalty_box -j bw_happy_box", "-A bw_happy_box -j bw_data_saver",
Chenbo Feng703798e2018-06-15 17:07:59 -0700251 "-A bw_data_saver -j RETURN",
252 useBpf ? BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND : HAPPY_BOX_MATCH_WHITELIST_COMMAND,
253 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700254
Chenbo Feng703798e2018-06-15 17:07:59 -0700255 "*raw",
256 // Prevents IPSec double counting (Tunnel mode and Transport mode,
257 // respectively)
Maciej Żenczykowskiece434a2020-04-22 09:43:39 +0000258 ("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700259 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000260 // This is ingress interface accounting. There is no need to do anything specific
261 // for 464xlat here, because we only ever account 464xlat traffic on the clat
262 // interface and later correct for overhead (+20 bytes/packet).
263 //
264 // Note: eBPF offloaded packets never hit base interface's ip6tables, and non
265 // offloaded packets (which when using xt_qtaguid means all packets, because
266 // clat eBPF offload does not work on xt_qtaguid devices) are dropped in
267 // clat_raw_PREROUTING.
268 //
269 // Hence we will never double count and additional corrections are not needed.
270 // We can simply take the sum of base and stacked (+20B/pkt) interface counts.
Maciej Żenczykowskic5d4a2f2020-05-25 19:50:51 +0000271 useBpf ? "-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH
Chenbo Feng44c0f442018-07-10 16:54:30 -0700272 : "-A bw_raw_PREROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700273 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700274
Chenbo Feng703798e2018-06-15 17:07:59 -0700275 "*mangle",
276 // Prevents IPSec double counting (Tunnel mode and Transport mode,
277 // respectively)
Maciej Żenczykowskiece434a2020-04-22 09:43:39 +0000278 ("-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
Chenbo Feng703798e2018-06-15 17:07:59 -0700279 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000280 // Clear the uid billing done (egress) mark before sending this packet
281 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
282 // Packets from the clat daemon have already been counted on egress through the
283 // stacked v4-* interface.
Maciej Żenczykowskie408f882020-05-28 03:22:23 +0000284 "-A bw_mangle_POSTROUTING -m owner --uid-owner clat -j RETURN",
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000285 // This is egress interface accounting: we account 464xlat traffic only on
286 // the clat interface (as offloaded packets never hit base interface's ip6tables)
287 // and later sum base and stacked with overhead (+20B/pkt) in higher layers
Maciej Żenczykowskic5d4a2f2020-05-25 19:50:51 +0000288 useBpf ? "-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH
Maciej Żenczykowski75d75902020-05-27 23:03:41 +0000289 : "-A bw_mangle_POSTROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700290 COMMIT_AND_CLOSE};
Chenbo Feng5ed17992018-03-13 21:30:49 -0700291 return ipt_basic_accounting_commands;
292}
293
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900294std::vector<std::string> toStrVec(int num, const char* const strs[]) {
295 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900296}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900297
298} // namespace
299
Chenbo Feng44c0f442018-07-10 16:54:30 -0700300void BandwidthController::setBpfEnabled(bool isEnabled) {
301 mBpfSupported = isEnabled;
Chenbo Fenga121e202018-03-19 11:51:54 -0700302}
303
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900304BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700305}
306
JP Abgrall0e540ec2013-08-26 15:13:10 -0700307void BandwidthController::flushCleanTables(bool doClean) {
308 /* Flush and remove the bw_costly_<iface> tables */
309 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700310
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900311 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900312 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700313}
JP Abgrall0031cea2012-04-17 16:38:23 -0700314
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900315int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700316 /* flush+clean is allowed to fail */
317 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700318 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700319}
320
Luke Huangf44a3c12018-09-07 12:10:12 +0800321int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700322 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900323 mSharedQuotaIfaces.clear();
324 mQuotaIfaces.clear();
325 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900326 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700327
Uldiniadb198ec92018-03-01 08:54:00 -0500328 mRestrictAppsOnInterface.clear();
329
JP Abgrall0e540ec2013-08-26 15:13:10 -0700330 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700331
Chenbo Feng95892f32018-06-07 14:52:02 -0700332 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900333 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700334}
335
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900336int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700337
338 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700339 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700340}
341
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900342std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
343 std::string cmd;
344 const char *chainName = "bw_data_saver";
345 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
346 std::string criticalCommands = enable ?
347 FirewallController::makeCriticalCommands(target, chainName) : "";
348 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900349 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900350 ":%s -\n"
351 "%s"
352 "-A %s%s\n"
353 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
354 return cmd;
355}
356
357int BandwidthController::enableDataSaver(bool enable) {
358 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
359 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
360 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900361}
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::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900365 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
366 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -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::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900371 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
372 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700373}
374
Luke Huang531f5d32018-08-03 15:19:05 +0800375// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900376int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900377 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
378 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700379}
380
Luke Huang531f5d32018-08-03 15:19:05 +0800381// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900382int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900383 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
384 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700385}
386
Luke Huang531f5d32018-08-03 15:19:05 +0800387int BandwidthController::addNaughtyApps(const std::vector<std::string>& appStrUid) {
388 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpInsert);
389}
390
391int BandwidthController::removeNaughtyApps(const std::vector<std::string>& appStrUid) {
392 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpDelete);
393}
394
395int BandwidthController::addNiceApps(const std::vector<std::string>& appStrUid) {
396 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpInsert);
397}
398
399int BandwidthController::removeNiceApps(const std::vector<std::string>& appStrUid) {
400 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpDelete);
401}
402
Uldiniadb198ec92018-03-01 08:54:00 -0500403int BandwidthController::addRestrictAppsOnInterface(const std::string& usecase,
404 const std::string& iface,
405 const std::vector<std::string>& appStrUid) {
406 return manipulateRestrictAppsInOut(usecase, iface, appStrUid, IptOpInsert);
407}
408
409int BandwidthController::removeRestrictAppsOnInterface(const std::string& usecase,
410 const std::string& iface,
411 const std::vector<std::string>& appStrUid) {
412 return manipulateRestrictAppsInOut(usecase, iface, appStrUid, IptOpDelete);
413}
414
415
416int BandwidthController::appsOnInterfaceAccounting(const std::string& usecase,
417 const std::vector<std::string>& appStrUids,
418 IptOp op, bool update) {
419 /* Keep separate per app uid vectors for each usecase (vpn, wifi etc) */
420 std::vector<int>& restrictAppUids = mRestrictAppsOnInterface[usecase];
421
422 // Check our local per uid restriction accounting and update if requested.
423 for (const auto& appStrUid : appStrUids) {
424 int uid = std::stoi(appStrUid, nullptr, 0);
425 auto it = std::find(restrictAppUids.begin(), restrictAppUids.end(), uid);
426 bool found = (it != restrictAppUids.end());
427 if (op == IptOpDelete) {
428 if (!found) {
429 ALOGE("No such appUid %d to remove", uid);
430 return -1;
431 }
432 if (update) {
433 restrictAppUids.erase(it);
434 }
435 } else {
436 if (found) {
437 ALOGE("appUid %d exists already", uid);
438 return -1;
439 }
440 if (update) {
441 restrictAppUids.push_back(uid);
442 }
443 }
444 }
445 return 0;
446}
447
448int BandwidthController::manipulateRestrictAppsInOut(const std::string& usecase,
449 const std::string& iface,
450 const std::vector<std::string>& appStrUids,
451 IptOp op) {
452 int ret;
453 std::string chain;
454
455 // Sanity check inputs against our local restriction accounting
456 ret = appsOnInterfaceAccounting(usecase, appStrUids, op, false /* update */);
457 if (ret != 0) {
458 return ret;
459 }
460
461 if (mBpfSupported) {
462 // map use case to blacklist interface slot
463 int blacklistSlot = -1;
464 for (unsigned int i = 0; i < APP_RESTRICT_USE_CASES.size(); i++) {
465 if (usecase == APP_RESTRICT_USE_CASES[i]) {
466 blacklistSlot = (int) i;
467 break;
468 }
469 }
470 if (blacklistSlot < 0) {
471 ALOGE("unknown app restrict usecase: %s", usecase.c_str());
472 return -1;
473 }
474 Status status;
475 if (op == IptOpInsert) {
476 uint32_t ifaceIdx = android::net::RouteController::getIfIndex(iface.c_str());
477 if (!ifaceIdx) {
478 // Interface is unknown or down.
479 return -ENETDOWN;
480 }
481 status = gCtls->trafficCtrl.addUidInterfaceBlacklist(blacklistSlot, ifaceIdx,
482 appStrUids);
483 } else {
484 status = gCtls->trafficCtrl.removeUidInterfaceBlacklist(blacklistSlot, appStrUids);
485 }
486 if (!isOk(status)) {
487 ALOGE("unable to update Bandwidth interface rule: %s", toString(status).c_str());
488 return status.code();
489 }
490 } else { // !mBpfSupported
491 // Use iptables if BPF is not supported
492 chain = StringPrintf("INPUT -i %s", iface.c_str());
493 ret = manipulateSpecialApps(appStrUids, chain, IptJumpReject, op);
494 if (ret != 0) {
495 return ret;
496 }
497 chain = StringPrintf("OUTPUT -o %s", iface.c_str());
498 ret = manipulateSpecialApps(appStrUids, chain, IptJumpReject, op);
499 if (ret != 0) {
500 return ret;
501 }
502 }
503
504 return appsOnInterfaceAccounting(usecase, appStrUids, op, true /* update */);
505}
506
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900507int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
508 const std::string& chain, IptJumpOp jumpHandling,
509 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700510 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700511 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
512 if (!isOk(status)) {
513 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700514 }
515 return status.code();
516 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900517 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900518 for (const auto& appStrUid : appStrUids) {
519 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
520 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700521 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900522 StringAppendF(&cmd, "COMMIT\n");
523 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700524}
525
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900526int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700527 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700528 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900529 constexpr char cost[] = "shared";
530 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700531
JP Abgrall8a932722011-07-13 19:17:35 -0700532 if (!maxBytes) {
533 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000534 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700535 return -1;
536 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700537 if (!isIfaceName(iface))
538 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700539
540 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900541 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700542 }
543
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900544 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700545
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900546 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900547 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
548 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800549 "*filter",
550 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain),
551 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(), chain),
552 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain),
553 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900554 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900555 if (mSharedQuotaIfaces.empty()) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800556 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900557 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900558 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900559 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900560
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900561 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900562 if (res) {
563 ALOGE("Failed set quota rule");
564 removeInterfaceSharedQuota(iface);
565 return -1;
566 }
567 mSharedQuotaBytes = maxBytes;
568 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700569 }
570
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900571 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900572 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700573 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900574 ALOGE("Failed update quota for %s", cost);
575 removeInterfaceSharedQuota(iface);
576 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700577 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900578 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700579 }
580 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700581}
582
JP Abgrall8a932722011-07-13 19:17:35 -0700583/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900584int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900585 constexpr char cost[] = "shared";
586 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700587
JP Abgrall69261cb2014-06-19 18:35:24 -0700588 if (!isIfaceName(iface))
589 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700590
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900591 auto it = mSharedQuotaIfaces.find(iface);
592
593 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900594 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700595 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700596 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700597
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900598 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800599 "*filter",
600 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain),
601 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain),
602 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain),
603 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900604 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900605 if (mSharedQuotaIfaces.size() == 1) {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800606 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64 " --name %s -j REJECT",
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900607 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700608 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900609 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900610
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900611 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
612 ALOGE("Failed to remove shared quota on %s", iface.c_str());
613 return -1;
614 }
615
616 int res = 0;
617 mSharedQuotaIfaces.erase(it);
618 if (mSharedQuotaIfaces.empty()) {
619 mSharedQuotaBytes = 0;
620 if (mSharedAlertBytes) {
621 res = removeSharedAlert();
622 if (res == 0) {
623 mSharedAlertBytes = 0;
624 }
625 }
626 }
627
628 return res;
629
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700630}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700631
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900632int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900633 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700634
Luke Huang531f5d32018-08-03 15:19:05 +0800635 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700636
JP Abgrall8a932722011-07-13 19:17:35 -0700637 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000638 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800639 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700640 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700641 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700642 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700643 }
644
JP Abgrall0dad7c22011-06-24 11:58:14 -0700645 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900646 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700647
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900648 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800649 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900650 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900651 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800652 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700653 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900654 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900655 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700656 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700657
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900658 const std::string chain = "bw_costly_" + iface;
659 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
660 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800661 "*filter",
662 StringPrintf(":%s -", chain.c_str()),
663 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
664 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain.c_str()),
665 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(),
666 chain.c_str()),
667 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
668 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
669 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT", chain.c_str(),
670 maxBytes, cost.c_str()),
671 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900672 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900673 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900674 ALOGE("Failed set quota rule");
675 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800676 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900677 }
678
679 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
680 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700681}
682
JP Abgrall8a932722011-07-13 19:17:35 -0700683int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
684 return getInterfaceQuota("shared", bytes);
685}
686
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900687int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900688 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900689 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700690
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900691 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700692
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900693 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
694 if (!isOk(file)) {
695 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700696 return -1;
697 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900698 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
699 if (!isOk(rv)) {
700 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
701 return -1;
702 }
703 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
704 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700705}
706
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900707int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800708 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700709
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900710 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700711
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900712 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900713 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800714 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700715 }
716
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900717 const std::string chain = "bw_costly_" + iface;
718 std::vector<std::string> cmds = {
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800719 "*filter",
720 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain.c_str()),
721 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain.c_str()),
722 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
723 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
724 StringPrintf("-F %s", chain.c_str()),
725 StringPrintf("-X %s", chain.c_str()),
726 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900727 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900728
729 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700730
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900731 if (res == 0) {
732 mQuotaIfaces.erase(it);
733 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700734
Luke Huang531f5d32018-08-03 15:19:05 +0800735 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700736}
JP Abgrall8a932722011-07-13 19:17:35 -0700737
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900738int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900739 const auto& sys = android::netdutils::sSyscalls.get();
740 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700741
JP Abgrall69261cb2014-06-19 18:35:24 -0700742 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900743 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800744 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700745 }
746
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900747 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
748 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800749 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900750 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800751 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700752 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900753 // TODO: should we propagate this error?
754 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700755 return 0;
756}
757
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900758int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
759 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900760 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900761 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700762
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900763 // TODO: consider using an alternate template for the delete that does not include the --quota
764 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900765
Luke Huangae038f82018-11-05 11:17:31 +0900766 /*
767 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
768 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
769 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
770 */
771 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900772 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900773 StringAppendF(&alertQuotaCmd, "COMMIT\n");
774
775 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700776}
777
778int BandwidthController::setGlobalAlert(int64_t bytes) {
779 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700780
781 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000782 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800783 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700784 }
Luke Huang19b49c52018-10-22 12:12:05 +0900785
786 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900787 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700788 res = updateQuota(alertName, bytes);
789 } else {
790 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800791 if (res) {
792 res = -EREMOTEIO;
793 }
JP Abgrall8a932722011-07-13 19:17:35 -0700794 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900795 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700796 return res;
797}
798
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900799int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700800
801 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700802
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900803 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000804 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700805 return -1;
806 }
Luke Huang19b49c52018-10-22 12:12:05 +0900807
808 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900809 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900810 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700811 return res;
812}
813
814int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900815 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000816 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700817 return -1;
818 }
819 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000820 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700821 return -1;
822 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900823 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700824}
825
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900826int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900827 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700828}
829
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900830int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700831 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900832 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800833 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700834 }
835
JP Abgrall8a932722011-07-13 19:17:35 -0700836 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000837 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800838 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700839 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900840 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700841
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900842 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000843 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800844 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700845 }
846
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900847 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700848}
849
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900850int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700851 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900852 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800853 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700854 }
855
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900856 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700857
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900858 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900859 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800860 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700861 }
862
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900863 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700864}
865
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900866int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
867 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700868 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700869
JP Abgrall69261cb2014-06-19 18:35:24 -0700870 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900871 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800872 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700873 }
874
JP Abgrall8a932722011-07-13 19:17:35 -0700875 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000876 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800877 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700878 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900879
880 std::string alertName = costName + "Alert";
881 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700882 if (*alertBytes) {
883 res = updateQuota(alertName, *alertBytes);
884 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900885 std::vector<std::string> commands = {
886 "*filter\n",
887 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
888 "COMMIT\n"
889 };
890 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
891 if (res) {
892 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800893 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900894 }
JP Abgrall8a932722011-07-13 19:17:35 -0700895 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900896 if (res == 0) {
897 *alertBytes = bytes;
898 }
JP Abgrall8a932722011-07-13 19:17:35 -0700899 return res;
900}
901
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900902int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700903 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900904 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800905 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700906 }
907
JP Abgrall8a932722011-07-13 19:17:35 -0700908 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900909 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800910 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700911 }
912
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900913 std::string alertName = costName + "Alert";
914 std::string chainName = "bw_costly_" + costName;
915 std::vector<std::string> commands = {
916 "*filter\n",
917 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
918 "COMMIT\n"
919 };
920 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
921 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800922 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900923 }
JP Abgrall8a932722011-07-13 19:17:35 -0700924
925 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900926 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700927}
JP Abgralldb7da582011-09-18 12:57:32 -0700928
JP Abgrall0e540ec2013-08-26 15:13:10 -0700929void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900930 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
931 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700932
933 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900934 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
935 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700936 return;
937 }
938 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900939 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700940}
941
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900942void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
943 std::stringstream stream(ruleList);
944 std::string rule;
945 std::vector<std::string> clearCommands = { "*filter" };
946 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700947
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900948 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
949 while (std::getline(stream, rule, '\n')) {
950 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
951 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
952 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
953
954 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700955 continue;
956 }
957
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900958 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700959 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900960 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700961 }
962 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900963
964 if (clearCommands.size() == 1) {
965 // No rules found.
966 return;
967 }
968
969 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900970 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700971}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900972
973inline const char *BandwidthController::opToString(IptOp op) {
974 switch (op) {
975 case IptOpInsert:
976 return "-I";
977 case IptOpDelete:
978 return "-D";
979 }
980}
981
982inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
983 /*
984 * Must be careful what one rejects with, as upper layer protocols will just
985 * keep on hammering the device until the number of retries are done.
986 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
987 */
988 switch (jumpHandling) {
989 case IptJumpNoAdd:
990 return "";
991 case IptJumpReject:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800992 return " -j REJECT";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900993 case IptJumpReturn:
Maciej Żenczykowskidec83c72019-12-24 15:27:14 -0800994 return " -j RETURN";
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900995 }
996}