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>
44 extern "C" int logwrap(int argc, const char **argv);
45 extern "C" int system_nosh(const char *command);
47 #include "NetdConstants.h"
48 #include "BandwidthController.h"
51 #define ALERT_IPT_TEMPLATE "%s %s %s -m quota2 ! --quota %lld --name %s"
52 const int BandwidthController::ALERT_RULE_POS_IN_COSTLY_CHAIN = 4;
53 const char BandwidthController::ALERT_GLOBAL_NAME[] = "globalAlert";
54 const int BandwidthController::MAX_CMD_ARGS = 32;
55 const int BandwidthController::MAX_CMD_LEN = 1024;
56 const int BandwidthController::MAX_IFACENAME_LEN = 64;
57 const int BandwidthController::MAX_IPT_OUTPUT_LINE_LEN = 256;
59 bool BandwidthController::useLogwrapCall = false;
62 * Some comments about the rules:
64 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
65 * E.g. "-I INPUT -i rmnet0 --jump costly"
66 * - quota'd rules in the costly chain should be before penalty_box lookups.
68 * * global quota vs per interface quota
69 * - global quota for all costly interfaces uses a single costly chain:
71 * iptables -N costly_shared
72 * iptables -I INPUT -i iface0 --jump costly_shared
73 * iptables -I OUTPUT -o iface0 --jump costly_shared
74 * iptables -I costly_shared -m quota \! --quota 500000 \
75 * --jump REJECT --reject-with icmp-net-prohibited
76 * iptables -A costly_shared --jump penalty_box
77 * iptables -A costly_shared -m owner --socket-exists
79 * . adding a new iface to this, E.g.:
80 * iptables -I INPUT -i iface1 --jump costly_shared
81 * iptables -I OUTPUT -o iface1 --jump costly_shared
83 * - quota per interface. This is achieve by having "costly" chains per quota.
84 * E.g. adding a new costly interface iface0 with its own quota:
85 * iptables -N costly_iface0
86 * iptables -I INPUT -i iface0 --jump costly_iface0
87 * iptables -I OUTPUT -o iface0 --jump costly_iface0
88 * iptables -A costly_iface0 -m quota \! --quota 500000 \
89 * --jump REJECT --reject-with icmp-net-prohibited
90 * iptables -A costly_iface0 --jump penalty_box
91 * iptables -A costly_iface0 -m owner --socket-exists
93 * * penalty_box handling:
94 * - only one penalty_box for all interfaces
96 * iptables -A penalty_box -m owner --uid-owner app_3 \
97 * --jump REJECT --reject-with icmp-net-prohibited
99 const char *BandwidthController::IPT_FLUSH_COMMANDS[] = {
102 * Should normally include costly_<iface>, but we rely on the way they are setup
103 * to allow coexistance.
112 /* The cleanup commands assume flushing has been done. */
113 const char *BandwidthController::IPT_CLEANUP_COMMANDS[] = {
114 /* Delete hooks to custom chains. */
115 "-D INPUT -j bw_INPUT",
116 "-D OUTPUT -j bw_OUTPUT",
117 "-D FORWARD -j bw_FORWARD",
125 const char *BandwidthController::IPT_SETUP_COMMANDS[] = {
126 /* Created needed chains. */
128 "-A INPUT -j bw_INPUT",
131 "-A OUTPUT -j bw_OUTPUT",
134 "-I FORWARD -j bw_FORWARD",
140 const char *BandwidthController::IPT_BASIC_ACCOUNTING_COMMANDS[] = {
141 "-A bw_INPUT -i lo --jump RETURN",
142 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
144 "-A bw_OUTPUT -o lo --jump RETURN",
145 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
147 "-A costly_shared --jump penalty_box",
148 "-A costly_shared -m owner --socket-exists", /* This is a tracking rule. */
151 BandwidthController::BandwidthController(void) {
152 char value[PROPERTY_VALUE_MAX];
154 property_get("persist.bandwidth.uselogwrap", value, "0");
155 useLogwrapCall = !strcmp(value, "1");
158 int BandwidthController::runIpxtablesCmd(const char *cmd, IptRejectOp rejectHandling,
159 IptFailureLog failureHandling) {
162 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
163 res |= runIptablesCmd(cmd, rejectHandling, IptIpV4, failureHandling);
164 res |= runIptablesCmd(cmd, rejectHandling, IptIpV6, failureHandling);
168 int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
170 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
171 strncpy(buffer, src, buffSize);
172 return buffer[buffSize - 1];
175 int BandwidthController::runIptablesCmd(const char *cmd, IptRejectOp rejectHandling,
176 IptIpVer iptVer, IptFailureLog failureHandling) {
177 char buffer[MAX_CMD_LEN];
178 const char *argv[MAX_CMD_ARGS];
184 std::string fullCmd = cmd;
186 if (rejectHandling == IptRejectAdd) {
187 fullCmd += " --jump REJECT --reject-with";
190 fullCmd += " icmp-net-prohibited";
193 fullCmd += " icmp6-adm-prohibited";
198 fullCmd.insert(0, " ");
199 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
201 if (!useLogwrapCall) {
202 res = system_nosh(fullCmd.c_str());
204 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
205 ALOGE("iptables command too long");
210 while ((tmp = strsep(&next, " "))) {
212 if (argc >= MAX_CMD_ARGS) {
213 ALOGE("iptables argument overflow");
219 res = logwrap(argc, argv);
221 if (res && failureHandling == IptFailShow) {
222 ALOGE("runIptablesCmd(): failed %s res=%d", fullCmd.c_str(), res);
227 int BandwidthController::setupIptablesHooks(void) {
229 /* Some of the initialCommands are allowed to fail */
230 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
231 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
233 runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
234 IPT_CLEANUP_COMMANDS, RunCmdFailureOk);
236 runCommands(sizeof(IPT_SETUP_COMMANDS) / sizeof(char*),
237 IPT_SETUP_COMMANDS, RunCmdFailureBad);
243 int BandwidthController::enableBandwidthControl(bool force) {
245 char value[PROPERTY_VALUE_MAX];
248 property_get("persist.bandwidth.enable", value, "1");
249 if (!strcmp(value, "0"))
253 /* Let's pretend we started from scratch ... */
254 sharedQuotaIfaces.clear();
256 naughtyAppUids.clear();
257 globalAlertBytes = 0;
258 globalAlertTetherCount = 0;
259 sharedQuotaBytes = sharedAlertBytes = 0;
261 res = runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
262 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
264 res |= runCommands(sizeof(IPT_BASIC_ACCOUNTING_COMMANDS) / sizeof(char*),
265 IPT_BASIC_ACCOUNTING_COMMANDS, RunCmdFailureBad);
271 int BandwidthController::disableBandwidthControl(void) {
272 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
273 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
277 int BandwidthController::runCommands(int numCommands, const char *commands[],
278 RunCmdErrHandling cmdErrHandling) {
280 IptFailureLog failureLogging = IptFailShow;
281 if (cmdErrHandling == RunCmdFailureOk) {
282 failureLogging = IptFailHide;
284 ALOGV("runCommands(): %d commands", numCommands);
285 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
286 res = runIpxtablesCmd(commands[cmdNum], IptRejectNoAdd, failureLogging);
287 if (res && cmdErrHandling != RunCmdFailureOk)
293 std::string BandwidthController::makeIptablesNaughtyCmd(IptOp op, int uid) {
310 asprintf(&buff, "%s penalty_box -m owner --uid-owner %d", opFlag, uid);
316 int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
317 return maninpulateNaughtyApps(numUids, appUids, NaughtyAppOpAdd);
320 int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
321 return maninpulateNaughtyApps(numUids, appUids, NaughtyAppOpRemove);
324 int BandwidthController::maninpulateNaughtyApps(int numUids, char *appStrUids[], NaughtyAppOp appOp) {
325 char cmd[MAX_CMD_LEN];
327 const char *failLogTemplate;
329 int appUids[numUids];
330 std::string naughtyCmd;
333 case NaughtyAppOpAdd:
335 failLogTemplate = "Failed to add app uid %d to penalty box.";
337 case NaughtyAppOpRemove:
339 failLogTemplate = "Failed to delete app uid %d from penalty box.";
342 ALOGE("Unexpected app Op %d", appOp);
346 for (uidNum = 0; uidNum < numUids; uidNum++) {
347 appUids[uidNum] = atol(appStrUids[uidNum]);
348 if (appUids[uidNum] == 0) {
349 ALOGE(failLogTemplate, appUids[uidNum]);
354 for (uidNum = 0; uidNum < numUids; uidNum++) {
355 naughtyCmd = makeIptablesNaughtyCmd(op, appUids[uidNum]);
356 if (runIpxtablesCmd(naughtyCmd.c_str(), IptRejectAdd)) {
357 ALOGE(failLogTemplate, appUids[uidNum]);
358 goto fail_with_uidNum;
364 /* Try to remove the uid that failed in any case*/
365 naughtyCmd = makeIptablesNaughtyCmd(IptOpDelete, appUids[uidNum]);
366 runIpxtablesCmd(naughtyCmd.c_str(), IptRejectAdd);
371 std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
376 ALOGV("makeIptablesQuotaCmd(%d, %lld)", op, quota);
391 // The requried IP version specific --jump REJECT ... will be added later.
392 asprintf(&buff, "%s costly_%s -m quota2 ! --quota %lld --name %s", opFlag, costName, quota,
399 int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
400 char cmd[MAX_CMD_LEN];
401 int res = 0, res1, res2;
402 int ruleInsertPos = 1;
403 std::string costString;
404 const char *costCString;
406 /* The "-N costly" is created upfront, no need to handle it here. */
409 costString = "costly_";
411 costCString = costString.c_str();
413 * Flush the costly_<iface> is allowed to fail in case it didn't exist.
414 * Creating a new one is allowed to fail in case it existed.
415 * This helps with netd restarts.
417 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
418 res1 = runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
419 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
420 res2 = runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
421 res = (res1 && res2) || (!res1 && !res2);
423 snprintf(cmd, sizeof(cmd), "-A %s -j penalty_box", costCString);
424 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
425 snprintf(cmd, sizeof(cmd), "-A %s -m owner --socket-exists", costCString);
426 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
429 costCString = "costly_shared";
432 ALOGE("Unexpected quotatype %d", quotaType);
436 if (globalAlertBytes) {
437 /* The alert rule comes 1st */
441 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
442 runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
444 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
445 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
447 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
448 runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
450 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
451 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
455 int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
456 char cmd[MAX_CMD_LEN];
458 std::string costString;
459 const char *costCString;
463 costString = "costly_";
465 costCString = costString.c_str();
468 costCString = "costly_shared";
471 ALOGE("Unexpected quotatype %d", quotaType);
475 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
476 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
477 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
478 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
480 /* The "-N costly_shared" is created upfront, no need to handle it here. */
481 if (quotaType == QuotaUnique) {
482 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
483 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
484 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
485 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
490 int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
491 char cmd[MAX_CMD_LEN];
492 char ifn[MAX_IFACENAME_LEN];
494 std::string quotaCmd;
495 std::string ifaceName;
497 const char *costName = "shared";
498 std::list<std::string>::iterator it;
501 /* Don't talk about -1, deprecate it. */
502 ALOGE("Invalid bytes value. 1..max_int64.");
505 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
506 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
511 if (maxBytes == -1) {
512 return removeInterfaceSharedQuota(ifn);
515 /* Insert ingress quota. */
516 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
517 if (*it == ifaceName)
521 if (it == sharedQuotaIfaces.end()) {
522 res |= prepCostlyIface(ifn, QuotaShared);
523 if (sharedQuotaIfaces.empty()) {
524 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
525 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
527 ALOGE("Failed set quota rule");
530 sharedQuotaBytes = maxBytes;
532 sharedQuotaIfaces.push_front(ifaceName);
536 if (maxBytes != sharedQuotaBytes) {
537 res |= updateQuota(costName, maxBytes);
539 ALOGE("Failed update quota for %s", costName);
542 sharedQuotaBytes = maxBytes;
548 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
549 * rules in the kernel to see which ones need cleaning up.
550 * For now callers needs to choose if they want to "ndc bandwidth enable"
551 * which resets everything.
553 removeInterfaceSharedQuota(ifn);
557 /* It will also cleanup any shared alerts */
558 int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
559 char ifn[MAX_IFACENAME_LEN];
561 std::string ifaceName;
562 std::list<std::string>::iterator it;
563 const char *costName = "shared";
565 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
566 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
571 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
572 if (*it == ifaceName)
575 if (it == sharedQuotaIfaces.end()) {
576 ALOGE("No such iface %s to delete", ifn);
580 res |= cleanupCostlyIface(ifn, QuotaShared);
581 sharedQuotaIfaces.erase(it);
583 if (sharedQuotaIfaces.empty()) {
584 std::string quotaCmd;
585 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
586 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
587 sharedQuotaBytes = 0;
588 if (sharedAlertBytes) {
590 sharedAlertBytes = 0;
596 int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
597 char ifn[MAX_IFACENAME_LEN];
599 std::string ifaceName;
600 const char *costName;
601 std::list<QuotaInfo>::iterator it;
602 std::string quotaCmd;
605 /* Don't talk about -1, deprecate it. */
606 ALOGE("Invalid bytes value. 1..max_int64.");
609 if (maxBytes == -1) {
610 return removeInterfaceQuota(iface);
613 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
614 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
620 /* Insert ingress quota. */
621 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
622 if (it->ifaceName == ifaceName)
626 if (it == quotaIfaces.end()) {
627 res |= prepCostlyIface(ifn, QuotaUnique);
628 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
629 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
631 ALOGE("Failed set quota rule");
635 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
638 res |= updateQuota(costName, maxBytes);
640 ALOGE("Failed update quota for %s", iface);
643 it->quota = maxBytes;
649 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
650 * rules in the kernel to see which ones need cleaning up.
651 * For now callers needs to choose if they want to "ndc bandwidth enable"
652 * which resets everything.
654 removeInterfaceSharedQuota(ifn);
658 int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
659 return getInterfaceQuota("shared", bytes);
662 int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
667 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
668 fp = fopen(fname, "r");
671 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
674 scanRes = fscanf(fp, "%lld", bytes);
675 ALOGV("Read quota res=%d bytes=%lld", scanRes, *bytes);
677 return scanRes == 1 ? 0 : -1;
680 int BandwidthController::removeInterfaceQuota(const char *iface) {
682 char ifn[MAX_IFACENAME_LEN];
684 std::string ifaceName;
685 const char *costName;
686 std::list<QuotaInfo>::iterator it;
688 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
689 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
695 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
696 if (it->ifaceName == ifaceName)
700 if (it == quotaIfaces.end()) {
701 ALOGE("No such iface %s to delete", ifn);
705 /* This also removes the quota command of CostlyIface chain. */
706 res |= cleanupCostlyIface(ifn, QuotaUnique);
708 quotaIfaces.erase(it);
713 int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
717 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
718 fp = fopen(fname, "w");
721 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
724 fprintf(fp, "%lld\n", bytes);
729 int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
732 const char *ifaceLimiting;
748 ifaceLimiting = "! -i lo+";
749 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, ifaceLimiting, opFlag, "bw_INPUT",
751 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
753 ifaceLimiting = "! -o lo+";
754 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, ifaceLimiting, opFlag, "bw_OUTPUT",
756 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
761 int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
764 const char *ifaceLimiting;
780 ifaceLimiting = "! -i lo+";
781 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, ifaceLimiting, opFlag, "bw_FORWARD",
783 res = runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
788 int BandwidthController::setGlobalAlert(int64_t bytes) {
789 const char *alertName = ALERT_GLOBAL_NAME;
793 ALOGE("Invalid bytes value. 1..max_int64.");
796 if (globalAlertBytes) {
797 res = updateQuota(alertName, bytes);
799 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
800 if (globalAlertTetherCount) {
801 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
802 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
805 globalAlertBytes = bytes;
809 int BandwidthController::setGlobalAlertInForwardChain(void) {
810 const char *alertName = ALERT_GLOBAL_NAME;
813 globalAlertTetherCount++;
814 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
817 * If there is no globalAlert active we are done.
818 * If there is an active globalAlert but this is not the 1st
819 * tether, we are also done.
821 if (!globalAlertBytes || globalAlertTetherCount != 1) {
825 /* We only add the rule if this was the 1st tether added. */
826 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
830 int BandwidthController::removeGlobalAlert(void) {
832 const char *alertName = ALERT_GLOBAL_NAME;
835 if (!globalAlertBytes) {
836 ALOGE("No prior alert set");
839 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
840 if (globalAlertTetherCount) {
841 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
843 globalAlertBytes = 0;
847 int BandwidthController::removeGlobalAlertInForwardChain(void) {
849 const char *alertName = ALERT_GLOBAL_NAME;
851 if (!globalAlertTetherCount) {
852 ALOGE("No prior alert set");
856 globalAlertTetherCount--;
858 * If there is no globalAlert active we are done.
859 * If there is an active globalAlert but there are more
860 * tethers, we are also done.
862 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
866 /* We only detete the rule if this was the last tether removed. */
867 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
871 int BandwidthController::setSharedAlert(int64_t bytes) {
872 if (!sharedQuotaBytes) {
873 ALOGE("Need to have a prior shared quota set to set an alert");
877 ALOGE("Invalid bytes value. 1..max_int64.");
880 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
883 int BandwidthController::removeSharedAlert(void) {
884 return removeCostlyAlert("shared", &sharedAlertBytes);
887 int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
888 std::list<QuotaInfo>::iterator it;
891 ALOGE("Invalid bytes value. 1..max_int64.");
894 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
895 if (it->ifaceName == iface)
899 if (it == quotaIfaces.end()) {
900 ALOGE("Need to have a prior interface quota set to set an alert");
904 return setCostlyAlert(iface, bytes, &it->alert);
907 int BandwidthController::removeInterfaceAlert(const char *iface) {
908 std::list<QuotaInfo>::iterator it;
910 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
911 if (it->ifaceName == iface)
915 if (it == quotaIfaces.end()) {
916 ALOGE("No prior alert set for interface %s", iface);
920 return removeCostlyAlert(iface, &it->alert);
923 int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
925 char *chainNameAndPos;
930 ALOGE("Invalid bytes value. 1..max_int64.");
933 asprintf(&alertName, "%sAlert", costName);
935 res = updateQuota(alertName, *alertBytes);
937 asprintf(&chainNameAndPos, "costly_%s %d", costName, ALERT_RULE_POS_IN_COSTLY_CHAIN);
938 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "", "-I", chainNameAndPos, bytes, alertName);
939 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
941 free(chainNameAndPos);
948 int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
954 asprintf(&alertName, "%sAlert", costName);
956 ALOGE("No prior alert set for %s alert", costName);
960 asprintf(&chainName, "costly_%s", costName);
961 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "", "-D", chainName, *alertBytes, alertName);
962 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
972 * Parse the ptks and bytes out of:
973 * Chain FORWARD (policy RETURN 0 packets, 0 bytes)
974 * pkts bytes target prot opt in out source destination
975 * 0 0 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
976 * 0 0 DROP all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0 state INVALID
977 * 0 0 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
980 int BandwidthController::parseForwardChainStats(TetherStats &stats, FILE *fp,
981 std::string &extraProcessingInfo) {
983 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
984 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
985 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
986 char rest[MAX_IPT_OUTPUT_LINE_LEN];
989 int64_t packets, bytes;
991 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
992 /* Clean up, so a failed parse can still print info */
993 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
994 res = sscanf(buffPtr, "%lld %lld RETURN all -- %s %s 0.%s",
995 &packets, &bytes, iface0, iface1, rest);
996 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%lld bytes=%lld rest=<%s> orig line=<%s>", res,
997 iface0, iface1, packets, bytes, rest, buffPtr);
998 extraProcessingInfo += buffPtr;
1003 if ((stats.ifaceIn == iface0) && (stats.ifaceOut == iface1)) {
1004 ALOGV("iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1005 stats.rxPackets = packets;
1006 stats.rxBytes = bytes;
1007 } else if ((stats.ifaceOut == iface0) && (stats.ifaceIn == iface1)) {
1008 ALOGV("iface_in=%s iface_out=%s tx_bytes=%lld tx_packets=%lld ", iface1, iface0, bytes, packets);
1009 stats.txPackets = packets;
1010 stats.txBytes = bytes;
1013 /* Failure if rx or tx was not found */
1014 return (stats.rxBytes == -1 || stats.txBytes == -1) ? -1 : 0;
1018 char *BandwidthController::TetherStats::getStatsLine(void) {
1020 asprintf(&msg, "%s %s %lld %lld %lld %lld", ifaceIn.c_str(), ifaceOut.c_str(),
1021 rxBytes, rxPackets, txBytes, txPackets);
1025 int BandwidthController::getTetherStats(TetherStats &stats, std::string &extraProcessingInfo) {
1027 std::string fullCmd;
1031 if (stats.rxBytes != -1 || stats.txBytes != -1) {
1032 ALOGE("Unexpected input stats. Byte counts should be -1.");
1037 * Why not use some kind of lib to talk to iptables?
1038 * Because the only libs are libiptc and libip6tc in iptables, and they are
1039 * not easy to use. They require the known iptables match modules to be
1040 * preloaded/linked, and require apparently a lot of wrapper code to get
1043 fullCmd = IPTABLES_PATH;
1044 fullCmd += " -nvx -L natctrl_FORWARD";
1045 iptOutput = popen(fullCmd.c_str(), "r");
1047 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
1048 extraProcessingInfo += "Failed to run iptables.";
1051 res = parseForwardChainStats(stats, iptOutput, extraProcessingInfo);
1054 /* Currently NatController doesn't do ipv6 tethering, so we are done. */