blob: cf0cb8c089bd77dd4a0f9f7270b69b86f6035dc8 [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>
Rom Lemarchand14150212013-01-24 10:01:04 -080051#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070052
Joel Scherpelz01cc5492017-06-16 10:45:14 +090053#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070054#include "BandwidthController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070055#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090056#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080057#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090058#include "NetdConstants.h"
Sam Mortimer797848d2020-04-03 23:49:28 -070059#include "RouteController.h"
Chenbo Feng95892f32018-06-07 14:52:02 -070060#include "TrafficController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070061#include "bpf/BpfUtils.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070062
JP Abgralldb7da582011-09-18 12:57:32 -070063/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090064#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090065const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
66const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
67const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
68const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
69const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +090070const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090071
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090072auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090073
Joel Scherpelzd59526a2017-06-28 16:24:09 +090074using android::base::Join;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090075using android::base::StringAppendF;
76using android::base::StringPrintf;
Luke Huange64fa382018-07-24 16:38:22 +080077using android::net::FirewallController;
Chenbo Feng95892f32018-06-07 14:52:02 -070078using android::net::gCtls;
Chenbo Feng95892f32018-06-07 14:52:02 -070079using android::netdutils::Status;
Luke Huange64fa382018-07-24 16:38:22 +080080using android::netdutils::StatusOr;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090081using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090082
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090083namespace {
84
85const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090086const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090087
Joel Scherpelzbcad6612017-05-30 10:55:11 +090088const char NAUGHTY_CHAIN[] = "bw_penalty_box";
89const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070090
Sam Mortimer797848d2020-04-03 23:49:28 -070091// Must match RESTRICT_USECASE_* definitions in
92// frameworks/base/services/core/java/com/android/server/NetworkManagementService.java
93const std::array<std::string, UID_MAX_IF_BLACKLIST> APP_RESTRICT_USE_CASES =
94 { "data", "vpn", "wlan" };
95
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070096/**
97 * Some comments about the rules:
98 * * Ordering
99 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -0700100 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -0700101 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -0700102 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700103 *
104 * * global quota vs per interface quota
105 * - global quota for all costly interfaces uses a single costly chain:
106 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700107 * iptables -N bw_costly_shared
108 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
109 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
110 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700111 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700112 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900113 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900114 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700115 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700116 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700117 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
118 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700119 *
120 * - quota per interface. This is achieve by having "costly" chains per quota.
121 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700122 * iptables -N bw_costly_iface0
123 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
124 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
125 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700126 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700127 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700128 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900129 * * Penalty box, happy box and data saver.
130 * - bw_penalty box is a blacklist of apps that are rejected.
131 * - bw_happy_box is a whitelist of apps. It always includes all system apps
132 * - bw_data_saver implements data usage restrictions.
133 * - Via the UI the user can add and remove apps from the whitelist and
134 * blacklist, and turn on/off data saver.
135 * - The blacklist takes precedence over the whitelist and the whitelist
136 * takes precedence over data saver.
137 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700138 * * bw_penalty_box handling:
139 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900140 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700141 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700142 * --jump REJECT --reject-with icmp-port-unreachable
143 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700144 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900145 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700146 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700147 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700148 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900149 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900150 * * bw_data_saver handling:
151 * - The bw_data_saver comes after the happy box.
152 * Enable data saver:
153 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
154 * Disable data saver:
155 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700156 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900157
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900158const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Chenbo Feng703798e2018-06-15 17:07:59 -0700159const std::string HAPPY_BOX_MATCH_WHITELIST_COMMAND =
160 StringPrintf("-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
161const std::string BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND = StringPrintf(
162 "-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
163const std::string BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND = StringPrintf(
164 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900165
166static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900167 /*
168 * Cleanup rules.
169 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
170 * to allow coexistance.
171 */
172 "*filter",
173 ":bw_INPUT -",
174 ":bw_OUTPUT -",
175 ":bw_FORWARD -",
176 ":bw_happy_box -",
177 ":bw_penalty_box -",
178 ":bw_data_saver -",
179 ":bw_costly_shared -",
180 ":bw_global_alert -",
181 "COMMIT",
182 "*raw",
183 ":bw_raw_PREROUTING -",
184 "COMMIT",
185 "*mangle",
186 ":bw_mangle_POSTROUTING -",
187 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700188
Benedict Wongb9baf262017-12-03 15:43:08 -0800189static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
190
191/**
192 * Basic commands for creation of hooks into data accounting and data boxes.
193 *
194 * Included in these commands are rules to prevent the double-counting of IPsec
195 * packets. The general overview is as follows:
196 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
197 * completely accurate, and count only the outer packet. As such, the inner
198 * packet must be ignored, which is done through the use of two rules: use
199 * of the policy module (for tunnel mode), and VTI interface checks (for
200 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
201 * ipsec*
202 * > Outbound UID billing can always be done with the outer packets, due to the
203 * ability to always find the correct UID (based on the skb->sk). As such,
204 * the inner packets should be ignored based on the policy module, or the
205 * output interface if a VTI (ipsec+)
206 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
207 * opened the encap socket, and as such, should be billed as early as
208 * possible (for transport mode; tunnel mode usage should be billed to
209 * sending/receiving application). Due to the inner packet being
210 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
211 * has to be applied to prevent counting a second time.
212 * > Inbound ESP has no socket, and as such must be accounted later. ESP
213 * protocol packets are skipped via a blanket rule.
214 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
215 * ignore rule in the input chain would actually break the INPUT chain;
216 * Those rules are designed to ignore inner packets, and in the tunnel
217 * mode UDP, or any ESP case, we would not have billed the outer packet.
218 *
219 * See go/ipsec-data-accounting for more information.
220 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800221
Chenbo Feng95892f32018-06-07 14:52:02 -0700222const std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
Chenbo Feng5ed17992018-03-13 21:30:49 -0700223 const std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700224 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900225
226 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700227 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
228 "-A bw_INPUT -p esp -j RETURN",
229 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
230 uidBillingMask),
Chenbo Feng44c0f442018-07-10 16:54:30 -0700231 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700232 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900233
Luke Huangae038f82018-11-05 11:17:31 +0900234 "-A bw_OUTPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700235 // Prevents IPSec double counting (Tunnel mode and Transport mode,
236 // respectively)
237 "-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
238 "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700239 useBpf ? "" : "-A bw_OUTPUT -m owner --socket-exists",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900240
Chenbo Feng703798e2018-06-15 17:07:59 -0700241 "-A bw_costly_shared --jump bw_penalty_box",
242 useBpf ? BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND : "",
243 "-A bw_penalty_box --jump bw_happy_box", "-A bw_happy_box --jump bw_data_saver",
244 "-A bw_data_saver -j RETURN",
245 useBpf ? BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND : HAPPY_BOX_MATCH_WHITELIST_COMMAND,
246 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700247
Chenbo Feng703798e2018-06-15 17:07:59 -0700248 "*raw",
249 // Prevents IPSec double counting (Tunnel mode and Transport mode,
250 // respectively)
251 "-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN",
252 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Chenbo Feng703798e2018-06-15 17:07:59 -0700253 useBpf ? StringPrintf("-A bw_raw_PREROUTING -m bpf --object-pinned %s",
254 XT_BPF_INGRESS_PROG_PATH)
Chenbo Feng44c0f442018-07-10 16:54:30 -0700255 : "-A bw_raw_PREROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700256 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700257
Chenbo Feng703798e2018-06-15 17:07:59 -0700258 "*mangle",
259 // Prevents IPSec double counting (Tunnel mode and Transport mode,
260 // respectively)
261 "-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
262 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700263 useBpf ? "" : "-A bw_mangle_POSTROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700264 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x",
265 uidBillingMask), // Clear the mark before sending this packet
266 useBpf ? StringPrintf("-A bw_mangle_POSTROUTING -m bpf --object-pinned %s",
267 XT_BPF_EGRESS_PROG_PATH)
268 : "",
269 COMMIT_AND_CLOSE};
Chenbo Feng5ed17992018-03-13 21:30:49 -0700270 return ipt_basic_accounting_commands;
271}
272
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900273
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900274std::vector<std::string> toStrVec(int num, const char* const strs[]) {
275 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900276}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900277
278} // namespace
279
Chenbo Feng44c0f442018-07-10 16:54:30 -0700280void BandwidthController::setBpfEnabled(bool isEnabled) {
281 mBpfSupported = isEnabled;
Chenbo Fenga121e202018-03-19 11:51:54 -0700282}
283
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900284BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700285}
286
JP Abgrall0e540ec2013-08-26 15:13:10 -0700287void BandwidthController::flushCleanTables(bool doClean) {
288 /* Flush and remove the bw_costly_<iface> tables */
289 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700290
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900291 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900292 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700293}
JP Abgrall0031cea2012-04-17 16:38:23 -0700294
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900295int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700296 /* flush+clean is allowed to fail */
297 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700298 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700299}
300
Luke Huangf44a3c12018-09-07 12:10:12 +0800301int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700302 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900303 mSharedQuotaIfaces.clear();
304 mQuotaIfaces.clear();
305 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900306 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700307
Uldiniad9748e942018-03-01 08:54:00 -0500308 mRestrictAppsOnInterface.clear();
309
JP Abgrall0e540ec2013-08-26 15:13:10 -0700310 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700311
Chenbo Feng95892f32018-06-07 14:52:02 -0700312 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900313 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700314}
315
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900316int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700317
318 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700319 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700320}
321
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900322std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
323 std::string cmd;
324 const char *chainName = "bw_data_saver";
325 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
326 std::string criticalCommands = enable ?
327 FirewallController::makeCriticalCommands(target, chainName) : "";
328 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900329 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900330 ":%s -\n"
331 "%s"
332 "-A %s%s\n"
333 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
334 return cmd;
335}
336
337int BandwidthController::enableDataSaver(bool enable) {
338 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
339 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
340 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900341}
342
Luke Huang531f5d32018-08-03 15:19:05 +0800343// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900344int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900345 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
346 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700347}
348
Luke Huang531f5d32018-08-03 15:19:05 +0800349// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900350int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900351 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
352 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700353}
354
Luke Huang531f5d32018-08-03 15:19:05 +0800355// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900356int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900357 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
358 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700359}
360
Luke Huang531f5d32018-08-03 15:19:05 +0800361// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900362int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900363 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
364 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700365}
366
Luke Huang531f5d32018-08-03 15:19:05 +0800367int BandwidthController::addNaughtyApps(const std::vector<std::string>& appStrUid) {
368 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpInsert);
369}
370
371int BandwidthController::removeNaughtyApps(const std::vector<std::string>& appStrUid) {
372 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpDelete);
373}
374
375int BandwidthController::addNiceApps(const std::vector<std::string>& appStrUid) {
376 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpInsert);
377}
378
379int BandwidthController::removeNiceApps(const std::vector<std::string>& appStrUid) {
380 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpDelete);
381}
382
Uldiniad9748e942018-03-01 08:54:00 -0500383int BandwidthController::addRestrictAppsOnInterface(const std::string& usecase,
384 const std::string& iface,
385 const std::vector<std::string>& appStrUid) {
386 return manipulateRestrictAppsInOut(usecase, iface, appStrUid, IptOpInsert);
387}
388
389int BandwidthController::removeRestrictAppsOnInterface(const std::string& usecase,
390 const std::string& iface,
391 const std::vector<std::string>& appStrUid) {
392 return manipulateRestrictAppsInOut(usecase, iface, appStrUid, IptOpDelete);
393}
394
Sam Mortimer797848d2020-04-03 23:49:28 -0700395
396int BandwidthController::appsOnInterfaceAccounting(const std::string& usecase,
397 const std::vector<std::string>& appStrUids,
398 IptOp op, bool update) {
Uldiniad9748e942018-03-01 08:54:00 -0500399 /* Keep separate per app uid vectors for each usecase (vpn, wlan etc) */
400 std::vector<int>& restrictAppUids = mRestrictAppsOnInterface[usecase];
401
Sam Mortimer797848d2020-04-03 23:49:28 -0700402 // Check our local per uid restriction accounting and update if requested.
Uldiniad9748e942018-03-01 08:54:00 -0500403 for (const auto& appStrUid : appStrUids) {
404 int uid = std::stoi(appStrUid, nullptr, 0);
405 auto it = std::find(restrictAppUids.begin(), restrictAppUids.end(), uid);
406 bool found = (it != restrictAppUids.end());
407 if (op == IptOpDelete) {
408 if (!found) {
409 ALOGE("No such appUid %d to remove", uid);
410 return -1;
411 }
Sam Mortimer797848d2020-04-03 23:49:28 -0700412 if (update) {
413 restrictAppUids.erase(it);
414 }
Uldiniad9748e942018-03-01 08:54:00 -0500415 } else {
Sam Mortimer797848d2020-04-03 23:49:28 -0700416 if (found) {
Uldiniad9748e942018-03-01 08:54:00 -0500417 ALOGE("appUid %d exists already", uid);
418 return -1;
419 }
Sam Mortimer797848d2020-04-03 23:49:28 -0700420 if (update) {
421 restrictAppUids.push_back(uid);
422 }
Uldiniad9748e942018-03-01 08:54:00 -0500423 }
424 }
Sam Mortimer797848d2020-04-03 23:49:28 -0700425 return 0;
426}
427
428int BandwidthController::manipulateRestrictAppsInOut(const std::string& usecase,
429 const std::string& iface,
430 const std::vector<std::string>& appStrUids,
431 IptOp op) {
432 int ret;
433 std::string chain;
434
435 // Sanity check inputs against our local restriction accounting
436 ret = appsOnInterfaceAccounting(usecase, appStrUids, op, false /* update */);
437 if (ret != 0) {
438 return ret;
439 }
440
441 if (mBpfSupported) {
442 // map use case to blacklist interface slot
443 int blacklistSlot = -1;
444 for (unsigned int i = 0; i < APP_RESTRICT_USE_CASES.size(); i++) {
445 if (usecase == APP_RESTRICT_USE_CASES[i]) {
446 blacklistSlot = (int) i;
447 break;
448 }
449 }
450 if (blacklistSlot < 0) {
451 ALOGE("unknown app restrict usecase: %s", usecase.c_str());
452 return -1;
453 }
454 Status status;
455 if (op == IptOpInsert) {
456 uint32_t ifaceIdx = android::net::RouteController::getIfIndex(iface.c_str());
457 if (!ifaceIdx) {
458 // Interface is unknown or down.
459 return -ENETDOWN;
460 }
461 status = gCtls->trafficCtrl.addUidInterfaceBlacklist(blacklistSlot, ifaceIdx,
462 appStrUids);
463 } else {
464 status = gCtls->trafficCtrl.removeUidInterfaceBlacklist(blacklistSlot, appStrUids);
465 }
466 if (!isOk(status)) {
467 ALOGE("unable to update Bandwidth interface rule: %s", toString(status).c_str());
468 return status.code();
469 }
470 } else { // !mBpfSupported
471 // Use iptables if BPF is not supported
472 chain = StringPrintf("INPUT -i %s", iface.c_str());
473 ret = manipulateSpecialApps(appStrUids, chain, IptJumpReject, op);
474 if (ret != 0) {
475 return ret;
476 }
477 chain = StringPrintf("OUTPUT -o %s", iface.c_str());
478 ret = manipulateSpecialApps(appStrUids, chain, IptJumpReject, op);
479 if (ret != 0) {
480 return ret;
481 }
482 }
483
484 return appsOnInterfaceAccounting(usecase, appStrUids, op, true /* update */);
Uldiniad9748e942018-03-01 08:54:00 -0500485}
486
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900487int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
488 const std::string& chain, IptJumpOp jumpHandling,
489 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700490 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700491 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
492 if (!isOk(status)) {
493 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700494 }
495 return status.code();
496 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900497 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900498 for (const auto& appStrUid : appStrUids) {
499 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
500 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700501 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900502 StringAppendF(&cmd, "COMMIT\n");
503 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700504}
505
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900506int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700507 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700508 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900509 constexpr char cost[] = "shared";
510 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700511
JP Abgrall8a932722011-07-13 19:17:35 -0700512 if (!maxBytes) {
513 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000514 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700515 return -1;
516 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700517 if (!isIfaceName(iface))
518 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700519
520 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900521 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700522 }
523
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900524 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700525
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900526 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900527 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
528 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900529 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900530 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
531 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900532 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900533 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
534 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900535 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900536 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
537 " --name %s --jump REJECT",
538 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900539 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900540 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900541
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900542 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900543 if (res) {
544 ALOGE("Failed set quota rule");
545 removeInterfaceSharedQuota(iface);
546 return -1;
547 }
548 mSharedQuotaBytes = maxBytes;
549 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700550 }
551
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900552 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900553 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700554 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900555 ALOGE("Failed update quota for %s", cost);
556 removeInterfaceSharedQuota(iface);
557 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700558 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900559 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700560 }
561 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700562}
563
JP Abgrall8a932722011-07-13 19:17:35 -0700564/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900565int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900566 constexpr char cost[] = "shared";
567 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700568
JP Abgrall69261cb2014-06-19 18:35:24 -0700569 if (!isIfaceName(iface))
570 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700571
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900572 auto it = mSharedQuotaIfaces.find(iface);
573
574 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900575 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700576 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700577 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700578
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900579 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900580 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900581 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
582 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900583 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900584 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
585 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900586 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900587 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
588 " --name %s --jump REJECT",
589 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700590 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900591 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900592
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900593 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
594 ALOGE("Failed to remove shared quota on %s", iface.c_str());
595 return -1;
596 }
597
598 int res = 0;
599 mSharedQuotaIfaces.erase(it);
600 if (mSharedQuotaIfaces.empty()) {
601 mSharedQuotaBytes = 0;
602 if (mSharedAlertBytes) {
603 res = removeSharedAlert();
604 if (res == 0) {
605 mSharedAlertBytes = 0;
606 }
607 }
608 }
609
610 return res;
611
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700612}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700613
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900614int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900615 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700616
Luke Huang531f5d32018-08-03 15:19:05 +0800617 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700618
JP Abgrall8a932722011-07-13 19:17:35 -0700619 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000620 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800621 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700622 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700623 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700624 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700625 }
626
JP Abgrall0dad7c22011-06-24 11:58:14 -0700627 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900628 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700629
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900630 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800631 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900632 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900633 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800634 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700635 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900636 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900637 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700638 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700639
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900640 const std::string chain = "bw_costly_" + iface;
641 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
642 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900643 "*filter",
644 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900645 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
646 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
647 chain.c_str()),
648 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
649 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900650 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900651 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
652 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
653 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900654 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900655 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900656 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900657 ALOGE("Failed set quota rule");
658 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800659 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900660 }
661
662 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
663 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700664}
665
JP Abgrall8a932722011-07-13 19:17:35 -0700666int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
667 return getInterfaceQuota("shared", bytes);
668}
669
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900670int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900671 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900672 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700673
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900674 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700675
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900676 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
677 if (!isOk(file)) {
678 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700679 return -1;
680 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900681 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
682 if (!isOk(rv)) {
683 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
684 return -1;
685 }
686 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
687 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700688}
689
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900690int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800691 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700692
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900693 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700694
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900695 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900696 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800697 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700698 }
699
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900700 const std::string chain = "bw_costly_" + iface;
701 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900702 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900703 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
704 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900705 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900706 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
707 StringPrintf("-F %s", chain.c_str()),
708 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900709 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900710 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900711
712 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700713
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900714 if (res == 0) {
715 mQuotaIfaces.erase(it);
716 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700717
Luke Huang531f5d32018-08-03 15:19:05 +0800718 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700719}
JP Abgrall8a932722011-07-13 19:17:35 -0700720
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900721int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900722 const auto& sys = android::netdutils::sSyscalls.get();
723 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700724
JP Abgrall69261cb2014-06-19 18:35:24 -0700725 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900726 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800727 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700728 }
729
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900730 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
731 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800732 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900733 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800734 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700735 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900736 // TODO: should we propagate this error?
737 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700738 return 0;
739}
740
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900741int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
742 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900743 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900744 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700745
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900746 // TODO: consider using an alternate template for the delete that does not include the --quota
747 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900748
Luke Huangae038f82018-11-05 11:17:31 +0900749 /*
750 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
751 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
752 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
753 */
754 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900755 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900756 StringAppendF(&alertQuotaCmd, "COMMIT\n");
757
758 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700759}
760
761int BandwidthController::setGlobalAlert(int64_t bytes) {
762 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700763
764 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000765 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800766 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700767 }
Luke Huang19b49c52018-10-22 12:12:05 +0900768
769 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900770 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700771 res = updateQuota(alertName, bytes);
772 } else {
773 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800774 if (res) {
775 res = -EREMOTEIO;
776 }
JP Abgrall8a932722011-07-13 19:17:35 -0700777 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900778 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700779 return res;
780}
781
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900782int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700783
784 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700785
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900786 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000787 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700788 return -1;
789 }
Luke Huang19b49c52018-10-22 12:12:05 +0900790
791 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900792 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900793 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700794 return res;
795}
796
797int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900798 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000799 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700800 return -1;
801 }
802 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000803 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700804 return -1;
805 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900806 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700807}
808
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900809int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900810 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700811}
812
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900813int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700814 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900815 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800816 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700817 }
818
JP Abgrall8a932722011-07-13 19:17:35 -0700819 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000820 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800821 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700822 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900823 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700824
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900825 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000826 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800827 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700828 }
829
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900830 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700831}
832
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900833int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700834 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900835 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800836 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700837 }
838
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900839 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700840
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900841 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900842 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800843 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700844 }
845
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900846 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700847}
848
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900849int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
850 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700851 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700852
JP Abgrall69261cb2014-06-19 18:35:24 -0700853 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900854 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800855 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700856 }
857
JP Abgrall8a932722011-07-13 19:17:35 -0700858 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000859 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800860 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700861 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900862
863 std::string alertName = costName + "Alert";
864 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700865 if (*alertBytes) {
866 res = updateQuota(alertName, *alertBytes);
867 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900868 std::vector<std::string> commands = {
869 "*filter\n",
870 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
871 "COMMIT\n"
872 };
873 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
874 if (res) {
875 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800876 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900877 }
JP Abgrall8a932722011-07-13 19:17:35 -0700878 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900879 if (res == 0) {
880 *alertBytes = bytes;
881 }
JP Abgrall8a932722011-07-13 19:17:35 -0700882 return res;
883}
884
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900885int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700886 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900887 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800888 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700889 }
890
JP Abgrall8a932722011-07-13 19:17:35 -0700891 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900892 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800893 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700894 }
895
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900896 std::string alertName = costName + "Alert";
897 std::string chainName = "bw_costly_" + costName;
898 std::vector<std::string> commands = {
899 "*filter\n",
900 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
901 "COMMIT\n"
902 };
903 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
904 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800905 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900906 }
JP Abgrall8a932722011-07-13 19:17:35 -0700907
908 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900909 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700910}
JP Abgralldb7da582011-09-18 12:57:32 -0700911
JP Abgrall0e540ec2013-08-26 15:13:10 -0700912void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900913 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
914 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700915
916 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900917 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
918 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700919 return;
920 }
921 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900922 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700923}
924
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900925void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
926 std::stringstream stream(ruleList);
927 std::string rule;
928 std::vector<std::string> clearCommands = { "*filter" };
929 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700930
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900931 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
932 while (std::getline(stream, rule, '\n')) {
933 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
934 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
935 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
936
937 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700938 continue;
939 }
940
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900941 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700942 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900943 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700944 }
945 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900946
947 if (clearCommands.size() == 1) {
948 // No rules found.
949 return;
950 }
951
952 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900953 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700954}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900955
956inline const char *BandwidthController::opToString(IptOp op) {
957 switch (op) {
958 case IptOpInsert:
959 return "-I";
960 case IptOpDelete:
961 return "-D";
962 }
963}
964
965inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
966 /*
967 * Must be careful what one rejects with, as upper layer protocols will just
968 * keep on hammering the device until the number of retries are done.
969 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
970 */
971 switch (jumpHandling) {
972 case IptJumpNoAdd:
973 return "";
974 case IptJumpReject:
975 return " --jump REJECT";
976 case IptJumpReturn:
977 return " --jump RETURN";
978 }
979}