blob: 5669a96317ac544df64a4083b55a19786d69bf9f [file] [log] [blame]
JP Abgrall4a5f5ca2011-06-15 18:37:39 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
JP Abgralle4788732013-07-02 20:28:45 -070017// #define LOG_NDEBUG 0
JP Abgralldb7da582011-09-18 12:57:32 -070018
19/*
20 * The CommandListener, FrameworkListener don't allow for
21 * multiple calls in parallel to reach the BandwidthController.
22 * If they ever were to allow it, then netd/ would need some tweaking.
23 */
24
Joel Scherpelz01cc5492017-06-16 10:45:14 +090025#include <ctype.h>
JP Abgrall8a932722011-07-13 19:17:35 -070026#include <errno.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070027#include <fcntl.h>
JP Abgralldb7da582011-09-18 12:57:32 -070028#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070029#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070030#include <string.h>
Joel Scherpelz01cc5492017-06-16 10:45:14 +090031#include <string>
32#include <vector>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070033
Matthew Leach2a54d962013-01-14 15:07:12 +000034#define __STDC_FORMAT_MACROS 1
35#include <inttypes.h>
36
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070037#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <sys/wait.h>
41
42#include <linux/netlink.h>
43#include <linux/rtnetlink.h>
44#include <linux/pkt_sched.h>
45
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090046#include "android-base/stringprintf.h"
Lorenzo Colitti13debb82016-03-27 17:46:30 +090047#include "android-base/strings.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070048#define LOG_TAG "BandwidthController"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080050#include <log/log.h>
Rom Lemarchand14150212013-01-24 10:01:04 -080051#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070052
Joel Scherpelz01cc5492017-06-16 10:45:14 +090053#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070054#include "BandwidthController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070055#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090056#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080057#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090058#include "NetdConstants.h"
Chenbo Feng95892f32018-06-07 14:52:02 -070059#include "TrafficController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070060#include "bpf/BpfUtils.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070061
JP Abgralldb7da582011-09-18 12:57:32 -070062/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090063#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090064const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
65const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
66const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
67const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
68const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090069
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090070auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090071
Joel Scherpelzd59526a2017-06-28 16:24:09 +090072using android::base::Join;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090073using android::base::StringAppendF;
74using android::base::StringPrintf;
Chenbo Feng95892f32018-06-07 14:52:02 -070075using android::net::gCtls;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090076using android::netdutils::StatusOr;
Chenbo Feng95892f32018-06-07 14:52:02 -070077using android::netdutils::Status;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090078using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090079
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090080namespace {
81
82const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090083const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090084
Joel Scherpelzbcad6612017-05-30 10:55:11 +090085const char NAUGHTY_CHAIN[] = "bw_penalty_box";
86const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070087
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070088/**
89 * Some comments about the rules:
90 * * Ordering
91 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070092 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070093 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070094 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070095 *
96 * * global quota vs per interface quota
97 * - global quota for all costly interfaces uses a single costly chain:
98 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070099 * iptables -N bw_costly_shared
100 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
101 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
102 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700103 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700104 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900105 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900106 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700107 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700108 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700109 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
110 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700111 *
112 * - quota per interface. This is achieve by having "costly" chains per quota.
113 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700114 * iptables -N bw_costly_iface0
115 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
116 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
117 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700118 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700119 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700120 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900121 * * Penalty box, happy box and data saver.
122 * - bw_penalty box is a blacklist of apps that are rejected.
123 * - bw_happy_box is a whitelist of apps. It always includes all system apps
124 * - bw_data_saver implements data usage restrictions.
125 * - Via the UI the user can add and remove apps from the whitelist and
126 * blacklist, and turn on/off data saver.
127 * - The blacklist takes precedence over the whitelist and the whitelist
128 * takes precedence over data saver.
129 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700130 * * bw_penalty_box handling:
131 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900132 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700133 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700134 * --jump REJECT --reject-with icmp-port-unreachable
135 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700136 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900137 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700138 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700139 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700140 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900141 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900142 * * bw_data_saver handling:
143 * - The bw_data_saver comes after the happy box.
144 * Enable data saver:
145 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
146 * Disable data saver:
147 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700148 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900149
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900150const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Chenbo Feng703798e2018-06-15 17:07:59 -0700151const std::string HAPPY_BOX_MATCH_WHITELIST_COMMAND =
152 StringPrintf("-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
153const std::string BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND = StringPrintf(
154 "-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
155const std::string BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND = StringPrintf(
156 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900157
158static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700159 /*
160 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700161 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700162 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700163 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900164 "*filter",
165 ":bw_INPUT -",
166 ":bw_OUTPUT -",
167 ":bw_FORWARD -",
168 ":bw_happy_box -",
169 ":bw_penalty_box -",
170 ":bw_data_saver -",
171 ":bw_costly_shared -",
172 "COMMIT",
173 "*raw",
174 ":bw_raw_PREROUTING -",
175 "COMMIT",
176 "*mangle",
177 ":bw_mangle_POSTROUTING -",
178 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700179};
180
Benedict Wongb9baf262017-12-03 15:43:08 -0800181static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
182
183/**
184 * Basic commands for creation of hooks into data accounting and data boxes.
185 *
186 * Included in these commands are rules to prevent the double-counting of IPsec
187 * packets. The general overview is as follows:
188 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
189 * completely accurate, and count only the outer packet. As such, the inner
190 * packet must be ignored, which is done through the use of two rules: use
191 * of the policy module (for tunnel mode), and VTI interface checks (for
192 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
193 * ipsec*
194 * > Outbound UID billing can always be done with the outer packets, due to the
195 * ability to always find the correct UID (based on the skb->sk). As such,
196 * the inner packets should be ignored based on the policy module, or the
197 * output interface if a VTI (ipsec+)
198 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
199 * opened the encap socket, and as such, should be billed as early as
200 * possible (for transport mode; tunnel mode usage should be billed to
201 * sending/receiving application). Due to the inner packet being
202 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
203 * has to be applied to prevent counting a second time.
204 * > Inbound ESP has no socket, and as such must be accounted later. ESP
205 * protocol packets are skipped via a blanket rule.
206 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
207 * ignore rule in the input chain would actually break the INPUT chain;
208 * Those rules are designed to ignore inner packets, and in the tunnel
209 * mode UDP, or any ESP case, we would not have billed the outer packet.
210 *
211 * See go/ipsec-data-accounting for more information.
212 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800213
Chenbo Feng95892f32018-06-07 14:52:02 -0700214const std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
Chenbo Feng5ed17992018-03-13 21:30:49 -0700215 const std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700216 "*filter",
217 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
218 "-A bw_INPUT -p esp -j RETURN",
219 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
220 uidBillingMask),
Chenbo Feng44c0f442018-07-10 16:54:30 -0700221 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700222 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900223
Chenbo Feng703798e2018-06-15 17:07:59 -0700224 // Prevents IPSec double counting (Tunnel mode and Transport mode,
225 // respectively)
226 "-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
227 "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700228 useBpf ? "" : "-A bw_OUTPUT -m owner --socket-exists",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900229
Chenbo Feng703798e2018-06-15 17:07:59 -0700230 "-A bw_costly_shared --jump bw_penalty_box",
231 useBpf ? BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND : "",
232 "-A bw_penalty_box --jump bw_happy_box", "-A bw_happy_box --jump bw_data_saver",
233 "-A bw_data_saver -j RETURN",
234 useBpf ? BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND : HAPPY_BOX_MATCH_WHITELIST_COMMAND,
235 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700236
Chenbo Feng703798e2018-06-15 17:07:59 -0700237 "*raw",
238 // Prevents IPSec double counting (Tunnel mode and Transport mode,
239 // respectively)
240 "-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN",
241 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
Chenbo Feng703798e2018-06-15 17:07:59 -0700242 useBpf ? StringPrintf("-A bw_raw_PREROUTING -m bpf --object-pinned %s",
243 XT_BPF_INGRESS_PROG_PATH)
Chenbo Feng44c0f442018-07-10 16:54:30 -0700244 : "-A bw_raw_PREROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700245 "COMMIT",
Chenbo Feng5ed17992018-03-13 21:30:49 -0700246
Chenbo Feng703798e2018-06-15 17:07:59 -0700247 "*mangle",
248 // Prevents IPSec double counting (Tunnel mode and Transport mode,
249 // respectively)
250 "-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
251 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
Chenbo Feng44c0f442018-07-10 16:54:30 -0700252 useBpf ? "" : "-A bw_mangle_POSTROUTING -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700253 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x",
254 uidBillingMask), // Clear the mark before sending this packet
255 useBpf ? StringPrintf("-A bw_mangle_POSTROUTING -m bpf --object-pinned %s",
256 XT_BPF_EGRESS_PROG_PATH)
257 : "",
258 COMMIT_AND_CLOSE};
Chenbo Feng5ed17992018-03-13 21:30:49 -0700259 return ipt_basic_accounting_commands;
260}
261
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900262
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900263std::vector<std::string> toStrVec(int num, const char* const strs[]) {
264 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900265}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900266
267} // namespace
268
Chenbo Feng44c0f442018-07-10 16:54:30 -0700269void BandwidthController::setBpfEnabled(bool isEnabled) {
270 mBpfSupported = isEnabled;
Chenbo Fenga121e202018-03-19 11:51:54 -0700271}
272
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900273BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700274}
275
JP Abgrall0e540ec2013-08-26 15:13:10 -0700276void BandwidthController::flushCleanTables(bool doClean) {
277 /* Flush and remove the bw_costly_<iface> tables */
278 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700279
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900280 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900281 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700282}
JP Abgrall0031cea2012-04-17 16:38:23 -0700283
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900284int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700285 /* flush+clean is allowed to fail */
286 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700287 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700288}
289
Luke Huangf44a3c12018-09-07 12:10:12 +0800290int BandwidthController::enableBandwidthControl() {
JP Abgralldb7da582011-09-18 12:57:32 -0700291 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900292 mSharedQuotaIfaces.clear();
293 mQuotaIfaces.clear();
294 mGlobalAlertBytes = 0;
295 mGlobalAlertTetherCount = 0;
296 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700297
JP Abgrall0e540ec2013-08-26 15:13:10 -0700298 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700299
Chenbo Feng95892f32018-06-07 14:52:02 -0700300 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900301 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700302}
303
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900304int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700305
306 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700307 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700308}
309
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900310std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
311 std::string cmd;
312 const char *chainName = "bw_data_saver";
313 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
314 std::string criticalCommands = enable ?
315 FirewallController::makeCriticalCommands(target, chainName) : "";
316 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900317 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900318 ":%s -\n"
319 "%s"
320 "-A %s%s\n"
321 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
322 return cmd;
323}
324
325int BandwidthController::enableDataSaver(bool enable) {
326 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
327 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
328 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900329}
330
Luke Huang531f5d32018-08-03 15:19:05 +0800331// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900332int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900333 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
334 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700335}
336
Luke Huang531f5d32018-08-03 15:19:05 +0800337// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900338int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900339 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
340 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700341}
342
Luke Huang531f5d32018-08-03 15:19:05 +0800343// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900344int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900345 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
346 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700347}
348
Luke Huang531f5d32018-08-03 15:19:05 +0800349// TODO: Remove after removing these commands in CommandListener
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900350int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900351 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
352 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700353}
354
Luke Huang531f5d32018-08-03 15:19:05 +0800355int BandwidthController::addNaughtyApps(const std::vector<std::string>& appStrUid) {
356 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpInsert);
357}
358
359int BandwidthController::removeNaughtyApps(const std::vector<std::string>& appStrUid) {
360 return manipulateSpecialApps(appStrUid, NAUGHTY_CHAIN, IptJumpReject, IptOpDelete);
361}
362
363int BandwidthController::addNiceApps(const std::vector<std::string>& appStrUid) {
364 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpInsert);
365}
366
367int BandwidthController::removeNiceApps(const std::vector<std::string>& appStrUid) {
368 return manipulateSpecialApps(appStrUid, NICE_CHAIN, IptJumpReturn, IptOpDelete);
369}
370
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900371int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
372 const std::string& chain, IptJumpOp jumpHandling,
373 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700374 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700375 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
376 if (!isOk(status)) {
377 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700378 }
379 return status.code();
380 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900381 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900382 for (const auto& appStrUid : appStrUids) {
383 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
384 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700385 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900386 StringAppendF(&cmd, "COMMIT\n");
387 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700388}
389
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900390int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700391 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700392 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900393 constexpr char cost[] = "shared";
394 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700395
JP Abgrall8a932722011-07-13 19:17:35 -0700396 if (!maxBytes) {
397 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000398 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700399 return -1;
400 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700401 if (!isIfaceName(iface))
402 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700403
404 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900405 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700406 }
407
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900408 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700409
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900410 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900411 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
412 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900413 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900414 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
415 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900416 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900417 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
418 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900419 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900420 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
421 " --name %s --jump REJECT",
422 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900423 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900424 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900425
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900426 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900427 if (res) {
428 ALOGE("Failed set quota rule");
429 removeInterfaceSharedQuota(iface);
430 return -1;
431 }
432 mSharedQuotaBytes = maxBytes;
433 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700434 }
435
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900436 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900437 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700438 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900439 ALOGE("Failed update quota for %s", cost);
440 removeInterfaceSharedQuota(iface);
441 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700442 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900443 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700444 }
445 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700446}
447
JP Abgrall8a932722011-07-13 19:17:35 -0700448/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900449int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900450 constexpr char cost[] = "shared";
451 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700452
JP Abgrall69261cb2014-06-19 18:35:24 -0700453 if (!isIfaceName(iface))
454 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700455
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900456 auto it = mSharedQuotaIfaces.find(iface);
457
458 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900459 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700460 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700461 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700462
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900463 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900464 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900465 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
466 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900467 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900468 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
469 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900470 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900471 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
472 " --name %s --jump REJECT",
473 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700474 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900475 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900476
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900477 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
478 ALOGE("Failed to remove shared quota on %s", iface.c_str());
479 return -1;
480 }
481
482 int res = 0;
483 mSharedQuotaIfaces.erase(it);
484 if (mSharedQuotaIfaces.empty()) {
485 mSharedQuotaBytes = 0;
486 if (mSharedAlertBytes) {
487 res = removeSharedAlert();
488 if (res == 0) {
489 mSharedAlertBytes = 0;
490 }
491 }
492 }
493
494 return res;
495
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700496}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700497
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900498int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900499 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700500
Luke Huang531f5d32018-08-03 15:19:05 +0800501 if (!isIfaceName(iface)) return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700502
JP Abgrall8a932722011-07-13 19:17:35 -0700503 if (!maxBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000504 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800505 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700506 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700507 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700508 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700509 }
510
JP Abgrall0dad7c22011-06-24 11:58:14 -0700511 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900512 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700513
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900514 if (it != mQuotaIfaces.end()) {
Luke Huang531f5d32018-08-03 15:19:05 +0800515 if (int res = updateQuota(cost, maxBytes)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900516 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900517 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800518 return res;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700519 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900520 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900521 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700522 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700523
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900524 const std::string chain = "bw_costly_" + iface;
525 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
526 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900527 "*filter",
528 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900529 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
530 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
531 chain.c_str()),
532 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
533 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900534 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900535 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
536 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
537 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900538 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900539 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900540 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900541 ALOGE("Failed set quota rule");
542 removeInterfaceQuota(iface);
Luke Huang531f5d32018-08-03 15:19:05 +0800543 return -EREMOTEIO;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900544 }
545
546 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
547 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700548}
549
JP Abgrall8a932722011-07-13 19:17:35 -0700550int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
551 return getInterfaceQuota("shared", bytes);
552}
553
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900554int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900555 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900556 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700557
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900558 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700559
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900560 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
561 if (!isOk(file)) {
562 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700563 return -1;
564 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900565 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
566 if (!isOk(rv)) {
567 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
568 return -1;
569 }
570 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
571 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700572}
573
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900574int BandwidthController::removeInterfaceQuota(const std::string& iface) {
Luke Huang531f5d32018-08-03 15:19:05 +0800575 if (!isIfaceName(iface)) return -EINVAL;
JP Abgrall26e0d492011-06-24 19:21:51 -0700576
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900577 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700578
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900579 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900580 ALOGE("No such iface %s to delete", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800581 return -ENODEV;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700582 }
583
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900584 const std::string chain = "bw_costly_" + iface;
585 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900586 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900587 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
588 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900589 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900590 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
591 StringPrintf("-F %s", chain.c_str()),
592 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900593 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900594 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900595
596 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700597
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900598 if (res == 0) {
599 mQuotaIfaces.erase(it);
600 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700601
Luke Huang531f5d32018-08-03 15:19:05 +0800602 return res ? -EREMOTEIO : 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700603}
JP Abgrall8a932722011-07-13 19:17:35 -0700604
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900605int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900606 const auto& sys = android::netdutils::sSyscalls.get();
607 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700608
JP Abgrall69261cb2014-06-19 18:35:24 -0700609 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900610 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800611 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700612 }
613
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900614 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
615 if (!isOk(file)) {
Luke Huang531f5d32018-08-03 15:19:05 +0800616 int res = errno;
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900617 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800618 return -res;
JP Abgrall8a932722011-07-13 19:17:35 -0700619 }
Bernie Innocenti0bdee432018-10-12 22:24:33 +0900620 // TODO: should we propagate this error?
621 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
JP Abgrall8a932722011-07-13 19:17:35 -0700622 return 0;
623}
624
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900625int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
626 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900627 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900628 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700629
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900630 // TODO: consider using an alternate template for the delete that does not include the --quota
631 // value. This code works because the --quota value is ignored by deletes
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900632 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
633 alertName.c_str());
634 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
635 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900636 StringAppendF(&alertQuotaCmd, "COMMIT\n");
637
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900638 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700639}
640
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900641int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
642 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900643 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900644 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900645 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
646 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900647 StringAppendF(&alertQuotaCmd, "COMMIT\n");
648
649 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700650}
651
652int BandwidthController::setGlobalAlert(int64_t bytes) {
653 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700654 int res = 0;
655
656 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000657 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800658 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700659 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900660 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700661 res = updateQuota(alertName, bytes);
662 } else {
663 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900664 if (mGlobalAlertTetherCount) {
665 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700666 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
667 }
Luke Huang531f5d32018-08-03 15:19:05 +0800668 if (res) {
669 res = -EREMOTEIO;
670 }
JP Abgrall8a932722011-07-13 19:17:35 -0700671 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900672 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700673 return res;
674}
675
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900676int BandwidthController::setGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700677 const char *alertName = ALERT_GLOBAL_NAME;
678 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700679
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900680 mGlobalAlertTetherCount++;
681 ALOGV("setGlobalAlertInForwardChain(): %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700682
683 /*
684 * If there is no globalAlert active we are done.
685 * If there is an active globalAlert but this is not the 1st
686 * tether, we are also done.
687 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900688 if (!mGlobalAlertBytes || mGlobalAlertTetherCount != 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700689 return 0;
690 }
691
692 /* We only add the rule if this was the 1st tether added. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900693 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700694 return res;
695}
696
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900697int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700698
699 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700700 int res = 0;
701
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900702 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000703 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700704 return -1;
705 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900706 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
707 if (mGlobalAlertTetherCount) {
708 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700709 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900710 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700711 return res;
712}
713
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900714int BandwidthController::removeGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700715 int res = 0;
716 const char *alertName = ALERT_GLOBAL_NAME;
717
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900718 if (!mGlobalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000719 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700720 return -1;
721 }
722
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900723 mGlobalAlertTetherCount--;
JP Abgrallc6c67342011-10-07 16:28:54 -0700724 /*
725 * If there is no globalAlert active we are done.
726 * If there is an active globalAlert but there are more
727 * tethers, we are also done.
728 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900729 if (!mGlobalAlertBytes || mGlobalAlertTetherCount >= 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700730 return 0;
731 }
732
733 /* We only detete the rule if this was the last tether removed. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900734 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700735 return res;
736}
737
JP Abgrall8a932722011-07-13 19:17:35 -0700738int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900739 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000740 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700741 return -1;
742 }
743 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000744 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700745 return -1;
746 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900747 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700748}
749
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900750int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900751 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700752}
753
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900754int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700755 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900756 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800757 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700758 }
759
JP Abgrall8a932722011-07-13 19:17:35 -0700760 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000761 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800762 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700763 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900764 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700765
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900766 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000767 ALOGE("Need to have a prior interface quota set to set an alert");
Luke Huang531f5d32018-08-03 15:19:05 +0800768 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700769 }
770
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900771 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700772}
773
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900774int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700775 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900776 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800777 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700778 }
779
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900780 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700781
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900782 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900783 ALOGE("No prior alert set for interface %s", iface.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800784 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700785 }
786
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900787 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700788}
789
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900790int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
791 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700792 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700793
JP Abgrall69261cb2014-06-19 18:35:24 -0700794 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900795 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800796 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700797 }
798
JP Abgrall8a932722011-07-13 19:17:35 -0700799 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000800 ALOGE("Invalid bytes value. 1..max_int64.");
Luke Huang531f5d32018-08-03 15:19:05 +0800801 return -ERANGE;
JP Abgrall8a932722011-07-13 19:17:35 -0700802 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900803
804 std::string alertName = costName + "Alert";
805 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700806 if (*alertBytes) {
807 res = updateQuota(alertName, *alertBytes);
808 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900809 std::vector<std::string> commands = {
810 "*filter\n",
811 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
812 "COMMIT\n"
813 };
814 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
815 if (res) {
816 ALOGE("Failed to set costly alert for %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800817 res = -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900818 }
JP Abgrall8a932722011-07-13 19:17:35 -0700819 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900820 if (res == 0) {
821 *alertBytes = bytes;
822 }
JP Abgrall8a932722011-07-13 19:17:35 -0700823 return res;
824}
825
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900826int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700827 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900828 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800829 return -EINVAL;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700830 }
831
JP Abgrall8a932722011-07-13 19:17:35 -0700832 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900833 ALOGE("No prior alert set for %s alert", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800834 return -ENOENT;
JP Abgrall8a932722011-07-13 19:17:35 -0700835 }
836
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900837 std::string alertName = costName + "Alert";
838 std::string chainName = "bw_costly_" + costName;
839 std::vector<std::string> commands = {
840 "*filter\n",
841 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
842 "COMMIT\n"
843 };
844 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
845 ALOGE("Failed to remove costly alert %s", costName.c_str());
Luke Huang531f5d32018-08-03 15:19:05 +0800846 return -EREMOTEIO;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900847 }
JP Abgrall8a932722011-07-13 19:17:35 -0700848
849 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900850 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700851}
JP Abgralldb7da582011-09-18 12:57:32 -0700852
JP Abgrall0e540ec2013-08-26 15:13:10 -0700853void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900854 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
855 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700856
857 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900858 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
859 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700860 return;
861 }
862 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900863 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700864}
865
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900866void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
867 std::stringstream stream(ruleList);
868 std::string rule;
869 std::vector<std::string> clearCommands = { "*filter" };
870 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700871
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900872 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
873 while (std::getline(stream, rule, '\n')) {
874 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
875 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
876 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
877
878 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700879 continue;
880 }
881
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900882 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700883 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900884 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700885 }
886 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900887
888 if (clearCommands.size() == 1) {
889 // No rules found.
890 return;
891 }
892
893 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900894 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700895}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900896
897inline const char *BandwidthController::opToString(IptOp op) {
898 switch (op) {
899 case IptOpInsert:
900 return "-I";
901 case IptOpDelete:
902 return "-D";
903 }
904}
905
906inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
907 /*
908 * Must be careful what one rejects with, as upper layer protocols will just
909 * keep on hammering the device until the number of retries are done.
910 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
911 */
912 switch (jumpHandling) {
913 case IptJumpNoAdd:
914 return "";
915 case IptJumpReject:
916 return " --jump REJECT";
917 case IptJumpReturn:
918 return " --jump RETURN";
919 }
920}