blob: c85d1023b2d2afb1b405ceac7e1dc624dcd935f9 [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";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090069
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090070auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090071
Joel Scherpelzd59526a2017-06-28 16:24:09 +090072using android::base::Join;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090073using android::base::StringAppendF;
74using android::base::StringPrintf;
Chenbo Feng95892f32018-06-07 14:52:02 -070075using android::bpf::XT_BPF_BLACKLIST_PROG_PATH;
Chenbo Feng5ed17992018-03-13 21:30:49 -070076using android::bpf::XT_BPF_EGRESS_PROG_PATH;
77using android::bpf::XT_BPF_INGRESS_PROG_PATH;
Chenbo Feng95892f32018-06-07 14:52:02 -070078using android::bpf::XT_BPF_WHITELIST_PROG_PATH;
79using android::net::gCtls;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090080using android::netdutils::StatusOr;
Chenbo Feng95892f32018-06-07 14:52:02 -070081using android::netdutils::Status;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090082using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090083
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090084namespace {
85
86const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090087const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090088
Joel Scherpelzbcad6612017-05-30 10:55:11 +090089const char NAUGHTY_CHAIN[] = "bw_penalty_box";
90const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070091
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070092/**
93 * Some comments about the rules:
94 * * Ordering
95 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070096 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070097 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070098 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070099 *
100 * * global quota vs per interface quota
101 * - global quota for all costly interfaces uses a single costly chain:
102 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700103 * iptables -N bw_costly_shared
104 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
105 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
106 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700107 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700108 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900109 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900110 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700111 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700112 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700113 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
114 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700115 *
116 * - quota per interface. This is achieve by having "costly" chains per quota.
117 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700118 * iptables -N bw_costly_iface0
119 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
120 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
121 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700122 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700123 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700124 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900125 * * Penalty box, happy box and data saver.
126 * - bw_penalty box is a blacklist of apps that are rejected.
127 * - bw_happy_box is a whitelist of apps. It always includes all system apps
128 * - bw_data_saver implements data usage restrictions.
129 * - Via the UI the user can add and remove apps from the whitelist and
130 * blacklist, and turn on/off data saver.
131 * - The blacklist takes precedence over the whitelist and the whitelist
132 * takes precedence over data saver.
133 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700134 * * bw_penalty_box handling:
135 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900136 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700137 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700138 * --jump REJECT --reject-with icmp-port-unreachable
139 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700140 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900141 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700142 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700143 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700144 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900145 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900146 * * bw_data_saver handling:
147 * - The bw_data_saver comes after the happy box.
148 * Enable data saver:
149 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
150 * Disable data saver:
151 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700152 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900153
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900154const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900155const std::string HAPPY_BOX_WHITELIST_COMMAND = StringPrintf(
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900156 "-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
Chenbo Feng95892f32018-06-07 14:52:02 -0700157const std::string BPF_HAPPY_BOX_WHITELIST_COMMAND =
158 StringPrintf("-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
159const std::string BPF_PENALTY_BOX_BLACKLIST_COMMAND =
160 StringPrintf("-I bw_penalty_box -m bpf --object-pinned %s -j REJECT",
161 XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900162
163static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700164 /*
165 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700166 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700167 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700168 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900169 "*filter",
170 ":bw_INPUT -",
171 ":bw_OUTPUT -",
172 ":bw_FORWARD -",
173 ":bw_happy_box -",
174 ":bw_penalty_box -",
175 ":bw_data_saver -",
176 ":bw_costly_shared -",
177 "COMMIT",
178 "*raw",
179 ":bw_raw_PREROUTING -",
180 "COMMIT",
181 "*mangle",
182 ":bw_mangle_POSTROUTING -",
183 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700184};
185
Benedict Wongb9baf262017-12-03 15:43:08 -0800186static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
187
188/**
189 * Basic commands for creation of hooks into data accounting and data boxes.
190 *
191 * Included in these commands are rules to prevent the double-counting of IPsec
192 * packets. The general overview is as follows:
193 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
194 * completely accurate, and count only the outer packet. As such, the inner
195 * packet must be ignored, which is done through the use of two rules: use
196 * of the policy module (for tunnel mode), and VTI interface checks (for
197 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
198 * ipsec*
199 * > Outbound UID billing can always be done with the outer packets, due to the
200 * ability to always find the correct UID (based on the skb->sk). As such,
201 * the inner packets should be ignored based on the policy module, or the
202 * output interface if a VTI (ipsec+)
203 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
204 * opened the encap socket, and as such, should be billed as early as
205 * possible (for transport mode; tunnel mode usage should be billed to
206 * sending/receiving application). Due to the inner packet being
207 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
208 * has to be applied to prevent counting a second time.
209 * > Inbound ESP has no socket, and as such must be accounted later. ESP
210 * protocol packets are skipped via a blanket rule.
211 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
212 * ignore rule in the input chain would actually break the INPUT chain;
213 * Those rules are designed to ignore inner packets, and in the tunnel
214 * mode UDP, or any ESP case, we would not have billed the outer packet.
215 *
216 * See go/ipsec-data-accounting for more information.
217 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800218
Chenbo Feng95892f32018-06-07 14:52:02 -0700219const std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
Chenbo Feng5ed17992018-03-13 21:30:49 -0700220 const std::vector<std::string> ipt_basic_accounting_commands = {
221 "*filter",
222 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
223 "-A bw_INPUT -p esp -j RETURN",
224 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN",
225 uidBillingMask, uidBillingMask),
226 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
227 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900228
Chenbo Feng5ed17992018-03-13 21:30:49 -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",
233 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900234
Chenbo Feng5ed17992018-03-13 21:30:49 -0700235 "-A bw_costly_shared --jump bw_penalty_box",
Chenbo Feng95892f32018-06-07 14:52:02 -0700236 useBpf ? BPF_PENALTY_BOX_BLACKLIST_COMMAND : "",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700237 "-A bw_penalty_box --jump bw_happy_box",
238 "-A bw_happy_box --jump bw_data_saver",
239 "-A bw_data_saver -j RETURN",
Chenbo Feng95892f32018-06-07 14:52:02 -0700240 useBpf ? BPF_HAPPY_BOX_WHITELIST_COMMAND : HAPPY_BOX_WHITELIST_COMMAND,
Chenbo Feng5ed17992018-03-13 21:30:49 -0700241 "COMMIT",
242
243 "*raw",
244 // Prevents IPSec double counting (Tunnel mode and Transport mode,
245 // respectively)
246 "-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN",
247 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
248 "-A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
249 useBpf ? StringPrintf("-A bw_raw_PREROUTING -m bpf --object-pinned %s",
Chenbo Feng95892f32018-06-07 14:52:02 -0700250 XT_BPF_INGRESS_PROG_PATH) : "",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700251 "COMMIT",
252
253 "*mangle",
254 // Prevents IPSec double counting (Tunnel mode and Transport mode,
255 // respectively)
256 "-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
257 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
258 "-A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
259 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x",
260 uidBillingMask), // Clear the mark before sending this packet
261 useBpf ? StringPrintf("-A bw_mangle_POSTROUTING -m bpf --object-pinned %s",
Chenbo Feng95892f32018-06-07 14:52:02 -0700262 XT_BPF_EGRESS_PROG_PATH) : "",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700263 COMMIT_AND_CLOSE
264 };
265 return ipt_basic_accounting_commands;
266}
267
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900268
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900269std::vector<std::string> toStrVec(int num, char* strs[]) {
270 std::vector<std::string> tmp;
271 for (int i = 0; i < num; ++i) {
272 tmp.emplace_back(strs[i]);
273 }
274 return tmp;
275}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900276
277} // namespace
278
Chenbo Feng95892f32018-06-07 14:52:02 -0700279bool BandwidthController::getBpfStatus() {
Chenbo Feng33a4de12018-03-16 18:10:07 -0700280 return (access(XT_BPF_INGRESS_PROG_PATH, F_OK) != -1) &&
Chenbo Feng95892f32018-06-07 14:52:02 -0700281 (access(XT_BPF_EGRESS_PROG_PATH, F_OK) != -1) &&
282 (access(XT_BPF_WHITELIST_PROG_PATH, F_OK) != -1) &&
283 (access(XT_BPF_BLACKLIST_PROG_PATH, F_OK) != -1);
Chenbo Fenga121e202018-03-19 11:51:54 -0700284}
285
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900286BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700287}
288
JP Abgrall0e540ec2013-08-26 15:13:10 -0700289void BandwidthController::flushCleanTables(bool doClean) {
290 /* Flush and remove the bw_costly_<iface> tables */
291 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700292
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900293 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900294 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700295}
JP Abgrall0031cea2012-04-17 16:38:23 -0700296
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900297int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700298 /* flush+clean is allowed to fail */
299 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700300 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700301}
302
303int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700304 char value[PROPERTY_VALUE_MAX];
305
306 if (!force) {
307 property_get("persist.bandwidth.enable", value, "1");
308 if (!strcmp(value, "0"))
309 return 0;
310 }
JP Abgrall8a932722011-07-13 19:17:35 -0700311
JP Abgralldb7da582011-09-18 12:57:32 -0700312 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900313 mSharedQuotaIfaces.clear();
314 mQuotaIfaces.clear();
315 mGlobalAlertBytes = 0;
316 mGlobalAlertTetherCount = 0;
317 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700318
JP Abgrall0e540ec2013-08-26 15:13:10 -0700319 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700320
Chenbo Feng95892f32018-06-07 14:52:02 -0700321 mBpfSupported = getBpfStatus();
322 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900323 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700324}
325
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900326int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700327
328 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700329 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700330}
331
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900332std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
333 std::string cmd;
334 const char *chainName = "bw_data_saver";
335 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
336 std::string criticalCommands = enable ?
337 FirewallController::makeCriticalCommands(target, chainName) : "";
338 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900339 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900340 ":%s -\n"
341 "%s"
342 "-A %s%s\n"
343 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
344 return cmd;
345}
346
347int BandwidthController::enableDataSaver(bool enable) {
348 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
349 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
350 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900351}
352
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700353int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900354 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
355 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700356}
357
358int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900359 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
360 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700361}
362
JP Abgralle4788732013-07-02 20:28:45 -0700363int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900364 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
365 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700366}
367
368int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900369 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
370 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700371}
372
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900373int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
374 const std::string& chain, IptJumpOp jumpHandling,
375 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700376 if (mBpfSupported) {
377 Status status = gCtls->trafficCtrl.updateBandwidthUidMap(appStrUids, jumpHandling, op);
378 if (!isOk(status)) {
379 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
380 }
381 return status.code();
382 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900383 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900384 for (const auto& appStrUid : appStrUids) {
385 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
386 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700387 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900388 StringAppendF(&cmd, "COMMIT\n");
389 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700390}
391
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900392int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700393 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700394 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900395 constexpr char cost[] = "shared";
396 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700397
JP Abgrall8a932722011-07-13 19:17:35 -0700398 if (!maxBytes) {
399 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000400 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700401 return -1;
402 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700403 if (!isIfaceName(iface))
404 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700405
406 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900407 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700408 }
409
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900410 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700411
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900412 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900413 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
414 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900415 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900416 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
417 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900418 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900419 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
420 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900421 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900422 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
423 " --name %s --jump REJECT",
424 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900425 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900426 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900427
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900428 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900429 if (res) {
430 ALOGE("Failed set quota rule");
431 removeInterfaceSharedQuota(iface);
432 return -1;
433 }
434 mSharedQuotaBytes = maxBytes;
435 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700436 }
437
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900438 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900439 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700440 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900441 ALOGE("Failed update quota for %s", cost);
442 removeInterfaceSharedQuota(iface);
443 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700444 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900445 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700446 }
447 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700448}
449
JP Abgrall8a932722011-07-13 19:17:35 -0700450/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900451int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900452 constexpr char cost[] = "shared";
453 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700454
JP Abgrall69261cb2014-06-19 18:35:24 -0700455 if (!isIfaceName(iface))
456 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700457
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900458 auto it = mSharedQuotaIfaces.find(iface);
459
460 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900461 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700462 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700463 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700464
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900465 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900466 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900467 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
468 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900469 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900470 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
471 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900472 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900473 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
474 " --name %s --jump REJECT",
475 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700476 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900477 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900478
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900479 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
480 ALOGE("Failed to remove shared quota on %s", iface.c_str());
481 return -1;
482 }
483
484 int res = 0;
485 mSharedQuotaIfaces.erase(it);
486 if (mSharedQuotaIfaces.empty()) {
487 mSharedQuotaBytes = 0;
488 if (mSharedAlertBytes) {
489 res = removeSharedAlert();
490 if (res == 0) {
491 mSharedAlertBytes = 0;
492 }
493 }
494 }
495
496 return res;
497
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700498}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700499
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900500int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900501 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700502
JP Abgrall69261cb2014-06-19 18:35:24 -0700503 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700504 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700505
JP Abgrall8a932722011-07-13 19:17:35 -0700506 if (!maxBytes) {
507 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000508 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700509 return -1;
510 }
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()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900519 if (updateQuota(cost, maxBytes) != 0) {
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);
522 return -1;
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 };
544
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900545 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900546 ALOGE("Failed set quota rule");
547 removeInterfaceQuota(iface);
548 return -1;
549 }
550
551 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
552 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700553}
554
JP Abgrall8a932722011-07-13 19:17:35 -0700555int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
556 return getInterfaceQuota("shared", bytes);
557}
558
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900559int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900560 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900561 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700562
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900563 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700564
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900565 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
566 if (!isOk(file)) {
567 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700568 return -1;
569 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900570 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
571 if (!isOk(rv)) {
572 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
573 return -1;
574 }
575 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
576 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700577}
578
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900579int BandwidthController::removeInterfaceQuota(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700580 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700581 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700582
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900583 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700584
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900585 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900586 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700587 return -1;
588 }
589
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900590 const std::string chain = "bw_costly_" + iface;
591 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900592 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900593 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
594 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900595 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900596 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
597 StringPrintf("-F %s", chain.c_str()),
598 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900599 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900600 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900601
602 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700603
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900604 if (res == 0) {
605 mQuotaIfaces.erase(it);
606 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700607
608 return res;
609}
JP Abgrall8a932722011-07-13 19:17:35 -0700610
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900611int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900612 const auto& sys = android::netdutils::sSyscalls.get();
613 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700614
JP Abgrall69261cb2014-06-19 18:35:24 -0700615 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900616 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700617 return -1;
618 }
619
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900620 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
621 if (!isOk(file)) {
622 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700623 return -1;
624 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900625 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes);
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
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900636 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
637 alertName.c_str());
638 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
639 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900640 StringAppendF(&alertQuotaCmd, "COMMIT\n");
641
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900642 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700643}
644
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900645int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
646 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900647 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900648 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900649 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
650 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900651 StringAppendF(&alertQuotaCmd, "COMMIT\n");
652
653 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700654}
655
656int BandwidthController::setGlobalAlert(int64_t bytes) {
657 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700658 int res = 0;
659
660 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000661 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700662 return -1;
663 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900664 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700665 res = updateQuota(alertName, bytes);
666 } else {
667 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900668 if (mGlobalAlertTetherCount) {
669 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700670 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
671 }
JP Abgrall8a932722011-07-13 19:17:35 -0700672 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900673 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700674 return res;
675}
676
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900677int BandwidthController::setGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700678 const char *alertName = ALERT_GLOBAL_NAME;
679 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700680
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900681 mGlobalAlertTetherCount++;
682 ALOGV("setGlobalAlertInForwardChain(): %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700683
684 /*
685 * If there is no globalAlert active we are done.
686 * If there is an active globalAlert but this is not the 1st
687 * tether, we are also done.
688 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900689 if (!mGlobalAlertBytes || mGlobalAlertTetherCount != 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700690 return 0;
691 }
692
693 /* We only add the rule if this was the 1st tether added. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900694 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700695 return res;
696}
697
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900698int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700699
700 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700701 int res = 0;
702
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900703 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000704 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700705 return -1;
706 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900707 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
708 if (mGlobalAlertTetherCount) {
709 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700710 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900711 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700712 return res;
713}
714
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900715int BandwidthController::removeGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700716 int res = 0;
717 const char *alertName = ALERT_GLOBAL_NAME;
718
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900719 if (!mGlobalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000720 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700721 return -1;
722 }
723
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900724 mGlobalAlertTetherCount--;
JP Abgrallc6c67342011-10-07 16:28:54 -0700725 /*
726 * If there is no globalAlert active we are done.
727 * If there is an active globalAlert but there are more
728 * tethers, we are also done.
729 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900730 if (!mGlobalAlertBytes || mGlobalAlertTetherCount >= 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700731 return 0;
732 }
733
734 /* We only detete the rule if this was the last tether removed. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900735 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700736 return res;
737}
738
JP Abgrall8a932722011-07-13 19:17:35 -0700739int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900740 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000741 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700742 return -1;
743 }
744 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000745 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700746 return -1;
747 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900748 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700749}
750
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900751int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900752 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700753}
754
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900755int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700756 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900757 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700758 return -1;
759 }
760
JP Abgrall8a932722011-07-13 19:17:35 -0700761 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000762 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700763 return -1;
764 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900765 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700766
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900767 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000768 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700769 return -1;
770 }
771
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900772 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700773}
774
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900775int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700776 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900777 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700778 return -1;
779 }
780
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900781 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700782
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900783 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900784 ALOGE("No prior alert set for interface %s", iface.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700785 return -1;
786 }
787
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900788 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700789}
790
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900791int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
792 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700793 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700794
JP Abgrall69261cb2014-06-19 18:35:24 -0700795 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900796 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700797 return -1;
798 }
799
JP Abgrall8a932722011-07-13 19:17:35 -0700800 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000801 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700802 return -1;
803 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900804
805 std::string alertName = costName + "Alert";
806 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700807 if (*alertBytes) {
808 res = updateQuota(alertName, *alertBytes);
809 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900810 std::vector<std::string> commands = {
811 "*filter\n",
812 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
813 "COMMIT\n"
814 };
815 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
816 if (res) {
817 ALOGE("Failed to set costly alert for %s", costName.c_str());
818 }
JP Abgrall8a932722011-07-13 19:17:35 -0700819 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900820 if (res == 0) {
821 *alertBytes = bytes;
822 }
JP Abgrall8a932722011-07-13 19:17:35 -0700823 return res;
824}
825
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900826int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700827 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900828 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700829 return -1;
830 }
831
JP Abgrall8a932722011-07-13 19:17:35 -0700832 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900833 ALOGE("No prior alert set for %s alert", costName.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700834 return -1;
835 }
836
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900837 std::string alertName = costName + "Alert";
838 std::string chainName = "bw_costly_" + costName;
839 std::vector<std::string> commands = {
840 "*filter\n",
841 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
842 "COMMIT\n"
843 };
844 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
845 ALOGE("Failed to remove costly alert %s", costName.c_str());
846 return -1;
847 }
JP Abgrall8a932722011-07-13 19:17:35 -0700848
849 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900850 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700851}
JP Abgralldb7da582011-09-18 12:57:32 -0700852
JP Abgrall0e540ec2013-08-26 15:13:10 -0700853void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900854 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
855 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700856
857 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900858 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
859 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700860 return;
861 }
862 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900863 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700864}
865
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900866void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
867 std::stringstream stream(ruleList);
868 std::string rule;
869 std::vector<std::string> clearCommands = { "*filter" };
870 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700871
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900872 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
873 while (std::getline(stream, rule, '\n')) {
874 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
875 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
876 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
877
878 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700879 continue;
880 }
881
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900882 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700883 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900884 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700885 }
886 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900887
888 if (clearCommands.size() == 1) {
889 // No rules found.
890 return;
891 }
892
893 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900894 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700895}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900896
897inline const char *BandwidthController::opToString(IptOp op) {
898 switch (op) {
899 case IptOpInsert:
900 return "-I";
901 case IptOpDelete:
902 return "-D";
903 }
904}
905
906inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
907 /*
908 * Must be careful what one rejects with, as upper layer protocols will just
909 * keep on hammering the device until the number of retries are done.
910 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
911 */
912 switch (jumpHandling) {
913 case IptJumpNoAdd:
914 return "";
915 case IptJumpReject:
916 return " --jump REJECT";
917 case IptJumpReturn:
918 return " --jump RETURN";
919 }
920}