blob: 6a40ba20631210d58c5a49fd0d0d3125364d3a94 [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;
Luke Huange64fa382018-07-24 16:38:22 +080075using android::net::FirewallController;
Chenbo Feng95892f32018-06-07 14:52:02 -070076using android::net::gCtls;
Chenbo Feng95892f32018-06-07 14:52:02 -070077using android::netdutils::Status;
Luke Huange64fa382018-07-24 16:38:22 +080078using android::netdutils::StatusOr;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090079using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090080
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090081namespace {
82
83const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090084const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090085
Joel Scherpelzbcad6612017-05-30 10:55:11 +090086const char NAUGHTY_CHAIN[] = "bw_penalty_box";
87const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070088
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070089/**
90 * Some comments about the rules:
91 * * Ordering
92 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070093 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070094 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070095 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070096 *
97 * * global quota vs per interface quota
98 * - global quota for all costly interfaces uses a single costly chain:
99 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700100 * iptables -N bw_costly_shared
101 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
102 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
103 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700104 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700105 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900106 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900107 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700108 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700109 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700110 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
111 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700112 *
113 * - quota per interface. This is achieve by having "costly" chains per quota.
114 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700115 * iptables -N bw_costly_iface0
116 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
117 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
118 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700119 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700120 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700121 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900122 * * Penalty box, happy box and data saver.
123 * - bw_penalty box is a blacklist of apps that are rejected.
124 * - bw_happy_box is a whitelist of apps. It always includes all system apps
125 * - bw_data_saver implements data usage restrictions.
126 * - Via the UI the user can add and remove apps from the whitelist and
127 * blacklist, and turn on/off data saver.
128 * - The blacklist takes precedence over the whitelist and the whitelist
129 * takes precedence over data saver.
130 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700131 * * bw_penalty_box handling:
132 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900133 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700134 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700135 * --jump REJECT --reject-with icmp-port-unreachable
136 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700137 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900138 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700139 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700140 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700141 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900142 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900143 * * bw_data_saver handling:
144 * - The bw_data_saver comes after the happy box.
145 * Enable data saver:
146 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
147 * Disable data saver:
148 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700149 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900150
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900151const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Chenbo Feng703798e2018-06-15 17:07:59 -0700152const std::string HAPPY_BOX_MATCH_WHITELIST_COMMAND =
153 StringPrintf("-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
154const std::string BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND = StringPrintf(
155 "-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
156const std::string BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND = StringPrintf(
157 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900158
159static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700160 /*
161 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700162 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700163 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700164 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900165 "*filter",
166 ":bw_INPUT -",
167 ":bw_OUTPUT -",
168 ":bw_FORWARD -",
169 ":bw_happy_box -",
170 ":bw_penalty_box -",
171 ":bw_data_saver -",
172 ":bw_costly_shared -",
173 "COMMIT",
174 "*raw",
175 ":bw_raw_PREROUTING -",
176 "COMMIT",
177 "*mangle",
178 ":bw_mangle_POSTROUTING -",
179 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700180};
181
Benedict Wongb9baf262017-12-03 15:43:08 -0800182static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
183
184/**
185 * Basic commands for creation of hooks into data accounting and data boxes.
186 *
187 * Included in these commands are rules to prevent the double-counting of IPsec
188 * packets. The general overview is as follows:
189 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
190 * completely accurate, and count only the outer packet. As such, the inner
191 * packet must be ignored, which is done through the use of two rules: use
192 * of the policy module (for tunnel mode), and VTI interface checks (for
193 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
194 * ipsec*
195 * > Outbound UID billing can always be done with the outer packets, due to the
196 * ability to always find the correct UID (based on the skb->sk). As such,
197 * the inner packets should be ignored based on the policy module, or the
198 * output interface if a VTI (ipsec+)
199 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
200 * opened the encap socket, and as such, should be billed as early as
201 * possible (for transport mode; tunnel mode usage should be billed to
202 * sending/receiving application). Due to the inner packet being
203 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
204 * has to be applied to prevent counting a second time.
205 * > Inbound ESP has no socket, and as such must be accounted later. ESP
206 * protocol packets are skipped via a blanket rule.
207 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
208 * ignore rule in the input chain would actually break the INPUT chain;
209 * Those rules are designed to ignore inner packets, and in the tunnel
210 * mode UDP, or any ESP case, we would not have billed the outer packet.
211 *
212 * See go/ipsec-data-accounting for more information.
213 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800214
Chenbo Feng95892f32018-06-07 14:52:02 -0700215const std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
Chenbo Feng5ed17992018-03-13 21:30:49 -0700216 const std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700217 "*filter",
218 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
219 "-A bw_INPUT -p esp -j RETURN",
220 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
221 uidBillingMask),
Chenbo Feng44c0f442018-07-10 16:54:30 -0700222 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700223 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900224
Chenbo Feng703798e2018-06-15 17:07:59 -0700225 // Prevents IPSec double counting (Tunnel mode and Transport mode,
226 // respectively)
227 "-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
228 "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700229 useBpf ? "" : "-A bw_OUTPUT -m owner --socket-exists",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900230
Chenbo Feng703798e2018-06-15 17:07:59 -0700231 "-A bw_costly_shared --jump bw_penalty_box",
232 useBpf ? BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND : "",
233 "-A bw_penalty_box --jump bw_happy_box", "-A bw_happy_box --jump bw_data_saver",
234 "-A bw_data_saver -j RETURN",
235 useBpf ? BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND : HAPPY_BOX_MATCH_WHITELIST_COMMAND,
236 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700237
Chenbo Feng703798e2018-06-15 17:07:59 -0700238 "*raw",
239 // Prevents IPSec double counting (Tunnel mode and Transport mode,
240 // respectively)
241 "-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN",
242 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Chenbo Feng703798e2018-06-15 17:07:59 -0700243 useBpf ? StringPrintf("-A bw_raw_PREROUTING -m bpf --object-pinned %s",
244 XT_BPF_INGRESS_PROG_PATH)
Chenbo Feng44c0f442018-07-10 16:54:30 -0700245 : "-A bw_raw_PREROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700246 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700247
Chenbo Feng703798e2018-06-15 17:07:59 -0700248 "*mangle",
249 // Prevents IPSec double counting (Tunnel mode and Transport mode,
250 // respectively)
251 "-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
252 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700253 useBpf ? "" : "-A bw_mangle_POSTROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700254 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x",
255 uidBillingMask), // Clear the mark before sending this packet
256 useBpf ? StringPrintf("-A bw_mangle_POSTROUTING -m bpf --object-pinned %s",
257 XT_BPF_EGRESS_PROG_PATH)
258 : "",
259 COMMIT_AND_CLOSE};
Chenbo Feng5ed17992018-03-13 21:30:49 -0700260 return ipt_basic_accounting_commands;
261}
262
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900263
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900264std::vector<std::string> toStrVec(int num, const char* const strs[]) {
265 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900266}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900267
268} // namespace
269
Chenbo Feng44c0f442018-07-10 16:54:30 -0700270void BandwidthController::setBpfEnabled(bool isEnabled) {
271 mBpfSupported = isEnabled;
Chenbo Fenga121e202018-03-19 11:51:54 -0700272}
273
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900274BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700275}
276
JP Abgrall0e540ec2013-08-26 15:13:10 -0700277void BandwidthController::flushCleanTables(bool doClean) {
278 /* Flush and remove the bw_costly_<iface> tables */
279 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700280
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900281 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900282 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700283}
JP Abgrall0031cea2012-04-17 16:38:23 -0700284
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900285int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700286 /* flush+clean is allowed to fail */
287 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700288 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700289}
290
Luke Huangf44a3c12018-09-07 12:10:12 +0800291int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700292 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900293 mSharedQuotaIfaces.clear();
294 mQuotaIfaces.clear();
295 mGlobalAlertBytes = 0;
296 mGlobalAlertTetherCount = 0;
297 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700298
JP Abgrall0e540ec2013-08-26 15:13:10 -0700299 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700300
Chenbo Feng95892f32018-06-07 14:52:02 -0700301 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900302 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700303}
304
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900305int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700306
307 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700308 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700309}
310
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900311std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
312 std::string cmd;
313 const char *chainName = "bw_data_saver";
314 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
315 std::string criticalCommands = enable ?
316 FirewallController::makeCriticalCommands(target, chainName) : "";
317 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900318 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900319 ":%s -\n"
320 "%s"
321 "-A %s%s\n"
322 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
323 return cmd;
324}
325
326int BandwidthController::enableDataSaver(bool enable) {
327 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
328 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
329 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900330}
331
Luke Huang531f5d32018-08-03 15:19:05 +0800332// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900333int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900334 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
335 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700336}
337
Luke Huang531f5d32018-08-03 15:19:05 +0800338// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900339int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900340 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
341 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700342}
343
Luke Huang531f5d32018-08-03 15:19:05 +0800344// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900345int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900346 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
347 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700348}
349
Luke Huang531f5d32018-08-03 15:19:05 +0800350// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900351int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900352 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
353 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700354}
355
Luke Huang531f5d32018-08-03 15:19:05 +0800356int BandwidthController::addNaughtyApps(const std::vector<std::string>& appStrUid) {
357 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpInsert);
358}
359
360int BandwidthController::removeNaughtyApps(const std::vector<std::string>& appStrUid) {
361 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpDelete);
362}
363
364int BandwidthController::addNiceApps(const std::vector<std::string>& appStrUid) {
365 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpInsert);
366}
367
368int BandwidthController::removeNiceApps(const std::vector<std::string>& appStrUid) {
369 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpDelete);
370}
371
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900372int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
373 const std::string& chain, IptJumpOp jumpHandling,
374 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700375 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700376 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
377 if (!isOk(status)) {
378 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700379 }
380 return status.code();
381 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900382 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900383 for (const auto& appStrUid : appStrUids) {
384 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
385 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700386 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900387 StringAppendF(&cmd, "COMMIT\n");
388 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700389}
390
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900391int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700392 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700393 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900394 constexpr char cost[] = "shared";
395 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700396
JP Abgrall8a932722011-07-13 19:17:35 -0700397 if (!maxBytes) {
398 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000399 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700400 return -1;
401 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700402 if (!isIfaceName(iface))
403 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700404
405 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900406 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700407 }
408
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900409 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700410
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900411 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900412 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
413 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900414 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900415 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
416 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900417 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900418 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
419 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900420 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900421 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
422 " --name %s --jump REJECT",
423 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900424 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900425 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900426
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900427 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900428 if (res) {
429 ALOGE("Failed set quota rule");
430 removeInterfaceSharedQuota(iface);
431 return -1;
432 }
433 mSharedQuotaBytes = maxBytes;
434 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700435 }
436
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900437 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900438 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700439 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900440 ALOGE("Failed update quota for %s", cost);
441 removeInterfaceSharedQuota(iface);
442 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700443 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900444 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700445 }
446 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700447}
448
JP Abgrall8a932722011-07-13 19:17:35 -0700449/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900450int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900451 constexpr char cost[] = "shared";
452 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700453
JP Abgrall69261cb2014-06-19 18:35:24 -0700454 if (!isIfaceName(iface))
455 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700456
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900457 auto it = mSharedQuotaIfaces.find(iface);
458
459 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900460 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700461 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700462 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700463
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900464 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900465 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900466 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
467 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900468 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900469 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
470 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900471 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900472 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
473 " --name %s --jump REJECT",
474 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700475 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900476 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900477
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900478 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
479 ALOGE("Failed to remove shared quota on %s", iface.c_str());
480 return -1;
481 }
482
483 int res = 0;
484 mSharedQuotaIfaces.erase(it);
485 if (mSharedQuotaIfaces.empty()) {
486 mSharedQuotaBytes = 0;
487 if (mSharedAlertBytes) {
488 res = removeSharedAlert();
489 if (res == 0) {
490 mSharedAlertBytes = 0;
491 }
492 }
493 }
494
495 return res;
496
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700497}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700498
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900499int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900500 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700501
Luke Huang531f5d32018-08-03 15:19:05 +0800502 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700503
JP Abgrall8a932722011-07-13 19:17:35 -0700504 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000505 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800506 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700507 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700508 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700509 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700510 }
511
JP Abgrall0dad7c22011-06-24 11:58:14 -0700512 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900513 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700514
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900515 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800516 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900517 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900518 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800519 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700520 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900521 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900522 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700523 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700524
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900525 const std::string chain = "bw_costly_" + iface;
526 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
527 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900528 "*filter",
529 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900530 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
531 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
532 chain.c_str()),
533 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
534 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900535 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900536 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
537 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
538 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900539 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900540 };
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);
Luke Huang531f5d32018-08-03 15:19:05 +0800544 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900545 }
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) {
Luke Huang531f5d32018-08-03 15:19:05 +0800576 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700577
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900578 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700579
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900580 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900581 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800582 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700583 }
584
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900585 const std::string chain = "bw_costly_" + iface;
586 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900587 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900588 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
589 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900590 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900591 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
592 StringPrintf("-F %s", chain.c_str()),
593 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900594 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900595 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900596
597 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700598
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900599 if (res == 0) {
600 mQuotaIfaces.erase(it);
601 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700602
Luke Huang531f5d32018-08-03 15:19:05 +0800603 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700604}
JP Abgrall8a932722011-07-13 19:17:35 -0700605
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900606int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900607 const auto& sys = android::netdutils::sSyscalls.get();
608 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700609
JP Abgrall69261cb2014-06-19 18:35:24 -0700610 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900611 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800612 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700613 }
614
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900615 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
616 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800617 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900618 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800619 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700620 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900621 // TODO: should we propagate this error?
622 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700623 return 0;
624}
625
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900626int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
627 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900628 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900629 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700630
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900631 // TODO: consider using an alternate template for the delete that does not include the --quota
632 // value. This code works because the --quota value is ignored by deletes
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900633 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
634 alertName.c_str());
635 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
636 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900637 StringAppendF(&alertQuotaCmd, "COMMIT\n");
638
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900639 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700640}
641
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900642int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
643 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900644 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900645 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900646 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
647 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900648 StringAppendF(&alertQuotaCmd, "COMMIT\n");
649
650 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700651}
652
653int BandwidthController::setGlobalAlert(int64_t bytes) {
654 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700655 int res = 0;
656
657 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000658 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800659 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700660 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900661 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700662 res = updateQuota(alertName, bytes);
663 } else {
664 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900665 if (mGlobalAlertTetherCount) {
666 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700667 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
668 }
Luke Huang531f5d32018-08-03 15:19:05 +0800669 if (res) {
670 res = -EREMOTEIO;
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());
Luke Huang531f5d32018-08-03 15:19:05 +0800758 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700759 }
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.");
Luke Huang531f5d32018-08-03 15:19:05 +0800763 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700764 }
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");
Luke Huang531f5d32018-08-03 15:19:05 +0800769 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700770 }
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());
Luke Huang531f5d32018-08-03 15:19:05 +0800778 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700779 }
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());
Luke Huang531f5d32018-08-03 15:19:05 +0800785 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700786 }
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());
Luke Huang531f5d32018-08-03 15:19:05 +0800797 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700798 }
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.");
Luke Huang531f5d32018-08-03 15:19:05 +0800802 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700803 }
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());
Luke Huang531f5d32018-08-03 15:19:05 +0800818 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900819 }
JP Abgrall8a932722011-07-13 19:17:35 -0700820 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900821 if (res == 0) {
822 *alertBytes = bytes;
823 }
JP Abgrall8a932722011-07-13 19:17:35 -0700824 return res;
825}
826
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900827int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700828 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900829 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800830 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700831 }
832
JP Abgrall8a932722011-07-13 19:17:35 -0700833 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900834 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800835 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700836 }
837
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900838 std::string alertName = costName + "Alert";
839 std::string chainName = "bw_costly_" + costName;
840 std::vector<std::string> commands = {
841 "*filter\n",
842 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
843 "COMMIT\n"
844 };
845 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
846 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800847 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900848 }
JP Abgrall8a932722011-07-13 19:17:35 -0700849
850 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900851 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700852}
JP Abgralldb7da582011-09-18 12:57:32 -0700853
JP Abgrall0e540ec2013-08-26 15:13:10 -0700854void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900855 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
856 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700857
858 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900859 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
860 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700861 return;
862 }
863 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900864 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700865}
866
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900867void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
868 std::stringstream stream(ruleList);
869 std::string rule;
870 std::vector<std::string> clearCommands = { "*filter" };
871 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700872
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900873 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
874 while (std::getline(stream, rule, '\n')) {
875 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
876 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
877 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
878
879 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700880 continue;
881 }
882
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900883 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700884 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900885 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700886 }
887 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900888
889 if (clearCommands.size() == 1) {
890 // No rules found.
891 return;
892 }
893
894 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900895 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700896}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900897
898inline const char *BandwidthController::opToString(IptOp op) {
899 switch (op) {
900 case IptOpInsert:
901 return "-I";
902 case IptOpDelete:
903 return "-D";
904 }
905}
906
907inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
908 /*
909 * Must be careful what one rejects with, as upper layer protocols will just
910 * keep on hammering the device until the number of retries are done.
911 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
912 */
913 switch (jumpHandling) {
914 case IptJumpNoAdd:
915 return "";
916 case IptJumpReject:
917 return " --jump REJECT";
918 case IptJumpReturn:
919 return " --jump RETURN";
920 }
921}