1 /*
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
17 // #define LOG_NDEBUG 0
18
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
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <string>
32 #include <vector>
33
34 #define __STDC_FORMAT_MACROS 1
35 #include <inttypes.h>
36
37 #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
46 #include "android-base/stringprintf.h"
47 #include "android-base/strings.h"
48 #define LOG_TAG "BandwidthController"
49 #include <cutils/properties.h>
50 #include <log/log.h>
51
52 #include <netdutils/Syscalls.h>
53 #include "BandwidthController.h"
54 #include "Controllers.h"
55 #include "FirewallController.h" /* For makeCriticalCommands */
56 #include "Fwmark.h"
57 #include "NetdConstants.h"
58 #include "android/net/INetd.h"
59
60 /* Alphabetical */
61 #define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
62 const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
63 const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
64 const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
65 const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
66 const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
67 const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
68
69 auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
70
71 using android::base::Join;
72 using android::base::StartsWith;
73 using android::base::StringAppendF;
74 using android::base::StringPrintf;
75 using android::net::FirewallController;
76 using android::net::INetd::CLAT_MARK;
77 using android::netdutils::StatusOr;
78 using android::netdutils::UniqueFile;
79
80 namespace {
81
82 const char ALERT_GLOBAL_NAME[] = "globalAlert";
83 const std::string NEW_CHAIN_COMMAND = "-N ";
84
85 /**
86 * Some comments about the rules:
87 * * Ordering
88 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
89 * E.g. "-I bw_INPUT -i rmnet0 -j costly"
90 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
91 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
92 *
93 * * global quota vs per interface quota
94 * - global quota for all costly interfaces uses a single costly chain:
95 * . initial rules
96 * iptables -N bw_costly_shared
97 * iptables -I bw_INPUT -i iface0 -j bw_costly_shared
98 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_shared
99 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
100 * -j REJECT --reject-with icmp-net-prohibited
101 * iptables -A bw_costly_shared -j bw_penalty_box
102 * iptables -A bw_penalty_box -j bw_happy_box
103 * iptables -A bw_happy_box -j bw_data_saver
104 *
105 * . adding a new iface to this, E.g.:
106 * iptables -I bw_INPUT -i iface1 -j bw_costly_shared
107 * iptables -I bw_OUTPUT -o iface1 -j bw_costly_shared
108 *
109 * - quota per interface. This is achieve by having "costly" chains per quota.
110 * E.g. adding a new costly interface iface0 with its own quota:
111 * iptables -N bw_costly_iface0
112 * iptables -I bw_INPUT -i iface0 -j bw_costly_iface0
113 * iptables -I bw_OUTPUT -o iface0 -j bw_costly_iface0
114 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
115 * -j REJECT --reject-with icmp-port-unreachable
116 * iptables -A bw_costly_iface0 -j bw_penalty_box
117 *
118 * * Penalty box, happy box and data saver.
119 * - bw_penalty box is a denylist of apps that are rejected.
120 * - bw_happy_box is an allowlist of apps. It always includes all system apps
121 * - bw_data_saver implements data usage restrictions.
122 * - Via the UI the user can add and remove apps from the allowlist and
123 * denylist, and turn on/off data saver.
124 * - The denylist takes precedence over the allowlist and the allowlist
125 * takes precedence over data saver.
126 *
127 * * bw_penalty_box handling:
128 * - only one bw_penalty_box for all interfaces
129 * E.g Adding an app:
130 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
131 * -j REJECT --reject-with icmp-port-unreachable
132 *
133 * * bw_happy_box handling:
134 * - The bw_happy_box comes after the penalty box.
135 * E.g Adding a happy app,
136 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
137 * -j RETURN
138 *
139 * * bw_data_saver handling:
140 * - The bw_data_saver comes after the happy box.
141 * Enable data saver:
142 * iptables -R 1 bw_data_saver -j REJECT --reject-with icmp-port-unreachable
143 * Disable data saver:
144 * iptables -R 1 bw_data_saver -j RETURN
145 */
146
147 const std::string COMMIT_AND_CLOSE = "COMMIT\n";
148
149 static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
150 /*
151 * Cleanup rules.
152 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
153 * to allow coexistance.
154 */
155 "*filter",
156 ":bw_INPUT -",
157 ":bw_OUTPUT -",
158 ":bw_FORWARD -",
159 ":bw_happy_box -",
160 ":bw_penalty_box -",
161 ":bw_data_saver -",
162 ":bw_costly_shared -",
163 ":bw_global_alert -",
164 "COMMIT",
165 "*raw",
166 ":bw_raw_PREROUTING -",
167 "COMMIT",
168 "*mangle",
169 ":bw_mangle_POSTROUTING -",
170 COMMIT_AND_CLOSE};
171
172 static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
173
174 /**
175 * Basic commands for creation of hooks into data accounting and data boxes.
176 *
177 * Included in these commands are rules to prevent the double-counting of IPsec
178 * packets. The general overview is as follows:
179 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
180 * completely accurate, and count only the outer packet. As such, the inner
181 * packet must be ignored, which is done through the use of two rules: use
182 * of the policy module (for tunnel mode), and VTI interface checks (for
183 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
184 * ipsec*
185 * > Outbound UID billing can always be done with the outer packets, due to the
186 * ability to always find the correct UID (based on the skb->sk). As such,
187 * the inner packets should be ignored based on the policy module, or the
188 * output interface if a VTI (ipsec+)
189 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
190 * opened the encap socket, and as such, should be billed as early as
191 * possible (for transport mode; tunnel mode usage should be billed to
192 * sending/receiving application). Due to the inner packet being
193 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
194 * has to be applied to prevent counting a second time.
195 * > Inbound ESP has no socket, and as such must be accounted later. ESP
196 * protocol packets are skipped via a blanket rule.
197 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
198 * ignore rule in the input chain would actually break the INPUT chain;
199 * Those rules are designed to ignore inner packets, and in the tunnel
200 * mode UDP, or any ESP case, we would not have billed the outer packet.
201 *
202 * See go/ipsec-data-accounting for more information.
203 */
204
getBasicAccountingCommands()205 std::vector<std::string> getBasicAccountingCommands() {
206 // clang-format off
207 std::vector<std::string> ipt_basic_accounting_commands = {
208 "*filter",
209
210 "-A bw_INPUT -j bw_global_alert",
211 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
212 "-A bw_INPUT -p esp -j RETURN",
213 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN", uidBillingMask,
214 uidBillingMask),
215 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
216 "-A bw_OUTPUT -j bw_global_alert",
217 "-A bw_costly_shared -j bw_penalty_box",
218 ("-I bw_penalty_box -m bpf --object-pinned " XT_BPF_DENYLIST_PROG_PATH " -j REJECT"),
219 "-A bw_penalty_box -j bw_happy_box",
220 "-A bw_happy_box -j bw_data_saver",
221 "-A bw_data_saver -j RETURN",
222 ("-I bw_happy_box -m bpf --object-pinned " XT_BPF_ALLOWLIST_PROG_PATH " -j RETURN"),
223 "COMMIT",
224
225 "*raw",
226 // Drop duplicate ingress clat packets
227 StringPrintf("-A bw_raw_PREROUTING -m mark --mark 0x%x -j DROP", CLAT_MARK),
228 // Prevents IPSec double counting (Tunnel mode and Transport mode,
229 // respectively)
230 ("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
231 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
232 // This is ingress interface accounting. There is no need to do anything specific
233 // for 464xlat here, because we only ever account 464xlat traffic on the clat
234 // interface and later correct for overhead (+20 bytes/packet).
235 //
236 // Note: eBPF offloaded packets never hit base interface's ip6tables, and non
237 // offloaded packets are dropped up above due to being marked with CLAT_MARK
238 //
239 // Hence we will never double count and additional corrections are not needed.
240 // We can simply take the sum of base and stacked (+20B/pkt) interface counts.
241 ("-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH),
242 "COMMIT",
243
244 "*mangle",
245 // Prevents IPSec double counting (Tunnel mode and Transport mode,
246 // respectively)
247 ("-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN"),
248 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
249 // Clear the uid billing done (egress) mark before sending this packet
250 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
251 // This is egress interface accounting: we account 464xlat traffic only on
252 // the clat interface (as offloaded packets never hit base interface's ip6tables)
253 // and later sum base and stacked with overhead (+20B/pkt) in higher layers
254 ("-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH),
255 COMMIT_AND_CLOSE};
256 // clang-format on
257 return ipt_basic_accounting_commands;
258 }
259
260 } // namespace
261
BandwidthController()262 BandwidthController::BandwidthController() {
263 }
264
flushCleanTables(bool doClean)265 void BandwidthController::flushCleanTables(bool doClean) {
266 /* Flush and remove the bw_costly_<iface> tables */
267 flushExistingCostlyTables(doClean);
268
269 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
270 iptablesRestoreFunction(V4V6, commands, nullptr);
271 }
272
setupIptablesHooks()273 int BandwidthController::setupIptablesHooks() {
274 /* flush+clean is allowed to fail */
275 flushCleanTables(true);
276 return 0;
277 }
278
enableBandwidthControl()279 int BandwidthController::enableBandwidthControl() {
280 /* Let's pretend we started from scratch ... */
281 mSharedQuotaIfaces.clear();
282 mQuotaIfaces.clear();
283 mGlobalAlertBytes = 0;
284 mSharedQuotaBytes = mSharedAlertBytes = 0;
285
286 flushCleanTables(false);
287
288 std::string commands = Join(getBasicAccountingCommands(), '\n');
289 return iptablesRestoreFunction(V4V6, commands, nullptr);
290 }
291
disableBandwidthControl()292 int BandwidthController::disableBandwidthControl() {
293
294 flushCleanTables(false);
295 return 0;
296 }
297
makeDataSaverCommand(IptablesTarget target,bool enable)298 std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
299 std::string cmd;
300 const char *chainName = "bw_data_saver";
301 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
302 std::string criticalCommands = enable ?
303 FirewallController::makeCriticalCommands(target, chainName) : "";
304 StringAppendF(&cmd,
305 "*filter\n"
306 ":%s -\n"
307 "%s"
308 "-A %s%s\n"
309 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
310 return cmd;
311 }
312
enableDataSaver(bool enable)313 int BandwidthController::enableDataSaver(bool enable) {
314 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
315 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
316 return ret;
317 }
318
setInterfaceSharedQuota(const std::string & iface,int64_t maxBytes)319 int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
320 int res = 0;
321 std::string quotaCmd;
322 constexpr char cost[] = "shared";
323 constexpr char chain[] = "bw_costly_shared";
324
325 if (!maxBytes) {
326 /* Don't talk about -1, deprecate it. */
327 ALOGE("Invalid bytes value. 1..max_int64.");
328 return -1;
329 }
330 if (!isIfaceName(iface))
331 return -1;
332
333 if (maxBytes == -1) {
334 return removeInterfaceSharedQuota(iface);
335 }
336
337 auto it = mSharedQuotaIfaces.find(iface);
338
339 if (it == mSharedQuotaIfaces.end()) {
340 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
341 std::vector<std::string> cmds = {
342 "*filter",
343 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain),
344 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(), chain),
345 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain),
346 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain),
347 };
348 if (mSharedQuotaIfaces.empty()) {
349 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT",
350 chain, maxBytes, cost));
351 }
352 cmds.push_back("COMMIT\n");
353
354 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
355 if (res) {
356 ALOGE("Failed set quota rule");
357 removeInterfaceSharedQuota(iface);
358 return -1;
359 }
360 mSharedQuotaBytes = maxBytes;
361 mSharedQuotaIfaces.insert(iface);
362 }
363
364 if (maxBytes != mSharedQuotaBytes) {
365 res |= updateQuota(cost, maxBytes);
366 if (res) {
367 ALOGE("Failed update quota for %s", cost);
368 removeInterfaceSharedQuota(iface);
369 return -1;
370 }
371 mSharedQuotaBytes = maxBytes;
372 }
373 return 0;
374 }
375
376 /* It will also cleanup any shared alerts */
removeInterfaceSharedQuota(const std::string & iface)377 int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
378 constexpr char cost[] = "shared";
379 constexpr char chain[] = "bw_costly_shared";
380
381 if (!isIfaceName(iface))
382 return -1;
383
384 auto it = mSharedQuotaIfaces.find(iface);
385
386 if (it == mSharedQuotaIfaces.end()) {
387 ALOGE("No such iface %s to delete", iface.c_str());
388 return -1;
389 }
390
391 std::vector<std::string> cmds = {
392 "*filter",
393 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain),
394 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain),
395 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain),
396 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain),
397 };
398 if (mSharedQuotaIfaces.size() == 1) {
399 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64 " --name %s -j REJECT",
400 chain, mSharedQuotaBytes, cost));
401 }
402 cmds.push_back("COMMIT\n");
403
404 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
405 ALOGE("Failed to remove shared quota on %s", iface.c_str());
406 return -1;
407 }
408
409 int res = 0;
410 mSharedQuotaIfaces.erase(it);
411 if (mSharedQuotaIfaces.empty()) {
412 mSharedQuotaBytes = 0;
413 if (mSharedAlertBytes) {
414 res = removeSharedAlert();
415 if (res == 0) {
416 mSharedAlertBytes = 0;
417 }
418 }
419 }
420
421 return res;
422
423 }
424
setInterfaceQuota(const std::string & iface,int64_t maxBytes)425 int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
426 const std::string& cost = iface;
427
428 if (!isIfaceName(iface)) return -EINVAL;
429
430 if (!maxBytes) {
431 ALOGE("Invalid bytes value. 1..max_int64.");
432 return -ERANGE;
433 }
434 if (maxBytes == -1) {
435 return removeInterfaceQuota(iface);
436 }
437
438 /* Insert ingress quota. */
439 auto it = mQuotaIfaces.find(iface);
440
441 if (it != mQuotaIfaces.end()) {
442 if (int res = updateQuota(cost, maxBytes)) {
443 ALOGE("Failed update quota for %s", iface.c_str());
444 removeInterfaceQuota(iface);
445 return res;
446 }
447 it->second.quota = maxBytes;
448 return 0;
449 }
450
451 const std::string chain = "bw_costly_" + iface;
452 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
453 std::vector<std::string> cmds = {
454 "*filter",
455 StringPrintf(":%s -", chain.c_str()),
456 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
457 StringPrintf("-I bw_INPUT %d -i %s -j %s", ruleInsertPos, iface.c_str(), chain.c_str()),
458 StringPrintf("-I bw_OUTPUT %d -o %s -j %s", ruleInsertPos, iface.c_str(),
459 chain.c_str()),
460 StringPrintf("-A bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
461 StringPrintf("-A bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
462 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s -j REJECT", chain.c_str(),
463 maxBytes, cost.c_str()),
464 "COMMIT\n",
465 };
466 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
467 ALOGE("Failed set quota rule");
468 removeInterfaceQuota(iface);
469 return -EREMOTEIO;
470 }
471
472 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
473 return 0;
474 }
475
getInterfaceSharedQuota(int64_t * bytes)476 int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
477 return getInterfaceQuota("shared", bytes);
478 }
479
getInterfaceQuota(const std::string & iface,int64_t * bytes)480 int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
481 const auto& sys = android::netdutils::sSyscalls.get();
482 const std::string fname = "/proc/net/xt_quota/" + iface;
483
484 if (!isIfaceName(iface)) return -1;
485
486 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
487 if (!isOk(file)) {
488 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
489 return -1;
490 }
491 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
492 if (!isOk(rv)) {
493 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
494 return -1;
495 }
496 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
497 return rv.value() == 1 ? 0 : -1;
498 }
499
removeInterfaceQuota(const std::string & iface)500 int BandwidthController::removeInterfaceQuota(const std::string& iface) {
501 if (!isIfaceName(iface)) return -EINVAL;
502
503 auto it = mQuotaIfaces.find(iface);
504
505 if (it == mQuotaIfaces.end()) {
506 ALOGE("No such iface %s to delete", iface.c_str());
507 return -ENODEV;
508 }
509
510 const std::string chain = "bw_costly_" + iface;
511 std::vector<std::string> cmds = {
512 "*filter",
513 StringPrintf("-D bw_INPUT -i %s -j %s", iface.c_str(), chain.c_str()),
514 StringPrintf("-D bw_OUTPUT -o %s -j %s", iface.c_str(), chain.c_str()),
515 StringPrintf("-D bw_FORWARD -i %s -j %s", iface.c_str(), chain.c_str()),
516 StringPrintf("-D bw_FORWARD -o %s -j %s", iface.c_str(), chain.c_str()),
517 StringPrintf("-F %s", chain.c_str()),
518 StringPrintf("-X %s", chain.c_str()),
519 "COMMIT\n",
520 };
521
522 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
523
524 if (res == 0) {
525 mQuotaIfaces.erase(it);
526 }
527
528 return res ? -EREMOTEIO : 0;
529 }
530
updateQuota(const std::string & quotaName,int64_t bytes)531 int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
532 const auto& sys = android::netdutils::sSyscalls.get();
533 const std::string fname = "/proc/net/xt_quota/" + quotaName;
534
535 if (!isIfaceName(quotaName)) {
536 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
537 return -EINVAL;
538 }
539
540 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
541 if (!isOk(file)) {
542 int res = errno;
543 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
544 return -res;
545 }
546 // TODO: should we propagate this error?
547 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes).ignoreError();
548 return 0;
549 }
550
runIptablesAlertCmd(IptOp op,const std::string & alertName,int64_t bytes)551 int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
552 int64_t bytes) {
553 const char *opFlag = opToString(op);
554 std::string alertQuotaCmd = "*filter\n";
555
556 // TODO: consider using an alternate template for the delete that does not include the --quota
557 // value. This code works because the --quota value is ignored by deletes
558
559 /*
560 * Add alert rule in bw_global_alert chain, 3 chains might reference bw_global_alert.
561 * bw_INPUT, bw_OUTPUT (added by BandwidthController in enableBandwidthControl)
562 * bw_FORWARD (added by TetherController in setTetherGlobalAlertRule if nat enable/disable)
563 */
564 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, LOCAL_GLOBAL_ALERT, bytes,
565 alertName.c_str());
566 StringAppendF(&alertQuotaCmd, "COMMIT\n");
567
568 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
569 }
570
setGlobalAlert(int64_t bytes)571 int BandwidthController::setGlobalAlert(int64_t bytes) {
572 const char *alertName = ALERT_GLOBAL_NAME;
573
574 if (!bytes) {
575 ALOGE("Invalid bytes value. 1..max_int64.");
576 return -ERANGE;
577 }
578
579 int res = 0;
580 if (mGlobalAlertBytes) {
581 res = updateQuota(alertName, bytes);
582 } else {
583 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
584 if (res) {
585 res = -EREMOTEIO;
586 }
587 }
588 mGlobalAlertBytes = bytes;
589 return res;
590 }
591
removeGlobalAlert()592 int BandwidthController::removeGlobalAlert() {
593
594 const char *alertName = ALERT_GLOBAL_NAME;
595
596 if (!mGlobalAlertBytes) {
597 ALOGE("No prior alert set");
598 return -1;
599 }
600
601 int res = 0;
602 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
603 mGlobalAlertBytes = 0;
604 return res;
605 }
606
setSharedAlert(int64_t bytes)607 int BandwidthController::setSharedAlert(int64_t bytes) {
608 if (!mSharedQuotaBytes) {
609 ALOGE("Need to have a prior shared quota set to set an alert");
610 return -1;
611 }
612 if (!bytes) {
613 ALOGE("Invalid bytes value. 1..max_int64.");
614 return -1;
615 }
616 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
617 }
618
removeSharedAlert()619 int BandwidthController::removeSharedAlert() {
620 return removeCostlyAlert("shared", &mSharedAlertBytes);
621 }
622
setInterfaceAlert(const std::string & iface,int64_t bytes)623 int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
624 if (!isIfaceName(iface)) {
625 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
626 return -EINVAL;
627 }
628
629 if (!bytes) {
630 ALOGE("Invalid bytes value. 1..max_int64.");
631 return -ERANGE;
632 }
633 auto it = mQuotaIfaces.find(iface);
634
635 if (it == mQuotaIfaces.end()) {
636 ALOGE("Need to have a prior interface quota set to set an alert");
637 return -ENOENT;
638 }
639
640 return setCostlyAlert(iface, bytes, &it->second.alert);
641 }
642
removeInterfaceAlert(const std::string & iface)643 int BandwidthController::removeInterfaceAlert(const std::string& iface) {
644 if (!isIfaceName(iface)) {
645 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
646 return -EINVAL;
647 }
648
649 auto it = mQuotaIfaces.find(iface);
650
651 if (it == mQuotaIfaces.end()) {
652 ALOGE("No prior alert set for interface %s", iface.c_str());
653 return -ENOENT;
654 }
655
656 return removeCostlyAlert(iface, &it->second.alert);
657 }
658
setCostlyAlert(const std::string & costName,int64_t bytes,int64_t * alertBytes)659 int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
660 int64_t* alertBytes) {
661 int res = 0;
662
663 if (!isIfaceName(costName)) {
664 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
665 return -EINVAL;
666 }
667
668 if (!bytes) {
669 ALOGE("Invalid bytes value. 1..max_int64.");
670 return -ERANGE;
671 }
672
673 std::string alertName = costName + "Alert";
674 std::string chainName = "bw_costly_" + costName;
675 if (*alertBytes) {
676 res = updateQuota(alertName, *alertBytes);
677 } else {
678 std::vector<std::string> commands = {
679 "*filter\n",
680 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
681 "COMMIT\n"
682 };
683 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
684 if (res) {
685 ALOGE("Failed to set costly alert for %s", costName.c_str());
686 res = -EREMOTEIO;
687 }
688 }
689 if (res == 0) {
690 *alertBytes = bytes;
691 }
692 return res;
693 }
694
removeCostlyAlert(const std::string & costName,int64_t * alertBytes)695 int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
696 if (!isIfaceName(costName)) {
697 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
698 return -EINVAL;
699 }
700
701 if (!*alertBytes) {
702 ALOGE("No prior alert set for %s alert", costName.c_str());
703 return -ENOENT;
704 }
705
706 std::string alertName = costName + "Alert";
707 std::string chainName = "bw_costly_" + costName;
708 std::vector<std::string> commands = {
709 "*filter\n",
710 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
711 "COMMIT\n"
712 };
713 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
714 ALOGE("Failed to remove costly alert %s", costName.c_str());
715 return -EREMOTEIO;
716 }
717
718 *alertBytes = 0;
719 return 0;
720 }
721
flushExistingCostlyTables(bool doClean)722 void BandwidthController::flushExistingCostlyTables(bool doClean) {
723 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
724 std::string ruleList;
725
726 /* Only lookup ip4 table names as ip6 will have the same tables ... */
727 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
728 ALOGE("Failed to list existing costly tables ret=%d", ret);
729 return;
730 }
731 /* ... then flush/clean both ip4 and ip6 iptables. */
732 parseAndFlushCostlyTables(ruleList, doClean);
733 }
734
parseAndFlushCostlyTables(const std::string & ruleList,bool doRemove)735 void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
736 std::stringstream stream(ruleList);
737 std::string rule;
738 std::vector<std::string> clearCommands = { "*filter" };
739 std::string chainName;
740
741 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
742 while (std::getline(stream, rule, '\n')) {
743 if (!StartsWith(rule, NEW_CHAIN_COMMAND)) continue;
744 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
745 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
746
747 if (!StartsWith(chainName, "bw_costly_") || chainName == std::string("bw_costly_shared")) {
748 continue;
749 }
750
751 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
752 if (doRemove) {
753 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
754 }
755 }
756
757 if (clearCommands.size() == 1) {
758 // No rules found.
759 return;
760 }
761
762 clearCommands.push_back("COMMIT\n");
763 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
764 }
765
opToString(IptOp op)766 inline const char *BandwidthController::opToString(IptOp op) {
767 switch (op) {
768 case IptOpInsert:
769 return "-I";
770 case IptOpDelete:
771 return "-D";
772 }
773 }
774
jumpToString(IptJumpOp jumpHandling)775 inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
776 /*
777 * Must be careful what one rejects with, as upper layer protocols will just
778 * keep on hammering the device until the number of retries are done.
779 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
780 */
781 switch (jumpHandling) {
782 case IptJumpReject:
783 return " -j REJECT";
784 case IptJumpReturn:
785 return " -j RETURN";
786 }
787 }
788