blob: f0a856e10e787c2ac339eb0189ba5b912aa89654 [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 Abgralldb7da582011-09-18 12:57:32 -070017// #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
JP Abgrall8a932722011-07-13 19:17:35 -070025#include <errno.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070026#include <fcntl.h>
JP Abgralldb7da582011-09-18 12:57:32 -070027#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070028#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070029#include <string.h>
30
31#include <sys/socket.h>
32#include <sys/stat.h>
33#include <sys/types.h>
34#include <sys/wait.h>
35
36#include <linux/netlink.h>
37#include <linux/rtnetlink.h>
38#include <linux/pkt_sched.h>
39
40#define LOG_TAG "BandwidthController"
41#include <cutils/log.h>
42#include <cutils/properties.h>
43
44extern "C" int logwrap(int argc, const char **argv, int background);
45
46#include "BandwidthController.h"
47
JP Abgralldb7da582011-09-18 12:57:32 -070048/* Alphabetical */
JP Abgrall87666692011-09-08 13:44:10 -070049const char BandwidthController::ALERT_IPT_TEMPLATE[] = "%s %s %s -m quota2 ! --quota %lld --name %s";
JP Abgralldb7da582011-09-18 12:57:32 -070050const int BandwidthController::ALERT_RULE_POS_IN_COSTLY_CHAIN = 4;
JP Abgrallc6c67342011-10-07 16:28:54 -070051const char BandwidthController::ALERT_GLOBAL_NAME[] = "globalAlert";
JP Abgralldb7da582011-09-18 12:57:32 -070052const char BandwidthController::IP6TABLES_PATH[] = "/system/bin/ip6tables";
53const char BandwidthController::IPTABLES_PATH[] = "/system/bin/iptables";
54const int BandwidthController::MAX_CMD_ARGS = 32;
55const int BandwidthController::MAX_CMD_LEN = 1024;
56const int BandwidthController::MAX_IFACENAME_LEN = 64;
57const int BandwidthController::MAX_IPT_OUTPUT_LINE_LEN = 256;
58
JP Abgrall11b4e9b2011-08-11 15:34:49 -070059bool BandwidthController::useLogwrapCall = false;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070060
61/**
62 * Some comments about the rules:
63 * * Ordering
64 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
65 * E.g. "-I INPUT -i rmnet0 --goto costly"
66 * - quota'd rules in the costly chain should be before penalty_box lookups.
67 *
68 * * global quota vs per interface quota
69 * - global quota for all costly interfaces uses a single costly chain:
70 * . initial rules
JP Abgrallbfa74662011-06-29 19:23:04 -070071 * iptables -N costly_shared
72 * iptables -I INPUT -i iface0 --goto costly_shared
73 * iptables -I OUTPUT -o iface0 --goto 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
JP Abgrall8a932722011-07-13 19:17:35 -070078 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070079 * . adding a new iface to this, E.g.:
JP Abgrallbfa74662011-06-29 19:23:04 -070080 * iptables -I INPUT -i iface1 --goto costly_shared
81 * iptables -I OUTPUT -o iface1 --goto costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070082 *
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 --goto costly_iface0
87 * iptables -I OUTPUT -o iface0 --goto costly_iface0
JP Abgrallbfa74662011-06-29 19:23:04 -070088 * iptables -A costly_iface0 -m quota \! --quota 500000 \
89 * --jump REJECT --reject-with icmp-net-prohibited
90 * iptables -A costly_iface0 --jump penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070091 * iptables -A costly_iface0 -m owner --socket-exists
92 *
93 * * penalty_box handling:
94 * - only one penalty_box for all interfaces
95 * E.g Adding an app:
JP Abgrallbfa74662011-06-29 19:23:04 -070096 * iptables -A penalty_box -m owner --uid-owner app_3 \
97 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070098 */
JP Abgralldb7da582011-09-18 12:57:32 -070099const char *BandwidthController::IPT_CLEANUP_COMMANDS[] = {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700100 /* Cleanup rules. */
101 "-F",
102 "-t raw -F",
JP Abgrall39f8f242011-06-29 19:21:58 -0700103 /* TODO: If at some point we need more user chains than here, then we will need
104 * a different cleanup approach.
105 */
JP Abgrallbfa74662011-06-29 19:23:04 -0700106 "-X", /* Should normally only be costly_shared, penalty_box, and costly_<iface> */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700107};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700108
JP Abgralldb7da582011-09-18 12:57:32 -0700109const char *BandwidthController::IPT_SETUP_COMMANDS[] = {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700110 /* Created needed chains. */
JP Abgrallbfa74662011-06-29 19:23:04 -0700111 "-N costly_shared",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700112 "-N penalty_box",
113};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700114
JP Abgralldb7da582011-09-18 12:57:32 -0700115const char *BandwidthController::IPT_BASIC_ACCOUNTING_COMMANDS[] = {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700116 "-F INPUT",
117 "-A INPUT -i lo --jump ACCEPT",
118 "-A INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700119
JP Abgrall0dad7c22011-06-24 11:58:14 -0700120 "-F OUTPUT",
121 "-A OUTPUT -o lo --jump ACCEPT",
122 "-A OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700123
JP Abgrallbfa74662011-06-29 19:23:04 -0700124 "-F costly_shared",
125 "-A costly_shared --jump penalty_box",
126 "-A costly_shared -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700127 /* TODO(jpa): Figure out why iptables doesn't correctly return from this
128 * chain. For now, hack the chain exit with an ACCEPT.
129 */
JP Abgrallbfa74662011-06-29 19:23:04 -0700130 "-A costly_shared --jump ACCEPT",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700131};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700132
133BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700134 char value[PROPERTY_VALUE_MAX];
135
136 property_get("persist.bandwidth.enable", value, "0");
137 if (!strcmp(value, "1")) {
138 enableBandwidthControl();
139 }
140
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700141 property_get("persist.bandwidth.uselogwrap", value, "0");
142 useLogwrapCall = !strcmp(value, "1");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700143}
144
JP Abgrall26e0d492011-06-24 19:21:51 -0700145int BandwidthController::runIpxtablesCmd(const char *cmd, IptRejectOp rejectHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700146 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700147
JP Abgralldb7da582011-09-18 12:57:32 -0700148 LOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700149 res |= runIptablesCmd(cmd, rejectHandling, IptIpV4);
150 res |= runIptablesCmd(cmd, rejectHandling, IptIpV6);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700151 return res;
152}
153
JP Abgrall26e0d492011-06-24 19:21:51 -0700154int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
155
156 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
157 strncpy(buffer, src, buffSize);
158 return buffer[buffSize - 1];
159}
160
JP Abgrall8a932722011-07-13 19:17:35 -0700161int BandwidthController::runIptablesCmd(const char *cmd, IptRejectOp rejectHandling,
162 IptIpVer iptVer) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700163 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700164 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700165 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700166 char *next = buffer;
167 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700168 int res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700169
JP Abgrall0dad7c22011-06-24 11:58:14 -0700170 std::string fullCmd = cmd;
JP Abgrall26e0d492011-06-24 19:21:51 -0700171
172 if (rejectHandling == IptRejectAdd) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700173 fullCmd += " --jump REJECT --reject-with";
JP Abgrall26e0d492011-06-24 19:21:51 -0700174 switch (iptVer) {
175 case IptIpV4:
JP Abgrall8a932722011-07-13 19:17:35 -0700176 fullCmd += " icmp-net-prohibited";
177 break;
JP Abgrall26e0d492011-06-24 19:21:51 -0700178 case IptIpV6:
JP Abgrall8a932722011-07-13 19:17:35 -0700179 fullCmd += " icmp6-adm-prohibited";
180 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700181 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700182 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700183
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700184 fullCmd.insert(0, " ");
185 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700186
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700187 if (!useLogwrapCall) {
188 res = system(fullCmd.c_str());
189 } else {
190 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
191 LOGE("iptables command too long");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700192 return -1;
193 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700194
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700195 argc = 0;
196 while ((tmp = strsep(&next, " "))) {
197 argv[argc++] = tmp;
198 if (argc >= MAX_CMD_ARGS) {
199 LOGE("iptables argument overflow");
200 return -1;
201 }
202 }
203
204 argv[argc] = NULL;
205 res = logwrap(argc, argv, 0);
206 }
207 if (res) {
208 LOGE("runIptablesCmd(): failed %s res=%d", fullCmd.c_str(), res);
209 }
210 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700211}
212
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700213int BandwidthController::enableBandwidthControl(void) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700214 int res;
JP Abgrall8a932722011-07-13 19:17:35 -0700215
JP Abgralldb7da582011-09-18 12:57:32 -0700216 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700217 sharedQuotaIfaces.clear();
218 quotaIfaces.clear();
219 naughtyAppUids.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700220 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700221 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700222 sharedQuotaBytes = sharedAlertBytes = 0;
223
224
225 /* Some of the initialCommands are allowed to fail */
226 runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
227 IPT_CLEANUP_COMMANDS, RunCmdFailureOk);
228 runCommands(sizeof(IPT_SETUP_COMMANDS) / sizeof(char*),
229 IPT_SETUP_COMMANDS, RunCmdFailureOk);
230 res = runCommands(sizeof(IPT_BASIC_ACCOUNTING_COMMANDS) / sizeof(char*),
231 IPT_BASIC_ACCOUNTING_COMMANDS, RunCmdFailureBad);
JP Abgrall8a932722011-07-13 19:17:35 -0700232
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700233 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700234
235}
236
237int BandwidthController::disableBandwidthControl(void) {
JP Abgralldb7da582011-09-18 12:57:32 -0700238 /* The IPT_CLEANUP_COMMANDS are allowed to fail. */
239 runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
240 IPT_CLEANUP_COMMANDS, RunCmdFailureOk);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700241 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700242}
243
JP Abgrall8a932722011-07-13 19:17:35 -0700244int BandwidthController::runCommands(int numCommands, const char *commands[],
245 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700246 int res = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700247 LOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700248 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700249 res = runIpxtablesCmd(commands[cmdNum], IptRejectNoAdd);
250 if (res && cmdErrHandling != RunCmdFailureBad)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700251 return res;
252 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700253 return cmdErrHandling == RunCmdFailureBad ? res : 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700254}
255
JP Abgrall0dad7c22011-06-24 11:58:14 -0700256std::string BandwidthController::makeIptablesNaughtyCmd(IptOp op, int uid) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700257 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700258 char *buff;
259 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700260
261 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700262 case IptOpInsert:
263 opFlag = "-I";
264 break;
265 case IptOpReplace:
266 opFlag = "-R";
267 break;
268 default:
269 case IptOpDelete:
270 opFlag = "-D";
271 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700272 }
JP Abgrall8a932722011-07-13 19:17:35 -0700273 asprintf(&buff, "%s penalty_box -m owner --uid-owner %d", opFlag, uid);
274 res = buff;
275 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700276 return res;
277}
278
279int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700280 return maninpulateNaughtyApps(numUids, appUids, NaughtyAppOpAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700281}
282
283int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700284 return maninpulateNaughtyApps(numUids, appUids, NaughtyAppOpRemove);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700285}
286
JP Abgrall26e0d492011-06-24 19:21:51 -0700287int BandwidthController::maninpulateNaughtyApps(int numUids, char *appStrUids[], NaughtyAppOp appOp) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700288 char cmd[MAX_CMD_LEN];
289 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700290 const char *failLogTemplate;
291 IptOp op;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700292 int appUids[numUids];
JP Abgrall26e0d492011-06-24 19:21:51 -0700293 std::string naughtyCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700294
JP Abgrall26e0d492011-06-24 19:21:51 -0700295 switch (appOp) {
296 case NaughtyAppOpAdd:
JP Abgrall8a932722011-07-13 19:17:35 -0700297 op = IptOpInsert;
298 failLogTemplate = "Failed to add app uid %d to penalty box.";
299 break;
JP Abgrall26e0d492011-06-24 19:21:51 -0700300 case NaughtyAppOpRemove:
JP Abgrall8a932722011-07-13 19:17:35 -0700301 op = IptOpDelete;
302 failLogTemplate = "Failed to delete app uid %d from penalty box.";
303 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700304 }
305
306 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700307 appUids[uidNum] = atol(appStrUids[uidNum]);
308 if (appUids[uidNum] == 0) {
309 LOGE(failLogTemplate, appUids[uidNum]);
310 goto fail_parse;
311 }
312 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700313
314 for (uidNum = 0; uidNum < numUids; uidNum++) {
315 naughtyCmd = makeIptablesNaughtyCmd(op, appUids[uidNum]);
316 if (runIpxtablesCmd(naughtyCmd.c_str(), IptRejectAdd)) {
317 LOGE(failLogTemplate, appUids[uidNum]);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700318 goto fail_with_uidNum;
319 }
320 }
321 return 0;
322
JP Abgrall26e0d492011-06-24 19:21:51 -0700323fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700324 /* Try to remove the uid that failed in any case*/
JP Abgrall26e0d492011-06-24 19:21:51 -0700325 naughtyCmd = makeIptablesNaughtyCmd(IptOpDelete, appUids[uidNum]);
326 runIpxtablesCmd(naughtyCmd.c_str(), IptRejectAdd);
327fail_parse:
328 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700329}
330
JP Abgrall26e0d492011-06-24 19:21:51 -0700331std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700332 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700333 char *buff;
334 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700335
JP Abgralldb7da582011-09-18 12:57:32 -0700336 LOGV("makeIptablesQuotaCmd(%d, %lld)", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700337
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700338 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700339 case IptOpInsert:
340 opFlag = "-I";
341 break;
342 case IptOpReplace:
343 opFlag = "-R";
344 break;
345 default:
346 case IptOpDelete:
347 opFlag = "-D";
348 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700349 }
JP Abgrall8a932722011-07-13 19:17:35 -0700350
JP Abgrallbfa74662011-06-29 19:23:04 -0700351 // The requried IP version specific --jump REJECT ... will be added later.
JP Abgrall8a932722011-07-13 19:17:35 -0700352 asprintf(&buff, "%s costly_%s -m quota2 ! --quota %lld --name %s", opFlag, costName, quota,
353 costName);
354 res = buff;
355 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700356 return res;
357}
358
JP Abgrall26e0d492011-06-24 19:21:51 -0700359int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700360 char cmd[MAX_CMD_LEN];
361 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700362 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700363 std::string costString;
364 const char *costCString;
365
JP Abgrall0dad7c22011-06-24 11:58:14 -0700366 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700367 switch (quotaType) {
368 case QuotaUnique:
JP Abgrallbfa74662011-06-29 19:23:04 -0700369 costString = "costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700370 costString += ifn;
371 costCString = costString.c_str();
372 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700373 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700374 snprintf(cmd, sizeof(cmd), "-A %s -j penalty_box", costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700375 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700376 snprintf(cmd, sizeof(cmd), "-A %s -m owner --socket-exists", costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700377 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700378 /* TODO(jpa): Figure out why iptables doesn't correctly return from this
379 * chain. For now, hack the chain exit with an ACCEPT.
380 */
381 snprintf(cmd, sizeof(cmd), "-A %s --jump ACCEPT", costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700382 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
383 break;
384 case QuotaShared:
JP Abgrallbfa74662011-06-29 19:23:04 -0700385 costCString = "costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700386 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700387 }
388
JP Abgrall8a932722011-07-13 19:17:35 -0700389 if (globalAlertBytes) {
390 /* The alert rule comes 1st */
391 ruleInsertPos = 2;
392 }
393 snprintf(cmd, sizeof(cmd), "-I INPUT %d -i %s --goto %s", ruleInsertPos, ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700394 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700395 snprintf(cmd, sizeof(cmd), "-I OUTPUT %d -o %s --goto %s", ruleInsertPos, ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700396 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700397 return res;
398}
399
JP Abgrall26e0d492011-06-24 19:21:51 -0700400int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700401 char cmd[MAX_CMD_LEN];
402 int res = 0;
403 std::string costString;
404 const char *costCString;
405
JP Abgrall26e0d492011-06-24 19:21:51 -0700406 switch (quotaType) {
407 case QuotaUnique:
JP Abgrallbfa74662011-06-29 19:23:04 -0700408 costString = "costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700409 costString += ifn;
410 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700411 break;
412 case QuotaShared:
JP Abgrallbfa74662011-06-29 19:23:04 -0700413 costCString = "costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700414 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700415 }
416
417 snprintf(cmd, sizeof(cmd), "-D INPUT -i %s --goto %s", ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700418 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700419 snprintf(cmd, sizeof(cmd), "-D OUTPUT -o %s --goto %s", ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700420 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700421
JP Abgrallbfa74662011-06-29 19:23:04 -0700422 /* The "-N costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700423 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700424 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700425 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700426 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
427 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700428 }
429 return res;
430}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700431
JP Abgrall0dad7c22011-06-24 11:58:14 -0700432int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700433 char cmd[MAX_CMD_LEN];
434 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700435 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700436 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700437 std::string ifaceName;
438 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700439 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700440 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700441
JP Abgrall8a932722011-07-13 19:17:35 -0700442 if (!maxBytes) {
443 /* Don't talk about -1, deprecate it. */
444 LOGE("Invalid bytes value. 1..max_int64.");
445 return -1;
446 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700447 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
448 LOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
449 return -1;
450 }
451 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700452
453 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700454 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700455 }
456
457 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700458 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
459 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700460 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700461 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700462
JP Abgrall0dad7c22011-06-24 11:58:14 -0700463 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700464 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700465 if (sharedQuotaIfaces.empty()) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700466 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgrall26e0d492011-06-24 19:21:51 -0700467 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700468 if (res) {
JP Abgrall8a932722011-07-13 19:17:35 -0700469 LOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700470 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700471 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700472 sharedQuotaBytes = maxBytes;
473 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700474 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700475
476 }
477
478 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700479 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700480 if (res) {
JP Abgrall8a932722011-07-13 19:17:35 -0700481 LOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700482 goto fail;
483 }
484 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700485 }
486 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700487
488 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700489 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700490 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
491 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700492 * For now callers needs to choose if they want to "ndc bandwidth enable"
493 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700494 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700495 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700496 return -1;
497}
498
JP Abgrall8a932722011-07-13 19:17:35 -0700499/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700500int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700501 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700502 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700503 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700504 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700505 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700506
JP Abgrall8a932722011-07-13 19:17:35 -0700507 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700508 LOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
509 return -1;
510 }
JP Abgrall8a932722011-07-13 19:17:35 -0700511 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700512
JP Abgrall0dad7c22011-06-24 11:58:14 -0700513 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
514 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700515 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700516 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700517 if (it == sharedQuotaIfaces.end()) {
JP Abgrall8a932722011-07-13 19:17:35 -0700518 LOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700519 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700520 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700521
JP Abgrall26e0d492011-06-24 19:21:51 -0700522 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700523 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700524
JP Abgrall0dad7c22011-06-24 11:58:14 -0700525 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700526 std::string quotaCmd;
JP Abgrallbfa74662011-06-29 19:23:04 -0700527 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
JP Abgrall26e0d492011-06-24 19:21:51 -0700528 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700529 sharedQuotaBytes = 0;
530 if (sharedAlertBytes) {
531 removeSharedAlert();
532 sharedAlertBytes = 0;
533 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700534 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700535 return res;
536}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700537
538int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
539 char ifn[MAX_IFACENAME_LEN];
540 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700541 std::string ifaceName;
542 const char *costName;
543 std::list<QuotaInfo>::iterator it;
544 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700545
JP Abgrall8a932722011-07-13 19:17:35 -0700546 if (!maxBytes) {
547 /* Don't talk about -1, deprecate it. */
548 LOGE("Invalid bytes value. 1..max_int64.");
549 return -1;
550 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700551 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700552 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700553 }
554
JP Abgrall8a932722011-07-13 19:17:35 -0700555 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700556 LOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
557 return -1;
558 }
559 ifaceName = ifn;
560 costName = iface;
561
JP Abgrall0dad7c22011-06-24 11:58:14 -0700562 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700563 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700564 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700565 break;
566 }
567
568 if (it == quotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700569 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700570 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgrall26e0d492011-06-24 19:21:51 -0700571 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700572 if (res) {
JP Abgrall8a932722011-07-13 19:17:35 -0700573 LOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700574 goto fail;
575 }
576
JP Abgrall8a932722011-07-13 19:17:35 -0700577 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700578
579 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700580 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700581 if (res) {
JP Abgrall8a932722011-07-13 19:17:35 -0700582 LOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700583 goto fail;
584 }
JP Abgrall8a932722011-07-13 19:17:35 -0700585 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700586 }
587 return 0;
588
589 fail:
590 /*
591 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
592 * rules in the kernel to see which ones need cleaning up.
593 * For now callers needs to choose if they want to "ndc bandwidth enable"
594 * which resets everything.
595 */
596 removeInterfaceSharedQuota(ifn);
597 return -1;
598}
599
JP Abgrall8a932722011-07-13 19:17:35 -0700600int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
601 return getInterfaceQuota("shared", bytes);
602}
603
604int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
605 FILE *fp;
606 char *fname;
607 int scanRes;
608
609 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
610 fp = fopen(fname, "r");
611 free(fname);
612 if (!fp) {
613 LOGE("Reading quota %s failed (%s)", costName, strerror(errno));
614 return -1;
615 }
616 scanRes = fscanf(fp, "%lld", bytes);
JP Abgralldb7da582011-09-18 12:57:32 -0700617 LOGV("Read quota res=%d bytes=%lld", scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700618 fclose(fp);
619 return scanRes == 1 ? 0 : -1;
620}
621
JP Abgrall0dad7c22011-06-24 11:58:14 -0700622int BandwidthController::removeInterfaceQuota(const char *iface) {
623
624 char ifn[MAX_IFACENAME_LEN];
625 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700626 std::string ifaceName;
627 const char *costName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700628 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700629
JP Abgrall8a932722011-07-13 19:17:35 -0700630 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700631 LOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
632 return -1;
633 }
634 ifaceName = ifn;
635 costName = iface;
636
JP Abgrall0dad7c22011-06-24 11:58:14 -0700637 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700638 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700639 break;
640 }
641
642 if (it == quotaIfaces.end()) {
JP Abgrall8a932722011-07-13 19:17:35 -0700643 LOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700644 return -1;
645 }
646
647 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700648 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700649
650 quotaIfaces.erase(it);
651
652 return res;
653}
JP Abgrall8a932722011-07-13 19:17:35 -0700654
655int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
656 FILE *fp;
657 char *fname;
658
659 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
660 fp = fopen(fname, "w");
661 free(fname);
662 if (!fp) {
663 LOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
664 return -1;
665 }
666 fprintf(fp, "%lld\n", bytes);
667 fclose(fp);
668 return 0;
669}
670
671int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
672 int res = 0;
673 const char *opFlag;
JP Abgrall87666692011-09-08 13:44:10 -0700674 const char *ifaceLimiting;
JP Abgrall8a932722011-07-13 19:17:35 -0700675 char *alertQuotaCmd;
676
677 switch (op) {
678 case IptOpInsert:
679 opFlag = "-I";
680 break;
681 case IptOpReplace:
682 opFlag = "-R";
683 break;
684 default:
685 case IptOpDelete:
686 opFlag = "-D";
687 break;
688 }
689
JP Abgrall87666692011-09-08 13:44:10 -0700690 ifaceLimiting = "! -i lo+";
691 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, ifaceLimiting, opFlag, "INPUT",
692 bytes, alertName, alertName);
JP Abgrall8a932722011-07-13 19:17:35 -0700693 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
694 free(alertQuotaCmd);
JP Abgrall87666692011-09-08 13:44:10 -0700695 ifaceLimiting = "! -o lo+";
696 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, ifaceLimiting, opFlag, "OUTPUT",
697 bytes, alertName, alertName);
JP Abgrall8a932722011-07-13 19:17:35 -0700698 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
699 free(alertQuotaCmd);
700 return res;
701}
702
JP Abgrallc6c67342011-10-07 16:28:54 -0700703int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
704 int res = 0;
705 const char *opFlag;
706 const char *ifaceLimiting;
JP Abgrall8a932722011-07-13 19:17:35 -0700707 char *alertQuotaCmd;
JP Abgrallc6c67342011-10-07 16:28:54 -0700708
709 switch (op) {
710 case IptOpInsert:
711 opFlag = "-I";
712 break;
713 case IptOpReplace:
714 opFlag = "-R";
715 break;
716 default:
717 case IptOpDelete:
718 opFlag = "-D";
719 break;
720 }
721
722 ifaceLimiting = "! -i lo+";
723 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, ifaceLimiting, opFlag, "FORWARD",
724 bytes, alertName, alertName);
725 res = runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
726 free(alertQuotaCmd);
727 return res;
728}
729
730int BandwidthController::setGlobalAlert(int64_t bytes) {
731 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700732 int res = 0;
733
734 if (!bytes) {
735 LOGE("Invalid bytes value. 1..max_int64.");
736 return -1;
737 }
738 if (globalAlertBytes) {
739 res = updateQuota(alertName, bytes);
740 } else {
741 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700742 if (globalAlertTetherCount) {
743 LOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
744 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
745 }
JP Abgrall8a932722011-07-13 19:17:35 -0700746 }
747 globalAlertBytes = bytes;
748 return res;
749}
750
JP Abgrallc6c67342011-10-07 16:28:54 -0700751int BandwidthController::setGlobalAlertInForwardChain(void) {
752 const char *alertName = ALERT_GLOBAL_NAME;
753 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700754
JP Abgrallc6c67342011-10-07 16:28:54 -0700755 globalAlertTetherCount++;
756 LOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
757
758 /*
759 * If there is no globalAlert active we are done.
760 * If there is an active globalAlert but this is not the 1st
761 * tether, we are also done.
762 */
763 if (!globalAlertBytes || globalAlertTetherCount != 1) {
764 return 0;
765 }
766
767 /* We only add the rule if this was the 1st tether added. */
768 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
769 return res;
770}
771
772int BandwidthController::removeGlobalAlert(void) {
773
774 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700775 int res = 0;
776
777 if (!globalAlertBytes) {
778 LOGE("No prior alert set");
779 return -1;
780 }
781 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700782 if (globalAlertTetherCount) {
783 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
784 }
JP Abgrall8a932722011-07-13 19:17:35 -0700785 globalAlertBytes = 0;
786 return res;
787}
788
JP Abgrallc6c67342011-10-07 16:28:54 -0700789int BandwidthController::removeGlobalAlertInForwardChain(void) {
790 int res = 0;
791 const char *alertName = ALERT_GLOBAL_NAME;
792
793 if (!globalAlertTetherCount) {
794 LOGE("No prior alert set");
795 return -1;
796 }
797
798 globalAlertTetherCount--;
799 /*
800 * If there is no globalAlert active we are done.
801 * If there is an active globalAlert but there are more
802 * tethers, we are also done.
803 */
804 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
805 return 0;
806 }
807
808 /* We only detete the rule if this was the last tether removed. */
809 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
810 return res;
811}
812
JP Abgrall8a932722011-07-13 19:17:35 -0700813int BandwidthController::setSharedAlert(int64_t bytes) {
814 if (!sharedQuotaBytes) {
815 LOGE("Need to have a prior shared quota set to set an alert");
816 return -1;
817 }
818 if (!bytes) {
819 LOGE("Invalid bytes value. 1..max_int64.");
820 return -1;
821 }
822 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
823}
824
825int BandwidthController::removeSharedAlert(void) {
826 return removeCostlyAlert("shared", &sharedAlertBytes);
827}
828
829int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
830 std::list<QuotaInfo>::iterator it;
831
832 if (!bytes) {
833 LOGE("Invalid bytes value. 1..max_int64.");
834 return -1;
835 }
836 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
837 if (it->ifaceName == iface)
838 break;
839 }
840
841 if (it == quotaIfaces.end()) {
842 LOGE("Need to have a prior interface quota set to set an alert");
843 return -1;
844 }
845
846 return setCostlyAlert(iface, bytes, &it->alert);
847}
848
849int BandwidthController::removeInterfaceAlert(const char *iface) {
850 std::list<QuotaInfo>::iterator it;
851
852 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
853 if (it->ifaceName == iface)
854 break;
855 }
856
857 if (it == quotaIfaces.end()) {
858 LOGE("No prior alert set for interface %s", iface);
859 return -1;
860 }
861
862 return removeCostlyAlert(iface, &it->alert);
863}
864
865int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
866 char *alertQuotaCmd;
867 char *chainNameAndPos;
868 int res = 0;
869 char *alertName;
870
871 if (!bytes) {
872 LOGE("Invalid bytes value. 1..max_int64.");
873 return -1;
874 }
875 asprintf(&alertName, "%sAlert", costName);
876 if (*alertBytes) {
877 res = updateQuota(alertName, *alertBytes);
878 } else {
879 asprintf(&chainNameAndPos, "costly_%s %d", costName, ALERT_RULE_POS_IN_COSTLY_CHAIN);
880 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-I", chainNameAndPos, bytes, alertName,
881 alertName);
882 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
883 free(alertQuotaCmd);
884 free(chainNameAndPos);
885 }
886 *alertBytes = bytes;
887 free(alertName);
888 return res;
889}
890
891int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
892 char *alertQuotaCmd;
893 char *chainName;
894 char *alertName;
895 int res = 0;
896
897 asprintf(&alertName, "%sAlert", costName);
898 if (!*alertBytes) {
899 LOGE("No prior alert set for %s alert", costName);
900 return -1;
901 }
902
903 asprintf(&chainName, "costly_%s", costName);
904 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName, alertName);
905 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
906 free(alertQuotaCmd);
907 free(chainName);
908
909 *alertBytes = 0;
910 free(alertName);
911 return res;
912}
JP Abgralldb7da582011-09-18 12:57:32 -0700913
914/*
915 * Parse the ptks and bytes out of:
916 * Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
917 * pkts bytes target prot opt in out source destination
918 * 0 0 ACCEPT all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
919 * 0 0 DROP all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0 state INVALID
920 * 0 0 ACCEPT all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
921 *
922 */
923int BandwidthController::parseForwardChainStats(TetherStats &stats, FILE *fp) {
924 int res;
925 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
926 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
927 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
928 char rest[MAX_IPT_OUTPUT_LINE_LEN];
929
930 char *buffPtr;
931 int64_t packets, bytes;
932
933 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
934 /* Clean up, so a failed parse can still print info */
935 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
936 res = sscanf(buffPtr, "%lld %lld ACCEPT all -- %s %s 0.%s",
937 &packets, &bytes, iface0, iface1, rest);
938 LOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%lld bytes=%lld rest=<%s> orig line=<%s>", res,
939 iface0, iface1, packets, bytes, rest, buffPtr);
940 if (res != 5) {
941 continue;
942 }
943 if ((stats.ifaceIn == iface0) && (stats.ifaceOut == iface1)) {
944 LOGV("iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
945 stats.rxPackets = packets;
946 stats.rxBytes = bytes;
947 } else if ((stats.ifaceOut == iface0) && (stats.ifaceIn == iface1)) {
948 LOGV("iface_in=%s iface_out=%s tx_bytes=%lld tx_packets=%lld ", iface1, iface0, bytes, packets);
949 stats.txPackets = packets;
950 stats.txBytes = bytes;
951 }
952 }
953 /* Failure if rx or tx was not found */
954 return (stats.rxBytes == -1 || stats.txBytes == -1) ? -1 : 0;
955}
956
957
958char *BandwidthController::TetherStats::getStatsLine(void) {
959 char *msg;
960 asprintf(&msg, "%s %s %lld %lld %lld %lld", ifaceIn.c_str(), ifaceOut.c_str(),
961 rxBytes, rxPackets, txBytes, txPackets);
962 return msg;
963}
964
965int BandwidthController::getTetherStats(TetherStats &stats) {
966 int res;
967 std::string fullCmd;
968 FILE *iptOutput;
969 const char *cmd;
970
971 if (stats.rxBytes != -1 || stats.txBytes != -1) {
972 LOGE("Unexpected input stats. Byte counts should be -1.");
973 return -1;
974 }
975
976 /*
977 * Why not use some kind of lib to talk to iptables?
978 * Because the only libs are libiptc and libip6tc in iptables, and they are
979 * not easy to use. They require the known iptables match modules to be
980 * preloaded/linked, and require apparently a lot of wrapper code to get
981 * the wanted info.
982 */
983 fullCmd = IPTABLES_PATH;
984 fullCmd += " -nvx -L FORWARD";
985 iptOutput = popen(fullCmd.c_str(), "r");
986 if (!iptOutput) {
987 LOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
988 return -1;
989 }
990 res = parseForwardChainStats(stats, iptOutput);
991 pclose(iptOutput);
992
993 /* Currently NatController doesn't do ipv6 tethering, so we are done. */
994 return res;
995}