blob: 3efc8a3468f9eea95f46f17eda1bdc61b6dea80c [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>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070051
Joel Scherpelz01cc5492017-06-16 10:45:14 +090052#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070053#include "BandwidthController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070054#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090055#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080056#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090057#include "NetdConstants.h"
Chenbo Feng95892f32018-06-07 14:52:02 -070058#include "TrafficController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070059#include "bpf/BpfUtils.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070060
JP Abgralldb7da582011-09-18 12:57:32 -070061/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090062#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090063const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
64const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
65const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
66const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
67const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +090068const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
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 = {
Luke Huangae038f82018-11-05 11:17:31 +0900160 /*
161 * Cleanup rules.
162 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
163 * to allow coexistance.
164 */
165 "*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 ":bw_global_alert -",
174 "COMMIT",
175 "*raw",
176 ":bw_raw_PREROUTING -",
177 "COMMIT",
178 "*mangle",
179 ":bw_mangle_POSTROUTING -",
180 COMMIT_AND_CLOSE};
JP Abgrall0031cea2012-04-17 16:38:23 -0700181
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",
Luke Huangae038f82018-11-05 11:17:31 +0900218
219 "-A bw_INPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700220 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
221 "-A bw_INPUT -p esp -j RETURN",
222 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
223 uidBillingMask),
Chenbo Feng44c0f442018-07-10 16:54:30 -0700224 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700225 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900226
Luke Huangae038f82018-11-05 11:17:31 +0900227 "-A bw_OUTPUT -j bw_global_alert",
Chenbo Feng703798e2018-06-15 17:07:59 -0700228 // Prevents IPSec double counting (Tunnel mode and Transport mode,
229 // respectively)
230 "-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
231 "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700232 useBpf ? "" : "-A bw_OUTPUT -m owner --socket-exists",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900233
Chenbo Feng703798e2018-06-15 17:07:59 -0700234 "-A bw_costly_shared --jump bw_penalty_box",
235 useBpf ? BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND : "",
236 "-A bw_penalty_box --jump bw_happy_box", "-A bw_happy_box --jump bw_data_saver",
237 "-A bw_data_saver -j RETURN",
238 useBpf ? BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND : HAPPY_BOX_MATCH_WHITELIST_COMMAND,
239 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700240
Chenbo Feng703798e2018-06-15 17:07:59 -0700241 "*raw",
242 // Prevents IPSec double counting (Tunnel mode and Transport mode,
243 // respectively)
244 "-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN",
245 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Chenbo Feng703798e2018-06-15 17:07:59 -0700246 useBpf ? StringPrintf("-A bw_raw_PREROUTING -m bpf --object-pinned %s",
247 XT_BPF_INGRESS_PROG_PATH)
Chenbo Feng44c0f442018-07-10 16:54:30 -0700248 : "-A bw_raw_PREROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700249 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700250
Chenbo Feng703798e2018-06-15 17:07:59 -0700251 "*mangle",
252 // Prevents IPSec double counting (Tunnel mode and Transport mode,
253 // respectively)
254 "-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
255 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700256 useBpf ? "" : "-A bw_mangle_POSTROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700257 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x",
258 uidBillingMask), // Clear the mark before sending this packet
259 useBpf ? StringPrintf("-A bw_mangle_POSTROUTING -m bpf --object-pinned %s",
260 XT_BPF_EGRESS_PROG_PATH)
261 : "",
262 COMMIT_AND_CLOSE};
Chenbo Feng5ed17992018-03-13 21:30:49 -0700263 return ipt_basic_accounting_commands;
264}
265
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900266
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900267std::vector<std::string> toStrVec(int num, const char* const strs[]) {
268 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900269}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900270
271} // namespace
272
Chenbo Feng44c0f442018-07-10 16:54:30 -0700273void BandwidthController::setBpfEnabled(bool isEnabled) {
274 mBpfSupported = isEnabled;
Chenbo Fenga121e202018-03-19 11:51:54 -0700275}
276
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900277BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700278}
279
JP Abgrall0e540ec2013-08-26 15:13:10 -0700280void BandwidthController::flushCleanTables(bool doClean) {
281 /* Flush and remove the bw_costly_<iface> tables */
282 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700283
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900284 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900285 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700286}
JP Abgrall0031cea2012-04-17 16:38:23 -0700287
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900288int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700289 /* flush+clean is allowed to fail */
290 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700291 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700292}
293
Luke Huangf44a3c12018-09-07 12:10:12 +0800294int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700295 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900296 mSharedQuotaIfaces.clear();
297 mQuotaIfaces.clear();
298 mGlobalAlertBytes = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900299 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700300
JP Abgrall0e540ec2013-08-26 15:13:10 -0700301 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700302
Chenbo Feng95892f32018-06-07 14:52:02 -0700303 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900304 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700305}
306
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900307int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700308
309 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700310 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700311}
312
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900313std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
314 std::string cmd;
315 const char *chainName = "bw_data_saver";
316 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
317 std::string criticalCommands = enable ?
318 FirewallController::makeCriticalCommands(target, chainName) : "";
319 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900320 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900321 ":%s -\n"
322 "%s"
323 "-A %s%s\n"
324 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
325 return cmd;
326}
327
328int BandwidthController::enableDataSaver(bool enable) {
329 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
330 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
331 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900332}
333
Luke Huang531f5d32018-08-03 15:19:05 +0800334// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900335int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900336 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
337 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700338}
339
Luke Huang531f5d32018-08-03 15:19:05 +0800340// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900341int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900342 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
343 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700344}
345
Luke Huang531f5d32018-08-03 15:19:05 +0800346// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900347int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900348 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
349 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700350}
351
Luke Huang531f5d32018-08-03 15:19:05 +0800352// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900353int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900354 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
355 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700356}
357
Luke Huang531f5d32018-08-03 15:19:05 +0800358int BandwidthController::addNaughtyApps(const std::vector<std::string>& appStrUid) {
359 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpInsert);
360}
361
362int BandwidthController::removeNaughtyApps(const std::vector<std::string>& appStrUid) {
363 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpDelete);
364}
365
366int BandwidthController::addNiceApps(const std::vector<std::string>& appStrUid) {
367 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpInsert);
368}
369
370int BandwidthController::removeNiceApps(const std::vector<std::string>& appStrUid) {
371 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpDelete);
372}
373
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900374int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
375 const std::string& chain, IptJumpOp jumpHandling,
376 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700377 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700378 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
379 if (!isOk(status)) {
380 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700381 }
382 return status.code();
383 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900384 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900385 for (const auto& appStrUid : appStrUids) {
386 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
387 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700388 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900389 StringAppendF(&cmd, "COMMIT\n");
390 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700391}
392
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900393int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700394 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700395 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900396 constexpr char cost[] = "shared";
397 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700398
JP Abgrall8a932722011-07-13 19:17:35 -0700399 if (!maxBytes) {
400 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000401 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700402 return -1;
403 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700404 if (!isIfaceName(iface))
405 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700406
407 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900408 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700409 }
410
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900411 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700412
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900413 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900414 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
415 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900416 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900417 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
418 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900419 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900420 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
421 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900422 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900423 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
424 " --name %s --jump REJECT",
425 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900426 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900427 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900428
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900429 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900430 if (res) {
431 ALOGE("Failed set quota rule");
432 removeInterfaceSharedQuota(iface);
433 return -1;
434 }
435 mSharedQuotaBytes = maxBytes;
436 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700437 }
438
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900439 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900440 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700441 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900442 ALOGE("Failed update quota for %s", cost);
443 removeInterfaceSharedQuota(iface);
444 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700445 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900446 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700447 }
448 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700449}
450
JP Abgrall8a932722011-07-13 19:17:35 -0700451/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900452int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900453 constexpr char cost[] = "shared";
454 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700455
JP Abgrall69261cb2014-06-19 18:35:24 -0700456 if (!isIfaceName(iface))
457 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700458
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900459 auto it = mSharedQuotaIfaces.find(iface);
460
461 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900462 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700463 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700464 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700465
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900466 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900467 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900468 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
469 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900470 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900471 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
472 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900473 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900474 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
475 " --name %s --jump REJECT",
476 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700477 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900478 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900479
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900480 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
481 ALOGE("Failed to remove shared quota on %s", iface.c_str());
482 return -1;
483 }
484
485 int res = 0;
486 mSharedQuotaIfaces.erase(it);
487 if (mSharedQuotaIfaces.empty()) {
488 mSharedQuotaBytes = 0;
489 if (mSharedAlertBytes) {
490 res = removeSharedAlert();
491 if (res == 0) {
492 mSharedAlertBytes = 0;
493 }
494 }
495 }
496
497 return res;
498
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700499}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700500
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900501int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900502 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700503
Luke Huang531f5d32018-08-03 15:19:05 +0800504 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700505
JP Abgrall8a932722011-07-13 19:17:35 -0700506 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000507 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800508 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700509 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700510 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700511 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700512 }
513
JP Abgrall0dad7c22011-06-24 11:58:14 -0700514 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900515 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700516
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900517 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800518 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900519 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900520 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800521 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700522 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900523 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900524 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700525 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700526
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900527 const std::string chain = "bw_costly_" + iface;
528 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
529 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900530 "*filter",
531 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900532 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
533 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
534 chain.c_str()),
535 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
536 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900537 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900538 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
539 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
540 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900541 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900542 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900543 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900544 ALOGE("Failed set quota rule");
545 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800546 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900547 }
548
549 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
550 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700551}
552
JP Abgrall8a932722011-07-13 19:17:35 -0700553int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
554 return getInterfaceQuota("shared", bytes);
555}
556
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900557int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900558 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900559 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700560
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900561 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700562
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900563 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
564 if (!isOk(file)) {
565 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700566 return -1;
567 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900568 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
569 if (!isOk(rv)) {
570 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
571 return -1;
572 }
573 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
574 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700575}
576
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900577int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800578 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700579
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900580 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700581
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900582 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900583 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800584 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700585 }
586
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900587 const std::string chain = "bw_costly_" + iface;
588 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900589 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900590 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
591 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900592 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900593 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
594 StringPrintf("-F %s", chain.c_str()),
595 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900596 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900597 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900598
599 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700600
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900601 if (res == 0) {
602 mQuotaIfaces.erase(it);
603 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700604
Luke Huang531f5d32018-08-03 15:19:05 +0800605 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700606}
JP Abgrall8a932722011-07-13 19:17:35 -0700607
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900608int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900609 const auto& sys = android::netdutils::sSyscalls.get();
610 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700611
JP Abgrall69261cb2014-06-19 18:35:24 -0700612 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900613 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800614 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700615 }
616
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900617 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
618 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800619 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900620 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800621 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700622 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900623 // TODO: should we propagate this error?
624 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700625 return 0;
626}
627
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900628int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
629 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900630 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900631 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700632
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900633 // TODO: consider using an alternate template for the delete that does not include the --quota
634 // value. This code works because the --quota value is ignored by deletes
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900635
Luke Huangae038f82018-11-05 11:17:31 +0900636 /*
637 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
638 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
639 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
640 */
641 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900642 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900643 StringAppendF(&alertQuotaCmd, "COMMIT\n");
644
645 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700646}
647
648int BandwidthController::setGlobalAlert(int64_t bytes) {
649 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700650
651 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000652 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800653 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700654 }
Luke Huang19b49c52018-10-22 12:12:05 +0900655
656 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900657 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700658 res = updateQuota(alertName, bytes);
659 } else {
660 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Luke Huang531f5d32018-08-03 15:19:05 +0800661 if (res) {
662 res = -EREMOTEIO;
663 }
JP Abgrall8a932722011-07-13 19:17:35 -0700664 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900665 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700666 return res;
667}
668
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900669int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700670
671 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700672
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900673 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000674 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700675 return -1;
676 }
Luke Huang19b49c52018-10-22 12:12:05 +0900677
678 int res = 0;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900679 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900680 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700681 return res;
682}
683
684int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900685 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000686 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700687 return -1;
688 }
689 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000690 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700691 return -1;
692 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900693 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700694}
695
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900696int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900697 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700698}
699
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900700int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700701 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900702 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800703 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700704 }
705
JP Abgrall8a932722011-07-13 19:17:35 -0700706 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000707 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800708 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700709 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900710 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700711
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900712 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000713 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800714 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700715 }
716
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900717 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700718}
719
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900720int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700721 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900722 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800723 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700724 }
725
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900726 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700727
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900728 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900729 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800730 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700731 }
732
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900733 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700734}
735
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900736int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
737 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700738 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700739
JP Abgrall69261cb2014-06-19 18:35:24 -0700740 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900741 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800742 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700743 }
744
JP Abgrall8a932722011-07-13 19:17:35 -0700745 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000746 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800747 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700748 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900749
750 std::string alertName = costName + "Alert";
751 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700752 if (*alertBytes) {
753 res = updateQuota(alertName, *alertBytes);
754 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900755 std::vector<std::string> commands = {
756 "*filter\n",
757 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
758 "COMMIT\n"
759 };
760 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
761 if (res) {
762 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800763 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900764 }
JP Abgrall8a932722011-07-13 19:17:35 -0700765 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900766 if (res == 0) {
767 *alertBytes = bytes;
768 }
JP Abgrall8a932722011-07-13 19:17:35 -0700769 return res;
770}
771
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900772int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700773 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900774 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800775 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700776 }
777
JP Abgrall8a932722011-07-13 19:17:35 -0700778 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900779 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800780 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700781 }
782
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900783 std::string alertName = costName + "Alert";
784 std::string chainName = "bw_costly_" + costName;
785 std::vector<std::string> commands = {
786 "*filter\n",
787 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
788 "COMMIT\n"
789 };
790 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
791 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800792 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900793 }
JP Abgrall8a932722011-07-13 19:17:35 -0700794
795 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900796 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700797}
JP Abgralldb7da582011-09-18 12:57:32 -0700798
JP Abgrall0e540ec2013-08-26 15:13:10 -0700799void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900800 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
801 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700802
803 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900804 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
805 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700806 return;
807 }
808 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900809 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700810}
811
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900812void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
813 std::stringstream stream(ruleList);
814 std::string rule;
815 std::vector<std::string> clearCommands = { "*filter" };
816 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700817
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900818 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
819 while (std::getline(stream, rule, '\n')) {
820 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
821 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
822 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
823
824 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700825 continue;
826 }
827
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900828 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700829 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900830 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700831 }
832 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900833
834 if (clearCommands.size() == 1) {
835 // No rules found.
836 return;
837 }
838
839 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900840 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700841}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900842
843inline const char *BandwidthController::opToString(IptOp op) {
844 switch (op) {
845 case IptOpInsert:
846 return "-I";
847 case IptOpDelete:
848 return "-D";
849 }
850}
851
852inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
853 /*
854 * Must be careful what one rejects with, as upper layer protocols will just
855 * keep on hammering the device until the number of retries are done.
856 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
857 */
858 switch (jumpHandling) {
859 case IptJumpNoAdd:
860 return "";
861 case IptJumpReject:
862 return " --jump REJECT";
863 case IptJumpReturn:
864 return " --jump RETURN";
865 }
866}