blob: 4abbc61f65e1b148941e69dd44ac9dfa8bc4df1f [file] [log] [blame]
JP Abgrall4a5f5ca2011-06-15 18:37:39 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
JP Abgralle4788732013-07-02 20:28:45 -070017// #define LOG_NDEBUG 0
JP Abgralldb7da582011-09-18 12:57:32 -070018
19/*
20 * The CommandListener, FrameworkListener don't allow for
21 * multiple calls in parallel to reach the BandwidthController.
22 * If they ever were to allow it, then netd/ would need some tweaking.
23 */
24
Joel Scherpelz01cc5492017-06-16 10:45:14 +090025#include <ctype.h>
JP Abgrall8a932722011-07-13 19:17:35 -070026#include <errno.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070027#include <fcntl.h>
JP Abgralldb7da582011-09-18 12:57:32 -070028#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070029#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070030#include <string.h>
Joel Scherpelz01cc5492017-06-16 10:45:14 +090031#include <string>
32#include <vector>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070033
Matthew Leach2a54d962013-01-14 15:07:12 +000034#define __STDC_FORMAT_MACROS 1
35#include <inttypes.h>
36
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070037#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <sys/wait.h>
41
42#include <linux/netlink.h>
43#include <linux/rtnetlink.h>
44#include <linux/pkt_sched.h>
45
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090046#include "android-base/stringprintf.h"
Lorenzo Colitti13debb82016-03-27 17:46:30 +090047#include "android-base/strings.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070048#define LOG_TAG "BandwidthController"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080050#include <log/log.h>
Rom Lemarchand14150212013-01-24 10:01:04 -080051#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070052
Joel Scherpelz01cc5492017-06-16 10:45:14 +090053#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070054#include "BandwidthController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070055#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090056#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080057#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090058#include "NetdConstants.h"
Chenbo Feng95892f32018-06-07 14:52:02 -070059#include "TrafficController.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070060#include "bpf/BpfUtils.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070061
JP Abgralldb7da582011-09-18 12:57:32 -070062/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090063#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090064const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
65const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
66const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
67const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
68const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090069
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090070auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090071
Joel Scherpelzd59526a2017-06-28 16:24:09 +090072using android::base::Join;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090073using android::base::StringAppendF;
74using android::base::StringPrintf;
Chenbo Feng95892f32018-06-07 14:52:02 -070075using android::bpf::XT_BPF_BLACKLIST_PROG_PATH;
Chenbo Feng5ed17992018-03-13 21:30:49 -070076using android::bpf::XT_BPF_EGRESS_PROG_PATH;
77using android::bpf::XT_BPF_INGRESS_PROG_PATH;
Chenbo Feng95892f32018-06-07 14:52:02 -070078using android::bpf::XT_BPF_WHITELIST_PROG_PATH;
79using android::net::gCtls;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090080using android::netdutils::StatusOr;
Chenbo Feng95892f32018-06-07 14:52:02 -070081using android::netdutils::Status;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090082using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090083
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090084namespace {
85
86const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090087const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090088
Joel Scherpelzbcad6612017-05-30 10:55:11 +090089const char NAUGHTY_CHAIN[] = "bw_penalty_box";
90const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070091
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070092/**
93 * Some comments about the rules:
94 * * Ordering
95 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070096 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070097 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070098 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070099 *
100 * * global quota vs per interface quota
101 * - global quota for all costly interfaces uses a single costly chain:
102 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700103 * iptables -N bw_costly_shared
104 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
105 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
106 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700107 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700108 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900109 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900110 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700111 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700112 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700113 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
114 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700115 *
116 * - quota per interface. This is achieve by having "costly" chains per quota.
117 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700118 * iptables -N bw_costly_iface0
119 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
120 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
121 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700122 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700123 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700124 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900125 * * Penalty box, happy box and data saver.
126 * - bw_penalty box is a blacklist of apps that are rejected.
127 * - bw_happy_box is a whitelist of apps. It always includes all system apps
128 * - bw_data_saver implements data usage restrictions.
129 * - Via the UI the user can add and remove apps from the whitelist and
130 * blacklist, and turn on/off data saver.
131 * - The blacklist takes precedence over the whitelist and the whitelist
132 * takes precedence over data saver.
133 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700134 * * bw_penalty_box handling:
135 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900136 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700137 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700138 * --jump REJECT --reject-with icmp-port-unreachable
139 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700140 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900141 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700142 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700143 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700144 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900145 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900146 * * bw_data_saver handling:
147 * - The bw_data_saver comes after the happy box.
148 * Enable data saver:
149 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
150 * Disable data saver:
151 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700152 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900153
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900154const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Chenbo Feng703798e2018-06-15 17:07:59 -0700155const std::string HAPPY_BOX_MATCH_WHITELIST_COMMAND =
156 StringPrintf("-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
157const std::string BPF_HAPPY_BOX_MATCH_WHITELIST_COMMAND = StringPrintf(
158 "-I bw_happy_box -m bpf --object-pinned %s -j RETURN", XT_BPF_WHITELIST_PROG_PATH);
159const std::string BPF_PENALTY_BOX_MATCH_BLACKLIST_COMMAND = StringPrintf(
160 "-I bw_penalty_box -m bpf --object-pinned %s -j REJECT", XT_BPF_BLACKLIST_PROG_PATH);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900161
162static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700163 /*
164 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700165 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700166 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700167 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900168 "*filter",
169 ":bw_INPUT -",
170 ":bw_OUTPUT -",
171 ":bw_FORWARD -",
172 ":bw_happy_box -",
173 ":bw_penalty_box -",
174 ":bw_data_saver -",
175 ":bw_costly_shared -",
176 "COMMIT",
177 "*raw",
178 ":bw_raw_PREROUTING -",
179 "COMMIT",
180 "*mangle",
181 ":bw_mangle_POSTROUTING -",
182 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700183};
184
Benedict Wongb9baf262017-12-03 15:43:08 -0800185static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
186
187/**
188 * Basic commands for creation of hooks into data accounting and data boxes.
189 *
190 * Included in these commands are rules to prevent the double-counting of IPsec
191 * packets. The general overview is as follows:
192 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
193 * completely accurate, and count only the outer packet. As such, the inner
194 * packet must be ignored, which is done through the use of two rules: use
195 * of the policy module (for tunnel mode), and VTI interface checks (for
196 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
197 * ipsec*
198 * > Outbound UID billing can always be done with the outer packets, due to the
199 * ability to always find the correct UID (based on the skb->sk). As such,
200 * the inner packets should be ignored based on the policy module, or the
201 * output interface if a VTI (ipsec+)
202 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
203 * opened the encap socket, and as such, should be billed as early as
204 * possible (for transport mode; tunnel mode usage should be billed to
205 * sending/receiving application). Due to the inner packet being
206 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
207 * has to be applied to prevent counting a second time.
208 * > Inbound ESP has no socket, and as such must be accounted later. ESP
209 * protocol packets are skipped via a blanket rule.
210 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
211 * ignore rule in the input chain would actually break the INPUT chain;
212 * Those rules are designed to ignore inner packets, and in the tunnel
213 * mode UDP, or any ESP case, we would not have billed the outer packet.
214 *
215 * See go/ipsec-data-accounting for more information.
216 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800217
Chenbo Feng95892f32018-06-07 14:52:02 -0700218const std::vector<std::string> getBasicAccountingCommands(const bool useBpf) {
Chenbo Feng5ed17992018-03-13 21:30:49 -0700219 const std::vector<std::string> ipt_basic_accounting_commands = {
Chenbo Feng703798e2018-06-15 17:07:59 -0700220 "*filter",
221 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
222 "-A bw_INPUT -p esp -j RETURN",
223 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
224 uidBillingMask),
Chenbo Feng44c0f442018-07-10 16:54:30 -0700225 useBpf ? "" : "-A bw_INPUT -m owner --socket-exists",
Chenbo Feng703798e2018-06-15 17:07:59 -0700226 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900227
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
294int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700295 char value[PROPERTY_VALUE_MAX];
296
297 if (!force) {
298 property_get("persist.bandwidth.enable", value, "1");
299 if (!strcmp(value, "0"))
300 return 0;
301 }
JP Abgrall8a932722011-07-13 19:17:35 -0700302
JP Abgralldb7da582011-09-18 12:57:32 -0700303 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900304 mSharedQuotaIfaces.clear();
305 mQuotaIfaces.clear();
306 mGlobalAlertBytes = 0;
307 mGlobalAlertTetherCount = 0;
308 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700309
JP Abgrall0e540ec2013-08-26 15:13:10 -0700310 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700311
Chenbo Feng95892f32018-06-07 14:52:02 -0700312 std::string commands = Join(getBasicAccountingCommands(mBpfSupported), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900313 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700314}
315
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900316int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700317
318 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700319 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700320}
321
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900322std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
323 std::string cmd;
324 const char *chainName = "bw_data_saver";
325 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
326 std::string criticalCommands = enable ?
327 FirewallController::makeCriticalCommands(target, chainName) : "";
328 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900329 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900330 ":%s -\n"
331 "%s"
332 "-A %s%s\n"
333 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
334 return cmd;
335}
336
337int BandwidthController::enableDataSaver(bool enable) {
338 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
339 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
340 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900341}
342
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900343int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900344 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
345 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700346}
347
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900348int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900349 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
350 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700351}
352
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900353int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900354 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
355 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700356}
357
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900358int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900359 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
360 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700361}
362
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900363int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
364 const std::string& chain, IptJumpOp jumpHandling,
365 IptOp op) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700366 if (mBpfSupported) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700367 Status status = gCtls->trafficCtrl.updateUidOwnerMap(appStrUids, jumpHandling, op);
368 if (!isOk(status)) {
369 ALOGE("unable to update the Bandwidth Uid Map: %s", toString(status).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700370 }
371 return status.code();
372 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900373 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900374 for (const auto& appStrUid : appStrUids) {
375 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
376 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700377 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900378 StringAppendF(&cmd, "COMMIT\n");
379 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700380}
381
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900382int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700383 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700384 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900385 constexpr char cost[] = "shared";
386 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700387
JP Abgrall8a932722011-07-13 19:17:35 -0700388 if (!maxBytes) {
389 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000390 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700391 return -1;
392 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700393 if (!isIfaceName(iface))
394 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700395
396 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900397 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700398 }
399
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900400 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700401
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900402 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900403 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
404 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900405 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900406 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
407 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900408 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900409 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
410 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900411 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900412 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
413 " --name %s --jump REJECT",
414 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900415 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900416 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900417
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900418 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900419 if (res) {
420 ALOGE("Failed set quota rule");
421 removeInterfaceSharedQuota(iface);
422 return -1;
423 }
424 mSharedQuotaBytes = maxBytes;
425 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700426 }
427
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900428 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900429 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700430 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900431 ALOGE("Failed update quota for %s", cost);
432 removeInterfaceSharedQuota(iface);
433 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700434 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900435 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700436 }
437 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700438}
439
JP Abgrall8a932722011-07-13 19:17:35 -0700440/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900441int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900442 constexpr char cost[] = "shared";
443 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700444
JP Abgrall69261cb2014-06-19 18:35:24 -0700445 if (!isIfaceName(iface))
446 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700447
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900448 auto it = mSharedQuotaIfaces.find(iface);
449
450 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900451 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700452 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700453 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700454
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900455 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900456 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900457 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
458 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900459 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900460 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
461 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900462 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900463 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
464 " --name %s --jump REJECT",
465 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700466 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900467 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900468
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900469 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
470 ALOGE("Failed to remove shared quota on %s", iface.c_str());
471 return -1;
472 }
473
474 int res = 0;
475 mSharedQuotaIfaces.erase(it);
476 if (mSharedQuotaIfaces.empty()) {
477 mSharedQuotaBytes = 0;
478 if (mSharedAlertBytes) {
479 res = removeSharedAlert();
480 if (res == 0) {
481 mSharedAlertBytes = 0;
482 }
483 }
484 }
485
486 return res;
487
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700488}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700489
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900490int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900491 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700492
JP Abgrall69261cb2014-06-19 18:35:24 -0700493 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700494 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700495
JP Abgrall8a932722011-07-13 19:17:35 -0700496 if (!maxBytes) {
497 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000498 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700499 return -1;
500 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700501 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700502 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700503 }
504
JP Abgrall0dad7c22011-06-24 11:58:14 -0700505 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900506 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700507
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900508 if (it != mQuotaIfaces.end()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900509 if (updateQuota(cost, maxBytes) != 0) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900510 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900511 removeInterfaceQuota(iface);
512 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700513 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900514 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900515 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700516 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700517
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900518 const std::string chain = "bw_costly_" + iface;
519 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
520 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900521 "*filter",
522 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900523 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
524 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
525 chain.c_str()),
526 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
527 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900528 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900529 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
530 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
531 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900532 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900533 };
534
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900535 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900536 ALOGE("Failed set quota rule");
537 removeInterfaceQuota(iface);
538 return -1;
539 }
540
541 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
542 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700543}
544
JP Abgrall8a932722011-07-13 19:17:35 -0700545int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
546 return getInterfaceQuota("shared", bytes);
547}
548
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900549int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900550 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900551 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700552
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900553 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700554
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900555 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
556 if (!isOk(file)) {
557 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700558 return -1;
559 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900560 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
561 if (!isOk(rv)) {
562 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
563 return -1;
564 }
565 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
566 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700567}
568
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900569int BandwidthController::removeInterfaceQuota(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700570 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700571 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700572
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900573 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700574
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900575 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900576 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700577 return -1;
578 }
579
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900580 const std::string chain = "bw_costly_" + iface;
581 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900582 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900583 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
584 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900585 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900586 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
587 StringPrintf("-F %s", chain.c_str()),
588 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900589 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900590 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900591
592 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700593
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900594 if (res == 0) {
595 mQuotaIfaces.erase(it);
596 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700597
598 return res;
599}
JP Abgrall8a932722011-07-13 19:17:35 -0700600
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900601int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900602 const auto& sys = android::netdutils::sSyscalls.get();
603 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700604
JP Abgrall69261cb2014-06-19 18:35:24 -0700605 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900606 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700607 return -1;
608 }
609
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900610 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
611 if (!isOk(file)) {
612 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700613 return -1;
614 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900615 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700616 return 0;
617}
618
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900619int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
620 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900621 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900622 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700623
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900624 // TODO: consider using an alternate template for the delete that does not include the --quota
625 // value. This code works because the --quota value is ignored by deletes
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900626 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
627 alertName.c_str());
628 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
629 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900630 StringAppendF(&alertQuotaCmd, "COMMIT\n");
631
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900632 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700633}
634
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900635int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
636 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900637 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900638 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900639 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
640 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900641 StringAppendF(&alertQuotaCmd, "COMMIT\n");
642
643 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700644}
645
646int BandwidthController::setGlobalAlert(int64_t bytes) {
647 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700648 int res = 0;
649
650 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000651 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700652 return -1;
653 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900654 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700655 res = updateQuota(alertName, bytes);
656 } else {
657 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900658 if (mGlobalAlertTetherCount) {
659 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700660 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
661 }
JP Abgrall8a932722011-07-13 19:17:35 -0700662 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900663 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700664 return res;
665}
666
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900667int BandwidthController::setGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700668 const char *alertName = ALERT_GLOBAL_NAME;
669 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700670
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900671 mGlobalAlertTetherCount++;
672 ALOGV("setGlobalAlertInForwardChain(): %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700673
674 /*
675 * If there is no globalAlert active we are done.
676 * If there is an active globalAlert but this is not the 1st
677 * tether, we are also done.
678 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900679 if (!mGlobalAlertBytes || mGlobalAlertTetherCount != 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700680 return 0;
681 }
682
683 /* We only add the rule if this was the 1st tether added. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900684 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700685 return res;
686}
687
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900688int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700689
690 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700691 int res = 0;
692
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900693 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000694 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700695 return -1;
696 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900697 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
698 if (mGlobalAlertTetherCount) {
699 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700700 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900701 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700702 return res;
703}
704
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900705int BandwidthController::removeGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700706 int res = 0;
707 const char *alertName = ALERT_GLOBAL_NAME;
708
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900709 if (!mGlobalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000710 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700711 return -1;
712 }
713
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900714 mGlobalAlertTetherCount--;
JP Abgrallc6c67342011-10-07 16:28:54 -0700715 /*
716 * If there is no globalAlert active we are done.
717 * If there is an active globalAlert but there are more
718 * tethers, we are also done.
719 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900720 if (!mGlobalAlertBytes || mGlobalAlertTetherCount >= 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700721 return 0;
722 }
723
724 /* We only detete the rule if this was the last tether removed. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900725 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700726 return res;
727}
728
JP Abgrall8a932722011-07-13 19:17:35 -0700729int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900730 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000731 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700732 return -1;
733 }
734 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000735 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700736 return -1;
737 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900738 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700739}
740
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900741int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900742 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700743}
744
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900745int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700746 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900747 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700748 return -1;
749 }
750
JP Abgrall8a932722011-07-13 19:17:35 -0700751 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000752 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700753 return -1;
754 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900755 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700756
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900757 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000758 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700759 return -1;
760 }
761
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900762 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700763}
764
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900765int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700766 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900767 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700768 return -1;
769 }
770
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900771 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700772
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900773 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900774 ALOGE("No prior alert set for interface %s", iface.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700775 return -1;
776 }
777
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900778 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700779}
780
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900781int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
782 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700783 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700784
JP Abgrall69261cb2014-06-19 18:35:24 -0700785 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900786 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700787 return -1;
788 }
789
JP Abgrall8a932722011-07-13 19:17:35 -0700790 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000791 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700792 return -1;
793 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900794
795 std::string alertName = costName + "Alert";
796 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700797 if (*alertBytes) {
798 res = updateQuota(alertName, *alertBytes);
799 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900800 std::vector<std::string> commands = {
801 "*filter\n",
802 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
803 "COMMIT\n"
804 };
805 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
806 if (res) {
807 ALOGE("Failed to set costly alert for %s", costName.c_str());
808 }
JP Abgrall8a932722011-07-13 19:17:35 -0700809 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900810 if (res == 0) {
811 *alertBytes = bytes;
812 }
JP Abgrall8a932722011-07-13 19:17:35 -0700813 return res;
814}
815
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900816int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700817 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900818 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700819 return -1;
820 }
821
JP Abgrall8a932722011-07-13 19:17:35 -0700822 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900823 ALOGE("No prior alert set for %s alert", costName.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700824 return -1;
825 }
826
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900827 std::string alertName = costName + "Alert";
828 std::string chainName = "bw_costly_" + costName;
829 std::vector<std::string> commands = {
830 "*filter\n",
831 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
832 "COMMIT\n"
833 };
834 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
835 ALOGE("Failed to remove costly alert %s", costName.c_str());
836 return -1;
837 }
JP Abgrall8a932722011-07-13 19:17:35 -0700838
839 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900840 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700841}
JP Abgralldb7da582011-09-18 12:57:32 -0700842
JP Abgrall0e540ec2013-08-26 15:13:10 -0700843void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900844 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
845 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700846
847 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900848 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
849 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700850 return;
851 }
852 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900853 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700854}
855
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900856void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
857 std::stringstream stream(ruleList);
858 std::string rule;
859 std::vector<std::string> clearCommands = { "*filter" };
860 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700861
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900862 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
863 while (std::getline(stream, rule, '\n')) {
864 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
865 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
866 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
867
868 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700869 continue;
870 }
871
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900872 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700873 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900874 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700875 }
876 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900877
878 if (clearCommands.size() == 1) {
879 // No rules found.
880 return;
881 }
882
883 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900884 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700885}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900886
887inline const char *BandwidthController::opToString(IptOp op) {
888 switch (op) {
889 case IptOpInsert:
890 return "-I";
891 case IptOpDelete:
892 return "-D";
893 }
894}
895
896inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
897 /*
898 * Must be careful what one rejects with, as upper layer protocols will just
899 * keep on hammering the device until the number of retries are done.
900 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
901 */
902 switch (jumpHandling) {
903 case IptJumpNoAdd:
904 return "";
905 case IptJumpReject:
906 return " --jump REJECT";
907 case IptJumpReturn:
908 return " --jump RETURN";
909 }
910}