blob: a01ad41c4cb87b60f4de9a0084206ae596aecf75 [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
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900269std::vector<std::string> toStrVec(int num, const char* const strs[]) {
270 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900271}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900272
273} // namespace
274
Chenbo Feng95892f32018-06-07 14:52:02 -0700275bool BandwidthController::getBpfStatus() {
Chenbo Feng33a4de12018-03-16 18:10:07 -0700276 return (access(XT_BPF_INGRESS_PROG_PATH, F_OK) != -1) &&
Chenbo Feng95892f32018-06-07 14:52:02 -0700277 (access(XT_BPF_EGRESS_PROG_PATH, F_OK) != -1) &&
278 (access(XT_BPF_WHITELIST_PROG_PATH, F_OK) != -1) &&
279 (access(XT_BPF_BLACKLIST_PROG_PATH, F_OK) != -1);
Chenbo Fenga121e202018-03-19 11:51:54 -0700280}
281
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900282BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700283}
284
JP Abgrall0e540ec2013-08-26 15:13:10 -0700285void BandwidthController::flushCleanTables(bool doClean) {
286 /* Flush and remove the bw_costly_<iface> tables */
287 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700288
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900289 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900290 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700291}
JP Abgrall0031cea2012-04-17 16:38:23 -0700292
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900293int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700294 /* flush+clean is allowed to fail */
295 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700296 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700297}
298
299int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700300 char value[PROPERTY_VALUE_MAX];
301
302 if (!force) {
303 property_get("persist.bandwidth.enable", value, "1");
304 if (!strcmp(value, "0"))
305 return 0;
306 }
JP Abgrall8a932722011-07-13 19:17:35 -0700307
JP Abgralldb7da582011-09-18 12:57:32 -0700308 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900309 mSharedQuotaIfaces.clear();
310 mQuotaIfaces.clear();
311 mGlobalAlertBytes = 0;
312 mGlobalAlertTetherCount = 0;
313 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700314
JP Abgrall0e540ec2013-08-26 15:13:10 -0700315 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700316
Chenbo Feng95892f32018-06-07 14:52:02 -0700317 mBpfSupported = getBpfStatus();
318 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900319 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700320}
321
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900322int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700323
324 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700325 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700326}
327
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900328std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
329 std::string cmd;
330 const char *chainName = "bw_data_saver";
331 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
332 std::string criticalCommands = enable ?
333 FirewallController::makeCriticalCommands(target, chainName) : "";
334 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900335 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900336 ":%s -\n"
337 "%s"
338 "-A %s%s\n"
339 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
340 return cmd;
341}
342
343int BandwidthController::enableDataSaver(bool enable) {
344 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
345 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
346 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900347}
348
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900349int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900350 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
351 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700352}
353
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900354int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900355 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
356 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700357}
358
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900359int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900360 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
361 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700362}
363
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900364int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900365 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
366 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700367}
368
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900369int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
370 const std::string& chain, IptJumpOp jumpHandling,
371 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700372 if (mBpfSupported) {
373 Status status = gCtls->trafficCtrl.updateBandwidthUidMap(appStrUids, jumpHandling, op);
374 if (!isOk(status)) {
375 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
376 }
377 return status.code();
378 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900379 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900380 for (const auto& appStrUid : appStrUids) {
381 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
382 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700383 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900384 StringAppendF(&cmd, "COMMIT\n");
385 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700386}
387
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900388int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700389 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700390 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900391 constexpr char cost[] = "shared";
392 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700393
JP Abgrall8a932722011-07-13 19:17:35 -0700394 if (!maxBytes) {
395 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000396 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700397 return -1;
398 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700399 if (!isIfaceName(iface))
400 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700401
402 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900403 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700404 }
405
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900406 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700407
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900408 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900409 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
410 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900411 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900412 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
413 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900414 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900415 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
416 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900417 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900418 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
419 " --name %s --jump REJECT",
420 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900421 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900422 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900423
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900424 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900425 if (res) {
426 ALOGE("Failed set quota rule");
427 removeInterfaceSharedQuota(iface);
428 return -1;
429 }
430 mSharedQuotaBytes = maxBytes;
431 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700432 }
433
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900434 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900435 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700436 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900437 ALOGE("Failed update quota for %s", cost);
438 removeInterfaceSharedQuota(iface);
439 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700440 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900441 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700442 }
443 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700444}
445
JP Abgrall8a932722011-07-13 19:17:35 -0700446/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900447int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900448 constexpr char cost[] = "shared";
449 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700450
JP Abgrall69261cb2014-06-19 18:35:24 -0700451 if (!isIfaceName(iface))
452 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700453
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900454 auto it = mSharedQuotaIfaces.find(iface);
455
456 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900457 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700458 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700459 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700460
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900461 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900462 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900463 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
464 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900465 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900466 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
467 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900468 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900469 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
470 " --name %s --jump REJECT",
471 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700472 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900473 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900474
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900475 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
476 ALOGE("Failed to remove shared quota on %s", iface.c_str());
477 return -1;
478 }
479
480 int res = 0;
481 mSharedQuotaIfaces.erase(it);
482 if (mSharedQuotaIfaces.empty()) {
483 mSharedQuotaBytes = 0;
484 if (mSharedAlertBytes) {
485 res = removeSharedAlert();
486 if (res == 0) {
487 mSharedAlertBytes = 0;
488 }
489 }
490 }
491
492 return res;
493
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700494}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700495
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900496int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900497 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700498
JP Abgrall69261cb2014-06-19 18:35:24 -0700499 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700500 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700501
JP Abgrall8a932722011-07-13 19:17:35 -0700502 if (!maxBytes) {
503 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000504 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700505 return -1;
506 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700507 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700508 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700509 }
510
JP Abgrall0dad7c22011-06-24 11:58:14 -0700511 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900512 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700513
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900514 if (it != mQuotaIfaces.end()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900515 if (updateQuota(cost, maxBytes) != 0) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900516 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900517 removeInterfaceQuota(iface);
518 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700519 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900520 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900521 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700522 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700523
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900524 const std::string chain = "bw_costly_" + iface;
525 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
526 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900527 "*filter",
528 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900529 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
530 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
531 chain.c_str()),
532 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
533 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900534 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900535 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
536 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
537 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900538 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900539 };
540
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900541 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900542 ALOGE("Failed set quota rule");
543 removeInterfaceQuota(iface);
544 return -1;
545 }
546
547 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
548 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700549}
550
JP Abgrall8a932722011-07-13 19:17:35 -0700551int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
552 return getInterfaceQuota("shared", bytes);
553}
554
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900555int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900556 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900557 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700558
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900559 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700560
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900561 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
562 if (!isOk(file)) {
563 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700564 return -1;
565 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900566 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
567 if (!isOk(rv)) {
568 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
569 return -1;
570 }
571 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
572 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700573}
574
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900575int BandwidthController::removeInterfaceQuota(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700576 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700577 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700578
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900579 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700580
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900581 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900582 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700583 return -1;
584 }
585
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900586 const std::string chain = "bw_costly_" + iface;
587 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900588 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900589 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
590 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900591 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900592 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
593 StringPrintf("-F %s", chain.c_str()),
594 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900595 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900596 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900597
598 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700599
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900600 if (res == 0) {
601 mQuotaIfaces.erase(it);
602 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700603
604 return res;
605}
JP Abgrall8a932722011-07-13 19:17:35 -0700606
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900607int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900608 const auto& sys = android::netdutils::sSyscalls.get();
609 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700610
JP Abgrall69261cb2014-06-19 18:35:24 -0700611 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900612 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700613 return -1;
614 }
615
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900616 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
617 if (!isOk(file)) {
618 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700619 return -1;
620 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900621 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700622 return 0;
623}
624
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900625int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
626 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900627 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900628 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700629
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900630 // TODO: consider using an alternate template for the delete that does not include the --quota
631 // value. This code works because the --quota value is ignored by deletes
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900632 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
633 alertName.c_str());
634 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
635 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900636 StringAppendF(&alertQuotaCmd, "COMMIT\n");
637
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900638 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700639}
640
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900641int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
642 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900643 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900644 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900645 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
646 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900647 StringAppendF(&alertQuotaCmd, "COMMIT\n");
648
649 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700650}
651
652int BandwidthController::setGlobalAlert(int64_t bytes) {
653 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700654 int res = 0;
655
656 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000657 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700658 return -1;
659 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900660 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700661 res = updateQuota(alertName, bytes);
662 } else {
663 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900664 if (mGlobalAlertTetherCount) {
665 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700666 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
667 }
JP Abgrall8a932722011-07-13 19:17:35 -0700668 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900669 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700670 return res;
671}
672
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900673int BandwidthController::setGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700674 const char *alertName = ALERT_GLOBAL_NAME;
675 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700676
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900677 mGlobalAlertTetherCount++;
678 ALOGV("setGlobalAlertInForwardChain(): %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700679
680 /*
681 * If there is no globalAlert active we are done.
682 * If there is an active globalAlert but this is not the 1st
683 * tether, we are also done.
684 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900685 if (!mGlobalAlertBytes || mGlobalAlertTetherCount != 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700686 return 0;
687 }
688
689 /* We only add the rule if this was the 1st tether added. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900690 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700691 return res;
692}
693
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900694int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700695
696 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700697 int res = 0;
698
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900699 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000700 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700701 return -1;
702 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900703 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
704 if (mGlobalAlertTetherCount) {
705 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700706 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900707 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700708 return res;
709}
710
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900711int BandwidthController::removeGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700712 int res = 0;
713 const char *alertName = ALERT_GLOBAL_NAME;
714
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900715 if (!mGlobalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000716 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700717 return -1;
718 }
719
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900720 mGlobalAlertTetherCount--;
JP Abgrallc6c67342011-10-07 16:28:54 -0700721 /*
722 * If there is no globalAlert active we are done.
723 * If there is an active globalAlert but there are more
724 * tethers, we are also done.
725 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900726 if (!mGlobalAlertBytes || mGlobalAlertTetherCount >= 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700727 return 0;
728 }
729
730 /* We only detete the rule if this was the last tether removed. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900731 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700732 return res;
733}
734
JP Abgrall8a932722011-07-13 19:17:35 -0700735int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900736 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000737 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700738 return -1;
739 }
740 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000741 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700742 return -1;
743 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900744 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700745}
746
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900747int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900748 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700749}
750
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900751int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700752 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900753 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700754 return -1;
755 }
756
JP Abgrall8a932722011-07-13 19:17:35 -0700757 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000758 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700759 return -1;
760 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900761 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700762
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900763 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000764 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700765 return -1;
766 }
767
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900768 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700769}
770
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900771int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700772 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900773 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700774 return -1;
775 }
776
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900777 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700778
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900779 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900780 ALOGE("No prior alert set for interface %s", iface.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700781 return -1;
782 }
783
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900784 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700785}
786
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900787int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
788 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700789 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700790
JP Abgrall69261cb2014-06-19 18:35:24 -0700791 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900792 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700793 return -1;
794 }
795
JP Abgrall8a932722011-07-13 19:17:35 -0700796 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000797 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700798 return -1;
799 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900800
801 std::string alertName = costName + "Alert";
802 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700803 if (*alertBytes) {
804 res = updateQuota(alertName, *alertBytes);
805 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900806 std::vector<std::string> commands = {
807 "*filter\n",
808 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
809 "COMMIT\n"
810 };
811 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
812 if (res) {
813 ALOGE("Failed to set costly alert for %s", costName.c_str());
814 }
JP Abgrall8a932722011-07-13 19:17:35 -0700815 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900816 if (res == 0) {
817 *alertBytes = bytes;
818 }
JP Abgrall8a932722011-07-13 19:17:35 -0700819 return res;
820}
821
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900822int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700823 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900824 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700825 return -1;
826 }
827
JP Abgrall8a932722011-07-13 19:17:35 -0700828 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900829 ALOGE("No prior alert set for %s alert", costName.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700830 return -1;
831 }
832
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900833 std::string alertName = costName + "Alert";
834 std::string chainName = "bw_costly_" + costName;
835 std::vector<std::string> commands = {
836 "*filter\n",
837 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
838 "COMMIT\n"
839 };
840 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
841 ALOGE("Failed to remove costly alert %s", costName.c_str());
842 return -1;
843 }
JP Abgrall8a932722011-07-13 19:17:35 -0700844
845 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900846 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700847}
JP Abgralldb7da582011-09-18 12:57:32 -0700848
JP Abgrall0e540ec2013-08-26 15:13:10 -0700849void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900850 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
851 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700852
853 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900854 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
855 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700856 return;
857 }
858 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900859 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700860}
861
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900862void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
863 std::stringstream stream(ruleList);
864 std::string rule;
865 std::vector<std::string> clearCommands = { "*filter" };
866 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700867
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900868 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
869 while (std::getline(stream, rule, '\n')) {
870 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
871 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
872 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
873
874 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700875 continue;
876 }
877
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900878 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700879 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900880 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700881 }
882 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900883
884 if (clearCommands.size() == 1) {
885 // No rules found.
886 return;
887 }
888
889 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900890 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700891}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900892
893inline const char *BandwidthController::opToString(IptOp op) {
894 switch (op) {
895 case IptOpInsert:
896 return "-I";
897 case IptOpDelete:
898 return "-D";
899 }
900}
901
902inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
903 /*
904 * Must be careful what one rejects with, as upper layer protocols will just
905 * keep on hammering the device until the number of retries are done.
906 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
907 */
908 switch (jumpHandling) {
909 case IptJumpNoAdd:
910 return "";
911 case IptJumpReject:
912 return " --jump REJECT";
913 case IptJumpReturn:
914 return " --jump RETURN";
915 }
916}