blob: 277f3209a5eccc8007215550bb314fc01b14a86f [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 Abgrallbaeccc42013-06-25 09:44:10 -070017#define LOG_NDEBUG 0
JP Abgralldb7da582011-09-18 12:57:32 -070018
19/*
20 * The CommandListener, FrameworkListener don't allow for
21 * multiple calls in parallel to reach the BandwidthController.
22 * If they ever were to allow it, then netd/ would need some tweaking.
23 */
24
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>
Rom Lemarchand14150212013-01-24 10:01:04 -080043#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070044
JP Abgrall0031cea2012-04-17 16:38:23 -070045#include "NetdConstants.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070046#include "BandwidthController.h"
JP Abgrallbaeccc42013-06-25 09:44:10 -070047#include "NatController.h" /* For LOCAL_TETHER_COUNTERS_CHAIN */
48#include "ResponseCode.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049
JP Abgralldb7da582011-09-18 12:57:32 -070050/* Alphabetical */
JP Abgrall92009c82013-02-06 18:01:24 -080051#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %lld --name %s"
JP Abgrallc6c67342011-10-07 16:28:54 -070052const char BandwidthController::ALERT_GLOBAL_NAME[] = "globalAlert";
Jeff Sharkey8e188ed2012-07-12 18:32:03 -070053const char* BandwidthController::LOCAL_INPUT = "bw_INPUT";
54const char* BandwidthController::LOCAL_FORWARD = "bw_FORWARD";
55const char* BandwidthController::LOCAL_OUTPUT = "bw_OUTPUT";
56const char* BandwidthController::LOCAL_RAW_PREROUTING = "bw_raw_PREROUTING";
57const char* BandwidthController::LOCAL_MANGLE_POSTROUTING = "bw_mangle_POSTROUTING";
JP Abgralldb7da582011-09-18 12:57:32 -070058const int BandwidthController::MAX_CMD_ARGS = 32;
59const int BandwidthController::MAX_CMD_LEN = 1024;
60const int BandwidthController::MAX_IFACENAME_LEN = 64;
61const int BandwidthController::MAX_IPT_OUTPUT_LINE_LEN = 256;
62
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070063/**
64 * Some comments about the rules:
65 * * Ordering
66 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070067 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070068 * - quota'd rules in the costly chain should be before penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070069 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070070 *
71 * * global quota vs per interface quota
72 * - global quota for all costly interfaces uses a single costly chain:
73 * . initial rules
JP Abgrallbfa74662011-06-29 19:23:04 -070074 * iptables -N costly_shared
JP Abgrall29e8de22012-05-03 12:52:15 -070075 * iptables -I bw_INPUT -i iface0 --jump costly_shared
76 * iptables -I bw_OUTPUT -o iface0 --jump costly_shared
JP Abgrallbfa74662011-06-29 19:23:04 -070077 * iptables -I costly_shared -m quota \! --quota 500000 \
78 * --jump REJECT --reject-with icmp-net-prohibited
79 * iptables -A costly_shared --jump penalty_box
JP Abgrall8a932722011-07-13 19:17:35 -070080 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070081 * . adding a new iface to this, E.g.:
JP Abgrall29e8de22012-05-03 12:52:15 -070082 * iptables -I bw_INPUT -i iface1 --jump costly_shared
83 * iptables -I bw_OUTPUT -o iface1 --jump costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070084 *
85 * - quota per interface. This is achieve by having "costly" chains per quota.
86 * E.g. adding a new costly interface iface0 with its own quota:
87 * iptables -N costly_iface0
JP Abgrall29e8de22012-05-03 12:52:15 -070088 * iptables -I bw_INPUT -i iface0 --jump costly_iface0
89 * iptables -I bw_OUTPUT -o iface0 --jump costly_iface0
JP Abgrallbfa74662011-06-29 19:23:04 -070090 * iptables -A costly_iface0 -m quota \! --quota 500000 \
91 * --jump REJECT --reject-with icmp-net-prohibited
92 * iptables -A costly_iface0 --jump penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070093 *
94 * * penalty_box handling:
95 * - only one penalty_box for all interfaces
96 * E.g Adding an app:
JP Abgrallbfa74662011-06-29 19:23:04 -070097 * iptables -A penalty_box -m owner --uid-owner app_3 \
98 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070099 */
JP Abgrall0031cea2012-04-17 16:38:23 -0700100const char *BandwidthController::IPT_FLUSH_COMMANDS[] = {
101 /*
102 * Cleanup rules.
103 * Should normally include costly_<iface>, but we rely on the way they are setup
104 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700105 */
JP Abgrall0031cea2012-04-17 16:38:23 -0700106 "-F bw_INPUT",
107 "-F bw_OUTPUT",
108 "-F bw_FORWARD",
109 "-F penalty_box",
110 "-F costly_shared",
JP Abgrallf66d6e92012-04-27 00:22:57 -0700111
112 "-t raw -F bw_raw_PREROUTING",
113 "-t mangle -F bw_mangle_POSTROUTING",
JP Abgrall0031cea2012-04-17 16:38:23 -0700114};
115
116/* The cleanup commands assume flushing has been done. */
117const char *BandwidthController::IPT_CLEANUP_COMMANDS[] = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700118 "-X penalty_box",
119 "-X costly_shared",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700120};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700121
JP Abgralldb7da582011-09-18 12:57:32 -0700122const char *BandwidthController::IPT_SETUP_COMMANDS[] = {
JP Abgrallbfa74662011-06-29 19:23:04 -0700123 "-N costly_shared",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700124 "-N penalty_box",
125};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700126
JP Abgralldb7da582011-09-18 12:57:32 -0700127const char *BandwidthController::IPT_BASIC_ACCOUNTING_COMMANDS[] = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700128 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700129
JP Abgrall0031cea2012-04-17 16:38:23 -0700130 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700131
JP Abgrallbfa74662011-06-29 19:23:04 -0700132 "-A costly_shared --jump penalty_box",
JP Abgrallf66d6e92012-04-27 00:22:57 -0700133
JP Abgrall92009c82013-02-06 18:01:24 -0800134 "-t raw -A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
135 "-t mangle -A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700136};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700137
138BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700139}
140
JP Abgrallad729ac2012-04-24 23:27:44 -0700141int BandwidthController::runIpxtablesCmd(const char *cmd, IptRejectOp rejectHandling,
142 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700143 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700144
Steve Block3fb42e02011-10-20 11:55:56 +0100145 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgrallad729ac2012-04-24 23:27:44 -0700146 res |= runIptablesCmd(cmd, rejectHandling, IptIpV4, failureHandling);
147 res |= runIptablesCmd(cmd, rejectHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700148 return res;
149}
150
JP Abgrall26e0d492011-06-24 19:21:51 -0700151int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
152
153 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
154 strncpy(buffer, src, buffSize);
155 return buffer[buffSize - 1];
156}
157
JP Abgrall8a932722011-07-13 19:17:35 -0700158int BandwidthController::runIptablesCmd(const char *cmd, IptRejectOp rejectHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700159 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700160 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700161 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700162 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700163 char *next = buffer;
164 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700165 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800166 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700167
JP Abgrall0dad7c22011-06-24 11:58:14 -0700168 std::string fullCmd = cmd;
JP Abgrall26e0d492011-06-24 19:21:51 -0700169
170 if (rejectHandling == IptRejectAdd) {
JP Abgrall340d5cc2013-06-28 17:06:00 -0700171 /*
172 * Must be carefull what one rejects with, as uper layer protocols will just
173 * keep on hammering the device until the number of retries are done.
174 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
175 */
176 fullCmd += " --jump REJECT";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700177 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700178
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700179 fullCmd.insert(0, " ");
180 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700181
Rom Lemarchand14150212013-01-24 10:01:04 -0800182 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
183 ALOGE("iptables command too long");
184 return -1;
185 }
186
187 argc = 0;
188 while ((tmp = strsep(&next, " "))) {
189 argv[argc++] = tmp;
190 if (argc >= MAX_CMD_ARGS) {
191 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700192 return -1;
193 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700194 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800195
196 argv[argc] = NULL;
197 res = android_fork_execvp(argc, (char **)argv, &status, false,
198 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800199 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
200 if (res && failureHandling == IptFailShow) {
201 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
202 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700203 }
204 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700205}
206
JP Abgrall0031cea2012-04-17 16:38:23 -0700207int BandwidthController::setupIptablesHooks(void) {
208
209 /* Some of the initialCommands are allowed to fail */
210 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
211 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
212
213 runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
214 IPT_CLEANUP_COMMANDS, RunCmdFailureOk);
215
216 runCommands(sizeof(IPT_SETUP_COMMANDS) / sizeof(char*),
217 IPT_SETUP_COMMANDS, RunCmdFailureBad);
218
219 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700220}
221
222int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700223 int res;
JP Abgrall0031cea2012-04-17 16:38:23 -0700224 char value[PROPERTY_VALUE_MAX];
225
226 if (!force) {
227 property_get("persist.bandwidth.enable", value, "1");
228 if (!strcmp(value, "0"))
229 return 0;
230 }
JP Abgrall8a932722011-07-13 19:17:35 -0700231
JP Abgralldb7da582011-09-18 12:57:32 -0700232 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700233 sharedQuotaIfaces.clear();
234 quotaIfaces.clear();
235 naughtyAppUids.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700236 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700237 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700238 sharedQuotaBytes = sharedAlertBytes = 0;
239
JP Abgrall0031cea2012-04-17 16:38:23 -0700240 res = runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
241 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
JP Abgralldb7da582011-09-18 12:57:32 -0700242
JP Abgrall0031cea2012-04-17 16:38:23 -0700243 res |= runCommands(sizeof(IPT_BASIC_ACCOUNTING_COMMANDS) / sizeof(char*),
JP Abgralldb7da582011-09-18 12:57:32 -0700244 IPT_BASIC_ACCOUNTING_COMMANDS, RunCmdFailureBad);
JP Abgrall8a932722011-07-13 19:17:35 -0700245
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700246 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700247
248}
249
250int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700251 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
252 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700253 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700254}
255
JP Abgrall8a932722011-07-13 19:17:35 -0700256int BandwidthController::runCommands(int numCommands, const char *commands[],
257 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700258 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700259 IptFailureLog failureLogging = IptFailShow;
260 if (cmdErrHandling == RunCmdFailureOk) {
261 failureLogging = IptFailHide;
262 }
Steve Block3fb42e02011-10-20 11:55:56 +0100263 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700264 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgrallad729ac2012-04-24 23:27:44 -0700265 res = runIpxtablesCmd(commands[cmdNum], IptRejectNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700266 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700267 return res;
268 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700269 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700270}
271
JP Abgrall0dad7c22011-06-24 11:58:14 -0700272std::string BandwidthController::makeIptablesNaughtyCmd(IptOp op, int uid) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700273 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700274 char *buff;
275 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700276
277 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700278 case IptOpInsert:
279 opFlag = "-I";
280 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800281 case IptOpAppend:
282 opFlag = "-A";
283 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700284 case IptOpReplace:
285 opFlag = "-R";
286 break;
287 default:
288 case IptOpDelete:
289 opFlag = "-D";
290 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700291 }
JP Abgrall8a932722011-07-13 19:17:35 -0700292 asprintf(&buff, "%s penalty_box -m owner --uid-owner %d", opFlag, uid);
293 res = buff;
294 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700295 return res;
296}
297
298int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700299 return maninpulateNaughtyApps(numUids, appUids, NaughtyAppOpAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700300}
301
302int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700303 return maninpulateNaughtyApps(numUids, appUids, NaughtyAppOpRemove);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700304}
305
JP Abgrall26e0d492011-06-24 19:21:51 -0700306int BandwidthController::maninpulateNaughtyApps(int numUids, char *appStrUids[], NaughtyAppOp appOp) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700307 char cmd[MAX_CMD_LEN];
308 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700309 const char *failLogTemplate;
310 IptOp op;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700311 int appUids[numUids];
JP Abgrall26e0d492011-06-24 19:21:51 -0700312 std::string naughtyCmd;
JP Abgrallb1d24092012-04-27 01:02:31 -0700313 std::list<int /*uid*/>::iterator it;
JP Abgrall8a932722011-07-13 19:17:35 -0700314
JP Abgrall26e0d492011-06-24 19:21:51 -0700315 switch (appOp) {
316 case NaughtyAppOpAdd:
JP Abgrall8a932722011-07-13 19:17:35 -0700317 op = IptOpInsert;
318 failLogTemplate = "Failed to add app uid %d to penalty box.";
319 break;
JP Abgrall26e0d492011-06-24 19:21:51 -0700320 case NaughtyAppOpRemove:
JP Abgrall8a932722011-07-13 19:17:35 -0700321 op = IptOpDelete;
322 failLogTemplate = "Failed to delete app uid %d from penalty box.";
323 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700324 default:
325 ALOGE("Unexpected app Op %d", appOp);
326 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700327 }
328
329 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700330 appUids[uidNum] = atol(appStrUids[uidNum]);
331 if (appUids[uidNum] == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000332 ALOGE(failLogTemplate, appUids[uidNum]);
JP Abgrall26e0d492011-06-24 19:21:51 -0700333 goto fail_parse;
334 }
335 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700336
337 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700338 int uid = appUids[uidNum];
339 for (it = naughtyAppUids.begin(); it != naughtyAppUids.end(); it++) {
340 if (*it == uid)
341 break;
342 }
343 bool found = (it != naughtyAppUids.end());
344
345 if (appOp == NaughtyAppOpRemove) {
346 if (!found) {
347 ALOGE("No such appUid %d to remove", uid);
348 return -1;
349 }
350 naughtyAppUids.erase(it);
351 } else {
352 if (found) {
353 ALOGE("appUid %d exists already", uid);
354 return -1;
355 }
356 naughtyAppUids.push_front(uid);
357 }
358
359 naughtyCmd = makeIptablesNaughtyCmd(op, uid);
JP Abgrall26e0d492011-06-24 19:21:51 -0700360 if (runIpxtablesCmd(naughtyCmd.c_str(), IptRejectAdd)) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700361 ALOGE(failLogTemplate, uid);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700362 goto fail_with_uidNum;
363 }
364 }
365 return 0;
366
JP Abgrall26e0d492011-06-24 19:21:51 -0700367fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700368 /* Try to remove the uid that failed in any case*/
JP Abgrall26e0d492011-06-24 19:21:51 -0700369 naughtyCmd = makeIptablesNaughtyCmd(IptOpDelete, appUids[uidNum]);
370 runIpxtablesCmd(naughtyCmd.c_str(), IptRejectAdd);
371fail_parse:
372 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700373}
374
JP Abgrall26e0d492011-06-24 19:21:51 -0700375std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700376 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700377 char *buff;
378 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700379
Steve Block3fb42e02011-10-20 11:55:56 +0100380 ALOGV("makeIptablesQuotaCmd(%d, %lld)", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700381
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700382 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700383 case IptOpInsert:
384 opFlag = "-I";
385 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800386 case IptOpAppend:
387 opFlag = "-A";
388 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700389 case IptOpReplace:
390 opFlag = "-R";
391 break;
392 default:
393 case IptOpDelete:
394 opFlag = "-D";
395 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700396 }
JP Abgrall8a932722011-07-13 19:17:35 -0700397
JP Abgrallbfa74662011-06-29 19:23:04 -0700398 // The requried IP version specific --jump REJECT ... will be added later.
JP Abgrall8a932722011-07-13 19:17:35 -0700399 asprintf(&buff, "%s costly_%s -m quota2 ! --quota %lld --name %s", opFlag, costName, quota,
400 costName);
401 res = buff;
402 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700403 return res;
404}
405
JP Abgrall26e0d492011-06-24 19:21:51 -0700406int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700407 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700408 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700409 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700410 std::string costString;
411 const char *costCString;
412
JP Abgrall0dad7c22011-06-24 11:58:14 -0700413 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700414 switch (quotaType) {
415 case QuotaUnique:
JP Abgrallbfa74662011-06-29 19:23:04 -0700416 costString = "costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700417 costString += ifn;
418 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700419 /*
420 * Flush the costly_<iface> is allowed to fail in case it didn't exist.
421 * Creating a new one is allowed to fail in case it existed.
422 * This helps with netd restarts.
423 */
424 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgrallad729ac2012-04-24 23:27:44 -0700425 res1 = runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700426 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgrallad729ac2012-04-24 23:27:44 -0700427 res2 = runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700428 res = (res1 && res2) || (!res1 && !res2);
429
JP Abgrall0dad7c22011-06-24 11:58:14 -0700430 snprintf(cmd, sizeof(cmd), "-A %s -j penalty_box", costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700431 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700432 break;
433 case QuotaShared:
JP Abgrallbfa74662011-06-29 19:23:04 -0700434 costCString = "costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700435 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700436 default:
437 ALOGE("Unexpected quotatype %d", quotaType);
438 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700439 }
440
JP Abgrall8a932722011-07-13 19:17:35 -0700441 if (globalAlertBytes) {
442 /* The alert rule comes 1st */
443 ruleInsertPos = 2;
444 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700445
446 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgrallad729ac2012-04-24 23:27:44 -0700447 runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700448
449 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700450 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700451
452 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgrallad729ac2012-04-24 23:27:44 -0700453 runIpxtablesCmd(cmd, IptRejectNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700454
455 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700456 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700457 return res;
458}
459
JP Abgrall26e0d492011-06-24 19:21:51 -0700460int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700461 char cmd[MAX_CMD_LEN];
462 int res = 0;
463 std::string costString;
464 const char *costCString;
465
JP Abgrall26e0d492011-06-24 19:21:51 -0700466 switch (quotaType) {
467 case QuotaUnique:
JP Abgrallbfa74662011-06-29 19:23:04 -0700468 costString = "costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700469 costString += ifn;
470 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700471 break;
472 case QuotaShared:
JP Abgrallbfa74662011-06-29 19:23:04 -0700473 costCString = "costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700474 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700475 default:
476 ALOGE("Unexpected quotatype %d", quotaType);
477 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700478 }
479
JP Abgrall0031cea2012-04-17 16:38:23 -0700480 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700481 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700482 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700483 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700484
JP Abgrallbfa74662011-06-29 19:23:04 -0700485 /* The "-N costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700486 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700487 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgrall26e0d492011-06-24 19:21:51 -0700488 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700489 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
490 res |= runIpxtablesCmd(cmd, IptRejectNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700491 }
492 return res;
493}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700494
JP Abgrall0dad7c22011-06-24 11:58:14 -0700495int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700496 char cmd[MAX_CMD_LEN];
497 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700498 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700499 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700500 std::string ifaceName;
501 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700502 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700503 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700504
JP Abgrall8a932722011-07-13 19:17:35 -0700505 if (!maxBytes) {
506 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000507 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700508 return -1;
509 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700510 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000511 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700512 return -1;
513 }
514 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700515
516 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700517 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700518 }
519
520 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700521 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
522 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700523 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700524 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700525
JP Abgrall0dad7c22011-06-24 11:58:14 -0700526 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700527 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700528 if (sharedQuotaIfaces.empty()) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700529 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgrall26e0d492011-06-24 19:21:51 -0700530 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700531 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000532 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700533 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700534 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700535 sharedQuotaBytes = maxBytes;
536 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700537 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700538
539 }
540
541 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700542 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700543 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000544 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700545 goto fail;
546 }
547 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700548 }
549 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700550
551 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700552 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700553 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
554 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700555 * For now callers needs to choose if they want to "ndc bandwidth enable"
556 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700557 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700558 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700559 return -1;
560}
561
JP Abgrall8a932722011-07-13 19:17:35 -0700562/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700563int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700564 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700565 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700566 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700567 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700568 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700569
JP Abgrall8a932722011-07-13 19:17:35 -0700570 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000571 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700572 return -1;
573 }
JP Abgrall8a932722011-07-13 19:17:35 -0700574 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700575
JP Abgrall0dad7c22011-06-24 11:58:14 -0700576 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
577 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700578 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700579 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700580 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000581 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700582 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700583 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700584
JP Abgrall26e0d492011-06-24 19:21:51 -0700585 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700586 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700587
JP Abgrall0dad7c22011-06-24 11:58:14 -0700588 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700589 std::string quotaCmd;
JP Abgrallbfa74662011-06-29 19:23:04 -0700590 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
JP Abgrall26e0d492011-06-24 19:21:51 -0700591 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700592 sharedQuotaBytes = 0;
593 if (sharedAlertBytes) {
594 removeSharedAlert();
595 sharedAlertBytes = 0;
596 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700597 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700598 return res;
599}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700600
601int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
602 char ifn[MAX_IFACENAME_LEN];
603 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700604 std::string ifaceName;
605 const char *costName;
606 std::list<QuotaInfo>::iterator it;
607 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700608
JP Abgrall8a932722011-07-13 19:17:35 -0700609 if (!maxBytes) {
610 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000611 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700612 return -1;
613 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700614 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700615 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700616 }
617
JP Abgrall8a932722011-07-13 19:17:35 -0700618 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000619 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700620 return -1;
621 }
622 ifaceName = ifn;
623 costName = iface;
624
JP Abgrall0dad7c22011-06-24 11:58:14 -0700625 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700626 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700627 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700628 break;
629 }
630
631 if (it == quotaIfaces.end()) {
JP Abgrall109899b2013-02-12 19:20:13 -0800632 /* Preparing the iface adds a penalty_box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700633 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700634 /*
635 * The rejecting quota limit should go after the penalty box checks
636 * or else a naughty app could just eat up the quota.
637 * So we append here.
638 */
JP Abgrall109899b2013-02-12 19:20:13 -0800639 quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
JP Abgrall26e0d492011-06-24 19:21:51 -0700640 res |= runIpxtablesCmd(quotaCmd.c_str(), IptRejectAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700641 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000642 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700643 goto fail;
644 }
645
JP Abgrall8a932722011-07-13 19:17:35 -0700646 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700647
648 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700649 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700650 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000651 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700652 goto fail;
653 }
JP Abgrall8a932722011-07-13 19:17:35 -0700654 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700655 }
656 return 0;
657
658 fail:
659 /*
660 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
661 * rules in the kernel to see which ones need cleaning up.
662 * For now callers needs to choose if they want to "ndc bandwidth enable"
663 * which resets everything.
664 */
665 removeInterfaceSharedQuota(ifn);
666 return -1;
667}
668
JP Abgrall8a932722011-07-13 19:17:35 -0700669int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
670 return getInterfaceQuota("shared", bytes);
671}
672
673int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
674 FILE *fp;
675 char *fname;
676 int scanRes;
677
678 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
679 fp = fopen(fname, "r");
680 free(fname);
681 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000682 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700683 return -1;
684 }
685 scanRes = fscanf(fp, "%lld", bytes);
Steve Block3fb42e02011-10-20 11:55:56 +0100686 ALOGV("Read quota res=%d bytes=%lld", scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700687 fclose(fp);
688 return scanRes == 1 ? 0 : -1;
689}
690
JP Abgrall0dad7c22011-06-24 11:58:14 -0700691int BandwidthController::removeInterfaceQuota(const char *iface) {
692
693 char ifn[MAX_IFACENAME_LEN];
694 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700695 std::string ifaceName;
696 const char *costName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700697 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700698
JP Abgrall8a932722011-07-13 19:17:35 -0700699 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000700 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700701 return -1;
702 }
703 ifaceName = ifn;
704 costName = iface;
705
JP Abgrall0dad7c22011-06-24 11:58:14 -0700706 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700707 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700708 break;
709 }
710
711 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000712 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700713 return -1;
714 }
715
716 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700717 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700718
719 quotaIfaces.erase(it);
720
721 return res;
722}
JP Abgrall8a932722011-07-13 19:17:35 -0700723
724int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
725 FILE *fp;
726 char *fname;
727
728 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
729 fp = fopen(fname, "w");
730 free(fname);
731 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000732 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700733 return -1;
734 }
735 fprintf(fp, "%lld\n", bytes);
736 fclose(fp);
737 return 0;
738}
739
740int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
741 int res = 0;
742 const char *opFlag;
743 char *alertQuotaCmd;
744
745 switch (op) {
746 case IptOpInsert:
747 opFlag = "-I";
748 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800749 case IptOpAppend:
750 opFlag = "-A";
751 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700752 case IptOpReplace:
753 opFlag = "-R";
754 break;
755 default:
756 case IptOpDelete:
757 opFlag = "-D";
758 break;
759 }
760
JP Abgrall92009c82013-02-06 18:01:24 -0800761 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800762 bytes, alertName);
JP Abgrall8a932722011-07-13 19:17:35 -0700763 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
764 free(alertQuotaCmd);
JP Abgrall92009c82013-02-06 18:01:24 -0800765 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800766 bytes, alertName);
JP Abgrall8a932722011-07-13 19:17:35 -0700767 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
768 free(alertQuotaCmd);
769 return res;
770}
771
JP Abgrallc6c67342011-10-07 16:28:54 -0700772int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
773 int res = 0;
774 const char *opFlag;
JP Abgrall8a932722011-07-13 19:17:35 -0700775 char *alertQuotaCmd;
JP Abgrallc6c67342011-10-07 16:28:54 -0700776
777 switch (op) {
778 case IptOpInsert:
779 opFlag = "-I";
780 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800781 case IptOpAppend:
782 opFlag = "-A";
783 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700784 case IptOpReplace:
785 opFlag = "-R";
786 break;
787 default:
788 case IptOpDelete:
789 opFlag = "-D";
790 break;
791 }
792
JP Abgrall92009c82013-02-06 18:01:24 -0800793 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800794 bytes, alertName);
JP Abgrallc6c67342011-10-07 16:28:54 -0700795 res = runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
796 free(alertQuotaCmd);
797 return res;
798}
799
800int BandwidthController::setGlobalAlert(int64_t bytes) {
801 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700802 int res = 0;
803
804 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000805 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700806 return -1;
807 }
808 if (globalAlertBytes) {
809 res = updateQuota(alertName, bytes);
810 } else {
811 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700812 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100813 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700814 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
815 }
JP Abgrall8a932722011-07-13 19:17:35 -0700816 }
817 globalAlertBytes = bytes;
818 return res;
819}
820
JP Abgrallc6c67342011-10-07 16:28:54 -0700821int BandwidthController::setGlobalAlertInForwardChain(void) {
822 const char *alertName = ALERT_GLOBAL_NAME;
823 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700824
JP Abgrallc6c67342011-10-07 16:28:54 -0700825 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100826 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700827
828 /*
829 * If there is no globalAlert active we are done.
830 * If there is an active globalAlert but this is not the 1st
831 * tether, we are also done.
832 */
833 if (!globalAlertBytes || globalAlertTetherCount != 1) {
834 return 0;
835 }
836
837 /* We only add the rule if this was the 1st tether added. */
838 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
839 return res;
840}
841
842int BandwidthController::removeGlobalAlert(void) {
843
844 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700845 int res = 0;
846
847 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000848 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700849 return -1;
850 }
851 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700852 if (globalAlertTetherCount) {
853 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
854 }
JP Abgrall8a932722011-07-13 19:17:35 -0700855 globalAlertBytes = 0;
856 return res;
857}
858
JP Abgrallc6c67342011-10-07 16:28:54 -0700859int BandwidthController::removeGlobalAlertInForwardChain(void) {
860 int res = 0;
861 const char *alertName = ALERT_GLOBAL_NAME;
862
863 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000864 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700865 return -1;
866 }
867
868 globalAlertTetherCount--;
869 /*
870 * If there is no globalAlert active we are done.
871 * If there is an active globalAlert but there are more
872 * tethers, we are also done.
873 */
874 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
875 return 0;
876 }
877
878 /* We only detete the rule if this was the last tether removed. */
879 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
880 return res;
881}
882
JP Abgrall8a932722011-07-13 19:17:35 -0700883int BandwidthController::setSharedAlert(int64_t bytes) {
884 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000885 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700886 return -1;
887 }
888 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000889 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700890 return -1;
891 }
892 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
893}
894
895int BandwidthController::removeSharedAlert(void) {
896 return removeCostlyAlert("shared", &sharedAlertBytes);
897}
898
899int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
900 std::list<QuotaInfo>::iterator it;
901
902 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000903 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700904 return -1;
905 }
906 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
907 if (it->ifaceName == iface)
908 break;
909 }
910
911 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000912 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700913 return -1;
914 }
915
916 return setCostlyAlert(iface, bytes, &it->alert);
917}
918
919int BandwidthController::removeInterfaceAlert(const char *iface) {
920 std::list<QuotaInfo>::iterator it;
921
922 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
923 if (it->ifaceName == iface)
924 break;
925 }
926
927 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000928 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700929 return -1;
930 }
931
932 return removeCostlyAlert(iface, &it->alert);
933}
934
935int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
936 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -0800937 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -0700938 int res = 0;
939 char *alertName;
940
941 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000942 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700943 return -1;
944 }
945 asprintf(&alertName, "%sAlert", costName);
946 if (*alertBytes) {
947 res = updateQuota(alertName, *alertBytes);
948 } else {
JP Abgrall109899b2013-02-12 19:20:13 -0800949 asprintf(&chainName, "costly_%s", costName);
950 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgrall8a932722011-07-13 19:17:35 -0700951 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
952 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -0800953 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -0700954 }
955 *alertBytes = bytes;
956 free(alertName);
957 return res;
958}
959
960int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
961 char *alertQuotaCmd;
962 char *chainName;
963 char *alertName;
964 int res = 0;
965
966 asprintf(&alertName, "%sAlert", costName);
967 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000968 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -0700969 return -1;
970 }
971
972 asprintf(&chainName, "costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -0800973 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgrall8a932722011-07-13 19:17:35 -0700974 res |= runIpxtablesCmd(alertQuotaCmd, IptRejectNoAdd);
975 free(alertQuotaCmd);
976 free(chainName);
977
978 *alertBytes = 0;
979 free(alertName);
980 return res;
981}
JP Abgralldb7da582011-09-18 12:57:32 -0700982
983/*
984 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -0700985 * Chain natctrl_tether_counters (4 references)
986 * pkts bytes target prot opt in out source destination
987 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0 counter wlan0_rmnet0: 0 bytes
988 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0 counter rmnet0_wlan0: 0 bytes
989 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0 counter bt-pan_rmnet0: 0 bytes
990 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0 counter rmnet0_bt-pan: 0 bytes
JP Abgralldb7da582011-09-18 12:57:32 -0700991 */
JP Abgrallbaeccc42013-06-25 09:44:10 -0700992int BandwidthController::parseForwardChainStats(SocketClient *cli, const TetherStats filter,
993 FILE *fp, std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -0700994 int res;
995 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
996 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
997 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
998 char rest[MAX_IPT_OUTPUT_LINE_LEN];
999
JP Abgrallbaeccc42013-06-25 09:44:10 -07001000 TetherStats stats;
JP Abgralldb7da582011-09-18 12:57:32 -07001001 char *buffPtr;
1002 int64_t packets, bytes;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001003 int statsFound = 0;
1004
1005 bool filterPair = filter.intIface[0] && filter.extIface[0];
1006
1007 char *filterMsg = filter.getStatsLine();
1008 ALOGV("filter: %s", filterMsg);
1009 free(filterMsg);
1010
1011 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001012
1013 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
1014 /* Clean up, so a failed parse can still print info */
1015 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
JP Abgrall0031cea2012-04-17 16:38:23 -07001016 res = sscanf(buffPtr, "%lld %lld RETURN all -- %s %s 0.%s",
JP Abgralldb7da582011-09-18 12:57:32 -07001017 &packets, &bytes, iface0, iface1, rest);
Steve Block3fb42e02011-10-20 11:55:56 +01001018 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%lld bytes=%lld rest=<%s> orig line=<%s>", res,
JP Abgralldb7da582011-09-18 12:57:32 -07001019 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001020 extraProcessingInfo += buffPtr;
1021
JP Abgralldb7da582011-09-18 12:57:32 -07001022 if (res != 5) {
1023 continue;
1024 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001025 /*
1026 * The following assumes that the 1st rule has in:extIface out:intIface,
1027 * which is what NatController sets up.
1028 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1029 */
1030 if (filter.intIface[0] && filter.extIface[0]) {
1031 if (filter.intIface == iface0 && filter.extIface == iface1) {
1032 ALOGV("2Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1033 stats.rxPackets = packets;
1034 stats.rxBytes = bytes;
1035 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
1036 ALOGV("2Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1037 stats.txPackets = packets;
1038 stats.txBytes = bytes;
1039 }
1040 } else if (filter.intIface[0] || filter.extIface[0]) {
1041 if (filter.intIface == iface0 || filter.extIface == iface1) {
1042 ALOGV("1Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1043 stats.intIface = iface0;
1044 stats.extIface = iface1;
1045 stats.rxPackets = packets;
1046 stats.rxBytes = bytes;
1047 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
1048 ALOGV("1Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1049 stats.intIface = iface1;
1050 stats.extIface = iface0;
1051 stats.txPackets = packets;
1052 stats.txBytes = bytes;
1053 }
1054 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1055 if (!stats.intIface[0]) {
1056 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1057 stats.intIface = iface0;
1058 stats.extIface = iface1;
1059 stats.rxPackets = packets;
1060 stats.rxBytes = bytes;
1061 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
1062 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
1063 stats.txPackets = packets;
1064 stats.txBytes = bytes;
1065 }
1066 }
1067 if (stats.rxBytes != -1 && stats.txBytes != -1) {
1068 ALOGV("rx_bytes=%lld tx_bytes=%lld filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
1069 /* Send out stats, and prep for the next if needed. */
1070 char *msg = stats.getStatsLine();
1071 if (filterPair) {
1072 cli->sendMsg(ResponseCode::TetheringStatsResult, msg, false);
1073 return 0;
1074 } else {
1075 cli->sendMsg(ResponseCode::TetheringStatsListResult, msg, false);
1076 stats = filter;
1077 }
1078 free(msg);
1079 statsFound++;
JP Abgralldb7da582011-09-18 12:57:32 -07001080 }
1081 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001082 /* We found some stats, and the last one isn't a partial stats. */
1083 if (statsFound && (stats.rxBytes == -1 || stats.txBytes == -1)) {
1084 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1085 return 0;
1086 }
1087 return -1;
JP Abgralldb7da582011-09-18 12:57:32 -07001088}
1089
JP Abgrallbaeccc42013-06-25 09:44:10 -07001090char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001091 char *msg;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001092 asprintf(&msg, "%s %s %lld %lld %lld %lld", intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001093 rxBytes, rxPackets, txBytes, txPackets);
1094 return msg;
1095}
1096
JP Abgrallbaeccc42013-06-25 09:44:10 -07001097int BandwidthController::getTetherStats(SocketClient *cli, TetherStats &stats, std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001098 int res;
1099 std::string fullCmd;
1100 FILE *iptOutput;
1101 const char *cmd;
1102
JP Abgralldb7da582011-09-18 12:57:32 -07001103 /*
1104 * Why not use some kind of lib to talk to iptables?
1105 * Because the only libs are libiptc and libip6tc in iptables, and they are
1106 * not easy to use. They require the known iptables match modules to be
1107 * preloaded/linked, and require apparently a lot of wrapper code to get
1108 * the wanted info.
1109 */
1110 fullCmd = IPTABLES_PATH;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001111 fullCmd += " -nvx -L ";
1112 fullCmd += NatController::LOCAL_TETHER_COUNTERS_CHAIN;
JP Abgralldb7da582011-09-18 12:57:32 -07001113 iptOutput = popen(fullCmd.c_str(), "r");
1114 if (!iptOutput) {
Steve Block5ea0c052012-01-06 19:18:11 +00001115 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
JP Abgralla2a64f02011-11-11 20:36:16 -08001116 extraProcessingInfo += "Failed to run iptables.";
JP Abgralldb7da582011-09-18 12:57:32 -07001117 return -1;
1118 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001119 res = parseForwardChainStats(cli, stats, iptOutput, extraProcessingInfo);
JP Abgralldb7da582011-09-18 12:57:32 -07001120 pclose(iptOutput);
1121
1122 /* Currently NatController doesn't do ipv6 tethering, so we are done. */
1123 return res;
1124}