2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // #define LOG_NDEBUG 0
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.
31 #include <sys/socket.h>
33 #include <sys/types.h>
36 #include <linux/netlink.h>
37 #include <linux/rtnetlink.h>
38 #include <linux/pkt_sched.h>
40 #define LOG_TAG "BandwidthController"
41 #include <cutils/log.h>
42 #include <cutils/properties.h>
43 #include <logwrap/logwrap.h>
45 #include "NetdConstants.h"
46 #include "BandwidthController.h"
47 #include "NatController.h" /* For LOCAL_TETHER_COUNTERS_CHAIN */
48 #include "ResponseCode.h"
51 #define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %lld --name %s"
52 const char BandwidthController::ALERT_GLOBAL_NAME[] = "globalAlert";
53 const char* BandwidthController::LOCAL_INPUT = "bw_INPUT";
54 const char* BandwidthController::LOCAL_FORWARD = "bw_FORWARD";
55 const char* BandwidthController::LOCAL_OUTPUT = "bw_OUTPUT";
56 const char* BandwidthController::LOCAL_RAW_PREROUTING = "bw_raw_PREROUTING";
57 const char* BandwidthController::LOCAL_MANGLE_POSTROUTING = "bw_mangle_POSTROUTING";
58 const int BandwidthController::MAX_CMD_ARGS = 32;
59 const int BandwidthController::MAX_CMD_LEN = 1024;
60 const int BandwidthController::MAX_IFACENAME_LEN = 64;
61 const int BandwidthController::MAX_IPT_OUTPUT_LINE_LEN = 256;
64 * Some comments about the rules:
66 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
67 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
68 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
69 * - bw_happy_box rejects everything by default.
70 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
72 * * global quota vs per interface quota
73 * - global quota for all costly interfaces uses a single costly chain:
75 * iptables -N bw_costly_shared
76 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
77 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
78 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
79 * --jump REJECT --reject-with icmp-net-prohibited
80 * iptables -A bw_costly_shared --jump bw_penalty_box
81 * If the happy box is enabled,
82 * iptables -A bw_penalty_box --jump bw_happy_box
84 * . adding a new iface to this, E.g.:
85 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
86 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
88 * - quota per interface. This is achieve by having "costly" chains per quota.
89 * E.g. adding a new costly interface iface0 with its own quota:
90 * iptables -N bw_costly_iface0
91 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
92 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
93 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
94 * --jump REJECT --reject-with icmp-port-unreachable
95 * iptables -A bw_costly_iface0 --jump bw_penalty_box
97 * * bw_penalty_box handling:
98 * - only one bw_penalty_box for all interfaces
99 * E.g Adding an app, it has to preserve the appened bw_happy_box, so "-I":
100 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
101 * --jump REJECT --reject-with icmp-port-unreachable
103 * * bw_happy_box handling:
104 * - The bw_happy_box goes at the end of the penalty box.
105 * E.g Adding a happy app,
106 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
109 const char *BandwidthController::IPT_FLUSH_COMMANDS[] = {
112 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
113 * to allow coexistance.
120 "-F bw_costly_shared",
122 /* Just a couple that are the most common. */
123 "-F bw_costly_rmnet0",
124 "-F bw_costly_wlan0",
126 "-t raw -F bw_raw_PREROUTING",
127 "-t mangle -F bw_mangle_POSTROUTING",
130 /* The cleanup commands assume flushing has been done. */
131 const char *BandwidthController::IPT_CLEANUP_COMMANDS[] = {
134 "-X bw_costly_shared",
136 /* Just a couple that are the most common. */
137 "-X bw_costly_rmnet0",
138 "-X bw_costly_wlan0",
141 const char *BandwidthController::IPT_SETUP_COMMANDS[] = {
144 "-N bw_costly_shared",
147 const char *BandwidthController::IPT_BASIC_ACCOUNTING_COMMANDS[] = {
148 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
150 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
152 "-A bw_costly_shared --jump bw_penalty_box",
154 "-t raw -A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
155 "-t mangle -A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
158 BandwidthController::BandwidthController(void) {
161 int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
162 IptFailureLog failureHandling) {
165 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
166 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
167 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
171 int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
173 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
174 strncpy(buffer, src, buffSize);
175 return buffer[buffSize - 1];
178 int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
179 IptIpVer iptVer, IptFailureLog failureHandling) {
180 char buffer[MAX_CMD_LEN];
181 const char *argv[MAX_CMD_ARGS];
188 std::string fullCmd = cmd;
190 switch (jumpHandling) {
193 * Must be carefull what one rejects with, as uper layer protocols will just
194 * keep on hammering the device until the number of retries are done.
195 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
197 fullCmd += " --jump REJECT";
200 fullCmd += " --jump RETURN";
206 fullCmd.insert(0, " ");
207 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
209 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
210 ALOGE("iptables command too long");
215 while ((tmp = strsep(&next, " "))) {
217 if (argc >= MAX_CMD_ARGS) {
218 ALOGE("iptables argument overflow");
224 res = android_fork_execvp(argc, (char **)argv, &status, false,
225 failureHandling == IptFailShow);
226 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
227 if (res && failureHandling == IptFailShow) {
228 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
234 int BandwidthController::setupIptablesHooks(void) {
236 /* Some of the initialCommands are allowed to fail */
237 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
238 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
240 runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
241 IPT_CLEANUP_COMMANDS, RunCmdFailureOk);
243 runCommands(sizeof(IPT_SETUP_COMMANDS) / sizeof(char*),
244 IPT_SETUP_COMMANDS, RunCmdFailureBad);
249 int BandwidthController::enableBandwidthControl(bool force) {
251 char value[PROPERTY_VALUE_MAX];
254 property_get("persist.bandwidth.enable", value, "1");
255 if (!strcmp(value, "0"))
259 /* Let's pretend we started from scratch ... */
260 sharedQuotaIfaces.clear();
262 naughtyAppUids.clear();
264 globalAlertBytes = 0;
265 globalAlertTetherCount = 0;
266 sharedQuotaBytes = sharedAlertBytes = 0;
268 res = runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
269 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
271 res |= runCommands(sizeof(IPT_BASIC_ACCOUNTING_COMMANDS) / sizeof(char*),
272 IPT_BASIC_ACCOUNTING_COMMANDS, RunCmdFailureBad);
278 int BandwidthController::disableBandwidthControl(void) {
279 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
280 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
284 int BandwidthController::runCommands(int numCommands, const char *commands[],
285 RunCmdErrHandling cmdErrHandling) {
287 IptFailureLog failureLogging = IptFailShow;
288 if (cmdErrHandling == RunCmdFailureOk) {
289 failureLogging = IptFailHide;
291 ALOGV("runCommands(): %d commands", numCommands);
292 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
293 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
294 if (res && cmdErrHandling != RunCmdFailureOk)
300 std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
310 ALOGE("Append op not supported for %s uids", chain);
322 asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
328 int BandwidthController::enableHappyBox(void) {
329 char cmd[MAX_CMD_LEN];
333 * We tentatively delete before adding, which helps recovering
334 * from bad states (e.g. netd died).
337 /* Should not exist, but ignore result if already there. */
338 snprintf(cmd, sizeof(cmd), "-N bw_happy_box");
339 runIpxtablesCmd(cmd, IptJumpNoAdd);
341 /* Should be empty, but clear in case something was wrong. */
343 snprintf(cmd, sizeof(cmd), "-F bw_happy_box");
344 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
346 snprintf(cmd, sizeof(cmd), "-D bw_penalty_box -j bw_happy_box");
347 runIpxtablesCmd(cmd, IptJumpNoAdd);
348 snprintf(cmd, sizeof(cmd), "-A bw_penalty_box -j bw_happy_box");
349 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
351 /* Reject. Defaulting to prot-unreachable */
352 snprintf(cmd, sizeof(cmd), "-D bw_happy_box -j REJECT");
353 runIpxtablesCmd(cmd, IptJumpNoAdd);
354 snprintf(cmd, sizeof(cmd), "-A bw_happy_box -j REJECT");
355 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
360 int BandwidthController::disableHappyBox(void) {
361 char cmd[MAX_CMD_LEN];
364 snprintf(cmd, sizeof(cmd), "-D bw_penalty_box -j bw_happy_box");
365 runIpxtablesCmd(cmd, IptJumpNoAdd);
367 snprintf(cmd, sizeof(cmd), "-F bw_happy_box");
368 runIpxtablesCmd(cmd, IptJumpNoAdd);
369 snprintf(cmd, sizeof(cmd), "-X bw_happy_box");
370 runIpxtablesCmd(cmd, IptJumpNoAdd);
375 int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
376 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpAdd);
379 int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
380 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpRemove);
383 int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
384 return manipulateNiceApps(numUids, appUids, SpecialAppOpAdd);
387 int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
388 return manipulateNiceApps(numUids, appUids, SpecialAppOpRemove);
391 int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
392 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", naughtyAppUids, IptJumpReject, appOp);
395 int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
396 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", niceAppUids, IptJumpReturn, appOp);
400 int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
402 std::list<int /*appUid*/> &specialAppUids,
403 IptJumpOp jumpHandling, SpecialAppOp appOp) {
405 char cmd[MAX_CMD_LEN];
407 const char *failLogTemplate;
409 int appUids[numUids];
411 std::list<int /*uid*/>::iterator it;
414 case SpecialAppOpAdd:
416 failLogTemplate = "Failed to add app uid %s(%d) to %s.";
418 case SpecialAppOpRemove:
420 failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
423 ALOGE("Unexpected app Op %d", appOp);
427 for (uidNum = 0; uidNum < numUids; uidNum++) {
429 appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
430 if (*end || !*appStrUids[uidNum]) {
431 ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
436 for (uidNum = 0; uidNum < numUids; uidNum++) {
437 int uid = appUids[uidNum];
438 for (it = specialAppUids.begin(); it != specialAppUids.end(); it++) {
442 bool found = (it != specialAppUids.end());
444 if (appOp == SpecialAppOpRemove) {
446 ALOGE("No such appUid %d to remove", uid);
449 specialAppUids.erase(it);
452 ALOGE("appUid %d exists already", uid);
455 specialAppUids.push_front(uid);
458 iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
459 if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
460 ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
461 goto fail_with_uidNum;
467 /* Try to remove the uid that failed in any case*/
468 iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
469 runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
474 std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
479 ALOGV("makeIptablesQuotaCmd(%d, %lld)", op, quota);
497 // The requried IP version specific --jump REJECT ... will be added later.
498 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %lld --name %s", opFlag, costName, quota,
505 int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
506 char cmd[MAX_CMD_LEN];
507 int res = 0, res1, res2;
508 int ruleInsertPos = 1;
509 std::string costString;
510 const char *costCString;
512 /* The "-N costly" is created upfront, no need to handle it here. */
515 costString = "bw_costly_";
517 costCString = costString.c_str();
519 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
520 * Creating a new one is allowed to fail in case it existed.
521 * This helps with netd restarts.
523 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
524 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
525 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
526 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
527 res = (res1 && res2) || (!res1 && !res2);
529 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
530 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
533 costCString = "bw_costly_shared";
536 ALOGE("Unexpected quotatype %d", quotaType);
540 if (globalAlertBytes) {
541 /* The alert rule comes 1st */
545 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
546 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
548 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
549 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
551 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
552 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
554 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
555 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
559 int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
560 char cmd[MAX_CMD_LEN];
562 std::string costString;
563 const char *costCString;
567 costString = "bw_costly_";
569 costCString = costString.c_str();
572 costCString = "bw_costly_shared";
575 ALOGE("Unexpected quotatype %d", quotaType);
579 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
580 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
581 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
582 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
584 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
585 if (quotaType == QuotaUnique) {
586 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
587 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
588 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
589 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
594 int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
595 char cmd[MAX_CMD_LEN];
596 char ifn[MAX_IFACENAME_LEN];
598 std::string quotaCmd;
599 std::string ifaceName;
601 const char *costName = "shared";
602 std::list<std::string>::iterator it;
605 /* Don't talk about -1, deprecate it. */
606 ALOGE("Invalid bytes value. 1..max_int64.");
609 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
610 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
615 if (maxBytes == -1) {
616 return removeInterfaceSharedQuota(ifn);
619 /* Insert ingress quota. */
620 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
621 if (*it == ifaceName)
625 if (it == sharedQuotaIfaces.end()) {
626 res |= prepCostlyIface(ifn, QuotaShared);
627 if (sharedQuotaIfaces.empty()) {
628 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
629 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
631 ALOGE("Failed set quota rule");
634 sharedQuotaBytes = maxBytes;
636 sharedQuotaIfaces.push_front(ifaceName);
640 if (maxBytes != sharedQuotaBytes) {
641 res |= updateQuota(costName, maxBytes);
643 ALOGE("Failed update quota for %s", costName);
646 sharedQuotaBytes = maxBytes;
652 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
653 * rules in the kernel to see which ones need cleaning up.
654 * For now callers needs to choose if they want to "ndc bandwidth enable"
655 * which resets everything.
657 removeInterfaceSharedQuota(ifn);
661 /* It will also cleanup any shared alerts */
662 int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
663 char ifn[MAX_IFACENAME_LEN];
665 std::string ifaceName;
666 std::list<std::string>::iterator it;
667 const char *costName = "shared";
669 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
670 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
675 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
676 if (*it == ifaceName)
679 if (it == sharedQuotaIfaces.end()) {
680 ALOGE("No such iface %s to delete", ifn);
684 res |= cleanupCostlyIface(ifn, QuotaShared);
685 sharedQuotaIfaces.erase(it);
687 if (sharedQuotaIfaces.empty()) {
688 std::string quotaCmd;
689 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
690 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
691 sharedQuotaBytes = 0;
692 if (sharedAlertBytes) {
694 sharedAlertBytes = 0;
700 int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
701 char ifn[MAX_IFACENAME_LEN];
703 std::string ifaceName;
704 const char *costName;
705 std::list<QuotaInfo>::iterator it;
706 std::string quotaCmd;
709 /* Don't talk about -1, deprecate it. */
710 ALOGE("Invalid bytes value. 1..max_int64.");
713 if (maxBytes == -1) {
714 return removeInterfaceQuota(iface);
717 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
718 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
724 /* Insert ingress quota. */
725 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
726 if (it->ifaceName == ifaceName)
730 if (it == quotaIfaces.end()) {
731 /* Preparing the iface adds a penalty/happy box check */
732 res |= prepCostlyIface(ifn, QuotaUnique);
734 * The rejecting quota limit should go after the penalty/happy box checks
735 * or else a naughty app could just eat up the quota.
738 quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
739 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
741 ALOGE("Failed set quota rule");
745 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
748 res |= updateQuota(costName, maxBytes);
750 ALOGE("Failed update quota for %s", iface);
753 it->quota = maxBytes;
759 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
760 * rules in the kernel to see which ones need cleaning up.
761 * For now callers needs to choose if they want to "ndc bandwidth enable"
762 * which resets everything.
764 removeInterfaceSharedQuota(ifn);
768 int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
769 return getInterfaceQuota("shared", bytes);
772 int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
777 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
778 fp = fopen(fname, "r");
781 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
784 scanRes = fscanf(fp, "%lld", bytes);
785 ALOGV("Read quota res=%d bytes=%lld", scanRes, *bytes);
787 return scanRes == 1 ? 0 : -1;
790 int BandwidthController::removeInterfaceQuota(const char *iface) {
792 char ifn[MAX_IFACENAME_LEN];
794 std::string ifaceName;
795 const char *costName;
796 std::list<QuotaInfo>::iterator it;
798 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
799 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
805 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
806 if (it->ifaceName == ifaceName)
810 if (it == quotaIfaces.end()) {
811 ALOGE("No such iface %s to delete", ifn);
815 /* This also removes the quota command of CostlyIface chain. */
816 res |= cleanupCostlyIface(ifn, QuotaUnique);
818 quotaIfaces.erase(it);
823 int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
827 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
828 fp = fopen(fname, "w");
831 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
834 fprintf(fp, "%lld\n", bytes);
839 int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
860 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
862 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
864 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
866 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
871 int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
892 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
894 res = runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
899 int BandwidthController::setGlobalAlert(int64_t bytes) {
900 const char *alertName = ALERT_GLOBAL_NAME;
904 ALOGE("Invalid bytes value. 1..max_int64.");
907 if (globalAlertBytes) {
908 res = updateQuota(alertName, bytes);
910 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
911 if (globalAlertTetherCount) {
912 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
913 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
916 globalAlertBytes = bytes;
920 int BandwidthController::setGlobalAlertInForwardChain(void) {
921 const char *alertName = ALERT_GLOBAL_NAME;
924 globalAlertTetherCount++;
925 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
928 * If there is no globalAlert active we are done.
929 * If there is an active globalAlert but this is not the 1st
930 * tether, we are also done.
932 if (!globalAlertBytes || globalAlertTetherCount != 1) {
936 /* We only add the rule if this was the 1st tether added. */
937 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
941 int BandwidthController::removeGlobalAlert(void) {
943 const char *alertName = ALERT_GLOBAL_NAME;
946 if (!globalAlertBytes) {
947 ALOGE("No prior alert set");
950 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
951 if (globalAlertTetherCount) {
952 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
954 globalAlertBytes = 0;
958 int BandwidthController::removeGlobalAlertInForwardChain(void) {
960 const char *alertName = ALERT_GLOBAL_NAME;
962 if (!globalAlertTetherCount) {
963 ALOGE("No prior alert set");
967 globalAlertTetherCount--;
969 * If there is no globalAlert active we are done.
970 * If there is an active globalAlert but there are more
971 * tethers, we are also done.
973 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
977 /* We only detete the rule if this was the last tether removed. */
978 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
982 int BandwidthController::setSharedAlert(int64_t bytes) {
983 if (!sharedQuotaBytes) {
984 ALOGE("Need to have a prior shared quota set to set an alert");
988 ALOGE("Invalid bytes value. 1..max_int64.");
991 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
994 int BandwidthController::removeSharedAlert(void) {
995 return removeCostlyAlert("shared", &sharedAlertBytes);
998 int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
999 std::list<QuotaInfo>::iterator it;
1002 ALOGE("Invalid bytes value. 1..max_int64.");
1005 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1006 if (it->ifaceName == iface)
1010 if (it == quotaIfaces.end()) {
1011 ALOGE("Need to have a prior interface quota set to set an alert");
1015 return setCostlyAlert(iface, bytes, &it->alert);
1018 int BandwidthController::removeInterfaceAlert(const char *iface) {
1019 std::list<QuotaInfo>::iterator it;
1021 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1022 if (it->ifaceName == iface)
1026 if (it == quotaIfaces.end()) {
1027 ALOGE("No prior alert set for interface %s", iface);
1031 return removeCostlyAlert(iface, &it->alert);
1034 int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1035 char *alertQuotaCmd;
1041 ALOGE("Invalid bytes value. 1..max_int64.");
1044 asprintf(&alertName, "%sAlert", costName);
1046 res = updateQuota(alertName, *alertBytes);
1048 asprintf(&chainName, "bw_costly_%s", costName);
1049 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
1050 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
1051 free(alertQuotaCmd);
1054 *alertBytes = bytes;
1059 int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1060 char *alertQuotaCmd;
1065 asprintf(&alertName, "%sAlert", costName);
1067 ALOGE("No prior alert set for %s alert", costName);
1071 asprintf(&chainName, "bw_costly_%s", costName);
1072 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
1073 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
1074 free(alertQuotaCmd);
1083 * Parse the ptks and bytes out of:
1084 * Chain natctrl_tether_counters (4 references)
1085 * pkts bytes target prot opt in out source destination
1086 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0 counter wlan0_rmnet0: 0 bytes
1087 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0 counter rmnet0_wlan0: 0 bytes
1088 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0 counter bt-pan_rmnet0: 0 bytes
1089 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0 counter rmnet0_bt-pan: 0 bytes
1091 int BandwidthController::parseForwardChainStats(SocketClient *cli, const TetherStats filter,
1092 FILE *fp, std::string &extraProcessingInfo) {
1094 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
1095 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1096 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1097 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1101 int64_t packets, bytes;
1104 bool filterPair = filter.intIface[0] && filter.extIface[0];
1106 char *filterMsg = filter.getStatsLine();
1107 ALOGV("filter: %s", filterMsg);
1112 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
1113 /* Clean up, so a failed parse can still print info */
1114 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
1115 res = sscanf(buffPtr, "%lld %lld RETURN all -- %s %s 0.%s",
1116 &packets, &bytes, iface0, iface1, rest);
1117 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%lld bytes=%lld rest=<%s> orig line=<%s>", res,
1118 iface0, iface1, packets, bytes, rest, buffPtr);
1119 extraProcessingInfo += buffPtr;
1125 * The following assumes that the 1st rule has in:extIface out:intIface,
1126 * which is what NatController sets up.
1127 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1129 if (filter.intIface[0] && filter.extIface[0]) {
1130 if (filter.intIface == iface0 && filter.extIface == iface1) {
1131 ALOGV("2Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1132 stats.rxPackets = packets;
1133 stats.rxBytes = bytes;
1134 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
1135 ALOGV("2Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1136 stats.txPackets = packets;
1137 stats.txBytes = bytes;
1139 } else if (filter.intIface[0] || filter.extIface[0]) {
1140 if (filter.intIface == iface0 || filter.extIface == iface1) {
1141 ALOGV("1Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1142 stats.intIface = iface0;
1143 stats.extIface = iface1;
1144 stats.rxPackets = packets;
1145 stats.rxBytes = bytes;
1146 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
1147 ALOGV("1Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1148 stats.intIface = iface1;
1149 stats.extIface = iface0;
1150 stats.txPackets = packets;
1151 stats.txBytes = bytes;
1153 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1154 if (!stats.intIface[0]) {
1155 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1156 stats.intIface = iface0;
1157 stats.extIface = iface1;
1158 stats.rxPackets = packets;
1159 stats.rxBytes = bytes;
1160 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
1161 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1162 stats.txPackets = packets;
1163 stats.txBytes = bytes;
1166 if (stats.rxBytes != -1 && stats.txBytes != -1) {
1167 ALOGV("rx_bytes=%lld tx_bytes=%lld filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
1168 /* Send out stats, and prep for the next if needed. */
1169 char *msg = stats.getStatsLine();
1171 cli->sendMsg(ResponseCode::TetheringStatsResult, msg, false);
1174 cli->sendMsg(ResponseCode::TetheringStatsListResult, msg, false);
1181 /* We found some stats, and the last one isn't a partial stats. */
1182 if (statsFound && (stats.rxBytes == -1 || stats.txBytes == -1)) {
1183 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1189 char *BandwidthController::TetherStats::getStatsLine(void) const {
1191 asprintf(&msg, "%s %s %lld %lld %lld %lld", intIface.c_str(), extIface.c_str(),
1192 rxBytes, rxPackets, txBytes, txPackets);
1196 int BandwidthController::getTetherStats(SocketClient *cli, TetherStats &stats, std::string &extraProcessingInfo) {
1198 std::string fullCmd;
1203 * Why not use some kind of lib to talk to iptables?
1204 * Because the only libs are libiptc and libip6tc in iptables, and they are
1205 * not easy to use. They require the known iptables match modules to be
1206 * preloaded/linked, and require apparently a lot of wrapper code to get
1209 fullCmd = IPTABLES_PATH;
1210 fullCmd += " -nvx -L ";
1211 fullCmd += NatController::LOCAL_TETHER_COUNTERS_CHAIN;
1212 iptOutput = popen(fullCmd.c_str(), "r");
1214 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
1215 extraProcessingInfo += "Failed to run iptables.";
1218 res = parseForwardChainStats(cli, stats, iptOutput, extraProcessingInfo);
1221 /* Currently NatController doesn't do ipv6 tethering, so we are done. */