blob: 7e9bff78934e89a471096126af5afead5954b380 [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"
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
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070090/**
91 * Some comments about the rules:
92 * * Ordering
93 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070094 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070095 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070096 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070097 *
98 * * global quota vs per interface quota
99 * - global quota for all costly interfaces uses a single costly chain:
100 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700101 * iptables -N bw_costly_shared
102 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
103 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
104 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700105 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700106 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900107 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900108 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700109 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700110 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700111 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
112 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700113 *
114 * - quota per interface. This is achieve by having "costly" chains per quota.
115 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700116 * iptables -N bw_costly_iface0
117 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
118 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
119 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700120 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700121 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700122 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900123 * * Penalty box, happy box and data saver.
124 * - bw_penalty box is a blacklist of apps that are rejected.
125 * - bw_happy_box is a whitelist of apps. It always includes all system apps
126 * - bw_data_saver implements data usage restrictions.
127 * - Via the UI the user can add and remove apps from the whitelist and
128 * blacklist, and turn on/off data saver.
129 * - The blacklist takes precedence over the whitelist and the whitelist
130 * takes precedence over data saver.
131 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700132 * * bw_penalty_box handling:
133 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900134 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700135 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700136 * --jump REJECT --reject-with icmp-port-unreachable
137 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700138 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900139 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700140 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700141 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700142 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900143 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900144 * * bw_data_saver handling:
145 * - The bw_data_saver comes after the happy box.
146 * Enable data saver:
147 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
148 * Disable data saver:
149 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700150 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900151
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900152const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Chenbo Feng703798e2018-06-15 17:07:59 -0700153const std::string HAPPY_BOX_MATCH_WHITELIST_COMMAND =
154 StringPrintf("-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
155const std::string BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND = StringPrintf(
156 "-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
157const std::string BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND = StringPrintf(
158 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900159
160static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
Luke Huangae038f82018-11-05 11:17:31 +0900161 /*
162 * Cleanup rules.
163 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
164 * to allow coexistance.
165 */
166 "*filter",
167 ":bw_INPUT -",
168 ":bw_OUTPUT -",
169 ":bw_FORWARD -",
170 ":bw_happy_box -",
171 ":bw_penalty_box -",
172 ":bw_data_saver -",
173 ":bw_costly_shared -",
174 ":bw_global_alert -",
175 "COMMIT",
176 "*raw",
177 ":bw_raw_PREROUTING -",
178 "COMMIT",
179 "*mangle",
180 ":bw_mangle_POSTROUTING -",
181 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700182
Benedict Wongb9baf262017-12-03 15:43:08 -0800183static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
184
185/**
186 * Basic commands for creation of hooks into data accounting and data boxes.
187 *
188 * Included in these commands are rules to prevent the double-counting of IPsec
189 * packets. The general overview is as follows:
190 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
191 * completely accurate, and count only the outer packet. As such, the inner
192 * packet must be ignored, which is done through the use of two rules: use
193 * of the policy module (for tunnel mode), and VTI interface checks (for
194 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
195 * ipsec*
196 * > Outbound UID billing can always be done with the outer packets, due to the
197 * ability to always find the correct UID (based on the skb->sk). As such,
198 * the inner packets should be ignored based on the policy module, or the
199 * output interface if a VTI (ipsec+)
200 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
201 * opened the encap socket, and as such, should be billed as early as
202 * possible (for transport mode; tunnel mode usage should be billed to
203 * sending/receiving application). Due to the inner packet being
204 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
205 * has to be applied to prevent counting a second time.
206 * > Inbound ESP has no socket, and as such must be accounted later. ESP
207 * protocol packets are skipped via a blanket rule.
208 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
209 * ignore rule in the input chain would actually break the INPUT chain;
210 * Those rules are designed to ignore inner packets, and in the tunnel
211 * mode UDP, or any ESP case, we would not have billed the outer packet.
212 *
213 * See go/ipsec-data-accounting for more information.
214 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800215
Chenbo Feng95892f32018-06-07 14:52:02 -0700216const std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
Chenbo Feng5ed17992018-03-13 21:30:49 -0700217 const std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700218 "*filter",
Luke Huangae038f82018-11-05 11:17:31 +0900219
220 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700221 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
222 "-A bw_INPUT -p esp -j RETURN",
223 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
224 uidBillingMask),
Chenbo Feng44c0f442018-07-10 16:54:30 -0700225 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700226 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900227
Luke Huangae038f82018-11-05 11:17:31 +0900228 "-A bw_OUTPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700229 // Prevents IPSec double counting (Tunnel mode and Transport mode,
230 // respectively)
231 "-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
232 "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700233 useBpf ? "" : "-A bw_OUTPUT -m owner --socket-exists",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900234
Chenbo Feng703798e2018-06-15 17:07:59 -0700235 "-A bw_costly_shared --jump bw_penalty_box",
236 useBpf ? BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND : "",
237 "-A bw_penalty_box --jump bw_happy_box", "-A bw_happy_box --jump bw_data_saver",
238 "-A bw_data_saver -j RETURN",
239 useBpf ? BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND : HAPPY_BOX_MATCH_WHITELIST_COMMAND,
240 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700241
Chenbo Feng703798e2018-06-15 17:07:59 -0700242 "*raw",
243 // Prevents IPSec double counting (Tunnel mode and Transport mode,
244 // respectively)
245 "-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN",
246 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Chenbo Feng703798e2018-06-15 17:07:59 -0700247 useBpf ? StringPrintf("-A bw_raw_PREROUTING -m bpf --object-pinned %s",
248 XT_BPF_INGRESS_PROG_PATH)
Chenbo Feng44c0f442018-07-10 16:54:30 -0700249 : "-A bw_raw_PREROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700250 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700251
Chenbo Feng703798e2018-06-15 17:07:59 -0700252 "*mangle",
253 // Prevents IPSec double counting (Tunnel mode and Transport mode,
254 // respectively)
255 "-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
256 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700257 useBpf ? "" : "-A bw_mangle_POSTROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700258 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x",
259 uidBillingMask), // Clear the mark before sending this packet
260 useBpf ? StringPrintf("-A bw_mangle_POSTROUTING -m bpf --object-pinned %s",
261 XT_BPF_EGRESS_PROG_PATH)
262 : "",
263 COMMIT_AND_CLOSE};
Chenbo Feng5ed17992018-03-13 21:30:49 -0700264 return ipt_basic_accounting_commands;
265}
266
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900267
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900268std::vector<std::string> toStrVec(int num, const char* const strs[]) {
269 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900270}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900271
272} // namespace
273
Chenbo Feng44c0f442018-07-10 16:54:30 -0700274void BandwidthController::setBpfEnabled(bool isEnabled) {
275 mBpfSupported = isEnabled;
Chenbo Fenga121e202018-03-19 11:51:54 -0700276}
277
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900278BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700279}
280
JP Abgrall0e540ec2013-08-26 15:13:10 -0700281void BandwidthController::flushCleanTables(bool doClean) {
282 /* Flush and remove the bw_costly_<iface> tables */
283 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700284
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900285 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900286 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700287}
JP Abgrall0031cea2012-04-17 16:38:23 -0700288
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900289int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700290 /* flush+clean is allowed to fail */
291 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700292 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700293}
294
Luke Huangf44a3c12018-09-07 12:10:12 +0800295int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700296 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900297 mSharedQuotaIfaces.clear();
298 mQuotaIfaces.clear();
299 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900300 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700301
JP Abgrall0e540ec2013-08-26 15:13:10 -0700302 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700303
Chenbo Feng95892f32018-06-07 14:52:02 -0700304 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900305 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700306}
307
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900308int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700309
310 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700311 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700312}
313
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900314std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
315 std::string cmd;
316 const char *chainName = "bw_data_saver";
317 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
318 std::string criticalCommands = enable ?
319 FirewallController::makeCriticalCommands(target, chainName) : "";
320 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900321 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900322 ":%s -\n"
323 "%s"
324 "-A %s%s\n"
325 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
326 return cmd;
327}
328
329int BandwidthController::enableDataSaver(bool enable) {
330 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
331 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
332 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900333}
334
Luke Huang531f5d32018-08-03 15:19:05 +0800335// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900336int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900337 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
338 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700339}
340
Luke Huang531f5d32018-08-03 15:19:05 +0800341// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900342int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900343 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
344 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700345}
346
Luke Huang531f5d32018-08-03 15:19:05 +0800347// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900348int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900349 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
350 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700351}
352
Luke Huang531f5d32018-08-03 15:19:05 +0800353// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900354int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900355 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
356 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700357}
358
Luke Huang531f5d32018-08-03 15:19:05 +0800359int BandwidthController::addNaughtyApps(const std::vector<std::string>& appStrUid) {
360 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpInsert);
361}
362
363int BandwidthController::removeNaughtyApps(const std::vector<std::string>& appStrUid) {
364 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpDelete);
365}
366
367int BandwidthController::addNiceApps(const std::vector<std::string>& appStrUid) {
368 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpInsert);
369}
370
371int BandwidthController::removeNiceApps(const std::vector<std::string>& appStrUid) {
372 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpDelete);
373}
374
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900375int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
376 const std::string& chain, IptJumpOp jumpHandling,
377 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700378 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700379 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
380 if (!isOk(status)) {
381 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700382 }
383 return status.code();
384 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900385 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900386 for (const auto& appStrUid : appStrUids) {
387 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
388 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700389 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900390 StringAppendF(&cmd, "COMMIT\n");
391 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700392}
393
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900394int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700395 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700396 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900397 constexpr char cost[] = "shared";
398 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700399
JP Abgrall8a932722011-07-13 19:17:35 -0700400 if (!maxBytes) {
401 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000402 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700403 return -1;
404 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700405 if (!isIfaceName(iface))
406 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700407
408 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900409 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700410 }
411
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900412 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700413
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900414 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900415 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
416 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900417 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900418 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
419 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900420 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900421 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
422 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900423 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900424 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
425 " --name %s --jump REJECT",
426 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900427 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900428 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900429
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900430 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900431 if (res) {
432 ALOGE("Failed set quota rule");
433 removeInterfaceSharedQuota(iface);
434 return -1;
435 }
436 mSharedQuotaBytes = maxBytes;
437 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700438 }
439
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900440 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900441 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700442 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900443 ALOGE("Failed update quota for %s", cost);
444 removeInterfaceSharedQuota(iface);
445 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700446 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900447 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700448 }
449 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700450}
451
JP Abgrall8a932722011-07-13 19:17:35 -0700452/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900453int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900454 constexpr char cost[] = "shared";
455 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700456
JP Abgrall69261cb2014-06-19 18:35:24 -0700457 if (!isIfaceName(iface))
458 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700459
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900460 auto it = mSharedQuotaIfaces.find(iface);
461
462 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900463 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700464 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700465 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700466
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900467 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900468 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900469 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
470 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900471 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900472 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
473 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900474 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900475 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
476 " --name %s --jump REJECT",
477 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700478 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900479 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900480
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900481 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
482 ALOGE("Failed to remove shared quota on %s", iface.c_str());
483 return -1;
484 }
485
486 int res = 0;
487 mSharedQuotaIfaces.erase(it);
488 if (mSharedQuotaIfaces.empty()) {
489 mSharedQuotaBytes = 0;
490 if (mSharedAlertBytes) {
491 res = removeSharedAlert();
492 if (res == 0) {
493 mSharedAlertBytes = 0;
494 }
495 }
496 }
497
498 return res;
499
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700500}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700501
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900502int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900503 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700504
Luke Huang531f5d32018-08-03 15:19:05 +0800505 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700506
JP Abgrall8a932722011-07-13 19:17:35 -0700507 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000508 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800509 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700510 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700511 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700512 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700513 }
514
JP Abgrall0dad7c22011-06-24 11:58:14 -0700515 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900516 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700517
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900518 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800519 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900520 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900521 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800522 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700523 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900524 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900525 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700526 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700527
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900528 const std::string chain = "bw_costly_" + iface;
529 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
530 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900531 "*filter",
532 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900533 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
534 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
535 chain.c_str()),
536 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
537 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900538 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900539 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
540 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
541 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900542 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900543 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900544 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900545 ALOGE("Failed set quota rule");
546 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800547 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900548 }
549
550 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
551 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700552}
553
JP Abgrall8a932722011-07-13 19:17:35 -0700554int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
555 return getInterfaceQuota("shared", bytes);
556}
557
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900558int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900559 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900560 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700561
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900562 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700563
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900564 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
565 if (!isOk(file)) {
566 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700567 return -1;
568 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900569 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
570 if (!isOk(rv)) {
571 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
572 return -1;
573 }
574 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
575 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700576}
577
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900578int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800579 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700580
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900581 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700582
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900583 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900584 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800585 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700586 }
587
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900588 const std::string chain = "bw_costly_" + iface;
589 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900590 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900591 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
592 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900593 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900594 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
595 StringPrintf("-F %s", chain.c_str()),
596 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900597 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900598 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900599
600 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700601
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900602 if (res == 0) {
603 mQuotaIfaces.erase(it);
604 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700605
Luke Huang531f5d32018-08-03 15:19:05 +0800606 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700607}
JP Abgrall8a932722011-07-13 19:17:35 -0700608
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900609int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900610 const auto& sys = android::netdutils::sSyscalls.get();
611 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700612
JP Abgrall69261cb2014-06-19 18:35:24 -0700613 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900614 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800615 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700616 }
617
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900618 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
619 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800620 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900621 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800622 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700623 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900624 // TODO: should we propagate this error?
625 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700626 return 0;
627}
628
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900629int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
630 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900631 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900632 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700633
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900634 // TODO: consider using an alternate template for the delete that does not include the --quota
635 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900636
Luke Huangae038f82018-11-05 11:17:31 +0900637 /*
638 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
639 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
640 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
641 */
642 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900643 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900644 StringAppendF(&alertQuotaCmd, "COMMIT\n");
645
646 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700647}
648
649int BandwidthController::setGlobalAlert(int64_t bytes) {
650 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700651
652 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000653 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800654 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700655 }
Luke Huang19b49c52018-10-22 12:12:05 +0900656
657 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900658 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700659 res = updateQuota(alertName, bytes);
660 } else {
661 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800662 if (res) {
663 res = -EREMOTEIO;
664 }
JP Abgrall8a932722011-07-13 19:17:35 -0700665 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900666 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700667 return res;
668}
669
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900670int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700671
672 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700673
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900674 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000675 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700676 return -1;
677 }
Luke Huang19b49c52018-10-22 12:12:05 +0900678
679 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900680 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900681 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700682 return res;
683}
684
685int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900686 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000687 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700688 return -1;
689 }
690 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000691 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700692 return -1;
693 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900694 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700695}
696
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900697int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900698 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700699}
700
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900701int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700702 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900703 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800704 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700705 }
706
JP Abgrall8a932722011-07-13 19:17:35 -0700707 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000708 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800709 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700710 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900711 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700712
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900713 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000714 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800715 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700716 }
717
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900718 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700719}
720
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900721int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700722 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900723 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800724 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700725 }
726
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900727 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700728
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900729 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900730 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800731 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700732 }
733
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900734 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700735}
736
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900737int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
738 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700739 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700740
JP Abgrall69261cb2014-06-19 18:35:24 -0700741 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900742 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800743 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700744 }
745
JP Abgrall8a932722011-07-13 19:17:35 -0700746 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000747 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800748 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700749 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900750
751 std::string alertName = costName + "Alert";
752 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700753 if (*alertBytes) {
754 res = updateQuota(alertName, *alertBytes);
755 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900756 std::vector<std::string> commands = {
757 "*filter\n",
758 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
759 "COMMIT\n"
760 };
761 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
762 if (res) {
763 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800764 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900765 }
JP Abgrall8a932722011-07-13 19:17:35 -0700766 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900767 if (res == 0) {
768 *alertBytes = bytes;
769 }
JP Abgrall8a932722011-07-13 19:17:35 -0700770 return res;
771}
772
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900773int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700774 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900775 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800776 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700777 }
778
JP Abgrall8a932722011-07-13 19:17:35 -0700779 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900780 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800781 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700782 }
783
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900784 std::string alertName = costName + "Alert";
785 std::string chainName = "bw_costly_" + costName;
786 std::vector<std::string> commands = {
787 "*filter\n",
788 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
789 "COMMIT\n"
790 };
791 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
792 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800793 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900794 }
JP Abgrall8a932722011-07-13 19:17:35 -0700795
796 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900797 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700798}
JP Abgralldb7da582011-09-18 12:57:32 -0700799
JP Abgrall0e540ec2013-08-26 15:13:10 -0700800void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900801 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
802 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700803
804 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900805 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
806 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700807 return;
808 }
809 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900810 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700811}
812
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900813void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
814 std::stringstream stream(ruleList);
815 std::string rule;
816 std::vector<std::string> clearCommands = { "*filter" };
817 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700818
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900819 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
820 while (std::getline(stream, rule, '\n')) {
821 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
822 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
823 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
824
825 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700826 continue;
827 }
828
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900829 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700830 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900831 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700832 }
833 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900834
835 if (clearCommands.size() == 1) {
836 // No rules found.
837 return;
838 }
839
840 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900841 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700842}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900843
844inline const char *BandwidthController::opToString(IptOp op) {
845 switch (op) {
846 case IptOpInsert:
847 return "-I";
848 case IptOpDelete:
849 return "-D";
850 }
851}
852
853inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
854 /*
855 * Must be careful what one rejects with, as upper layer protocols will just
856 * keep on hammering the device until the number of retries are done.
857 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
858 */
859 switch (jumpHandling) {
860 case IptJumpNoAdd:
861 return "";
862 case IptJumpReject:
863 return " --jump REJECT";
864 case IptJumpReturn:
865 return " --jump RETURN";
866 }
867}