blob: a7c2c2ca9783334dd668d97cfa3e6a9a7eb8ab99 [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 Abgralle4788732013-07-02 20:28:45 -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>
Nick Kralevich0b2b9022014-05-01 13:10:45 -070030#include <ctype.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070031
Matthew Leach2a54d962013-01-14 15:07:12 +000032#define __STDC_FORMAT_MACROS 1
33#include <inttypes.h>
34
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070035#include <sys/socket.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38#include <sys/wait.h>
39
40#include <linux/netlink.h>
41#include <linux/rtnetlink.h>
42#include <linux/pkt_sched.h>
43
44#define LOG_TAG "BandwidthController"
45#include <cutils/log.h>
46#include <cutils/properties.h>
Rom Lemarchand14150212013-01-24 10:01:04 -080047#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070048
JP Abgrall0031cea2012-04-17 16:38:23 -070049#include "NetdConstants.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070050#include "BandwidthController.h"
JP Abgrallbaeccc42013-06-25 09:44:10 -070051#include "NatController.h" /* For LOCAL_TETHER_COUNTERS_CHAIN */
52#include "ResponseCode.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070053
JP Abgralldb7da582011-09-18 12:57:32 -070054/* Alphabetical */
SynergyDev7776cea2014-03-16 15:48:51 -070055#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s"
JP Abgrallc6c67342011-10-07 16:28:54 -070056const char BandwidthController::ALERT_GLOBAL_NAME[] = "globalAlert";
Jeff Sharkey8e188ed2012-07-12 18:32:03 -070057const char* BandwidthController::LOCAL_INPUT = "bw_INPUT";
58const char* BandwidthController::LOCAL_FORWARD = "bw_FORWARD";
59const char* BandwidthController::LOCAL_OUTPUT = "bw_OUTPUT";
60const char* BandwidthController::LOCAL_RAW_PREROUTING = "bw_raw_PREROUTING";
61const char* BandwidthController::LOCAL_MANGLE_POSTROUTING = "bw_mangle_POSTROUTING";
JP Abgralldb7da582011-09-18 12:57:32 -070062const int BandwidthController::MAX_CMD_ARGS = 32;
63const int BandwidthController::MAX_CMD_LEN = 1024;
64const int BandwidthController::MAX_IFACENAME_LEN = 64;
65const int BandwidthController::MAX_IPT_OUTPUT_LINE_LEN = 256;
66
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070067/**
68 * Some comments about the rules:
69 * * Ordering
70 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070071 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070072 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
73 * - bw_happy_box rejects everything by default.
JP Abgrall29e8de22012-05-03 12:52:15 -070074 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070075 *
76 * * global quota vs per interface quota
77 * - global quota for all costly interfaces uses a single costly chain:
78 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070079 * iptables -N bw_costly_shared
80 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
81 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
82 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -070083 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -070084 * iptables -A bw_costly_shared --jump bw_penalty_box
JP Abgralle4788732013-07-02 20:28:45 -070085 * If the happy box is enabled,
JP Abgrall7e51cde2013-07-03 13:33:05 -070086 * iptables -A bw_penalty_box --jump bw_happy_box
JP Abgrall8a932722011-07-13 19:17:35 -070087 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070088 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -070089 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
90 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070091 *
92 * - quota per interface. This is achieve by having "costly" chains per quota.
93 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -070094 * iptables -N bw_costly_iface0
95 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
96 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
97 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -070098 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -070099 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700100 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700101 * * bw_penalty_box handling:
102 * - only one bw_penalty_box for all interfaces
103 * E.g Adding an app, it has to preserve the appened bw_happy_box, so "-I":
104 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700105 * --jump REJECT --reject-with icmp-port-unreachable
106 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700107 * * bw_happy_box handling:
108 * - The bw_happy_box goes at the end of the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700109 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700110 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700111 * --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700112 */
JP Abgrall0031cea2012-04-17 16:38:23 -0700113const char *BandwidthController::IPT_FLUSH_COMMANDS[] = {
114 /*
115 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700116 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700117 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700118 */
JP Abgrall0031cea2012-04-17 16:38:23 -0700119 "-F bw_INPUT",
120 "-F bw_OUTPUT",
121 "-F bw_FORWARD",
JP Abgrall7e51cde2013-07-03 13:33:05 -0700122 "-F bw_happy_box",
123 "-F bw_penalty_box",
124 "-F bw_costly_shared",
JP Abgrallf66d6e92012-04-27 00:22:57 -0700125
126 "-t raw -F bw_raw_PREROUTING",
127 "-t mangle -F bw_mangle_POSTROUTING",
JP Abgrall0031cea2012-04-17 16:38:23 -0700128};
129
130/* The cleanup commands assume flushing has been done. */
131const char *BandwidthController::IPT_CLEANUP_COMMANDS[] = {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700132 "-X bw_happy_box",
133 "-X bw_penalty_box",
134 "-X bw_costly_shared",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700135};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700136
JP Abgralldb7da582011-09-18 12:57:32 -0700137const char *BandwidthController::IPT_SETUP_COMMANDS[] = {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700138 "-N bw_happy_box",
139 "-N bw_penalty_box",
140 "-N bw_costly_shared",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700141};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700142
JP Abgralldb7da582011-09-18 12:57:32 -0700143const char *BandwidthController::IPT_BASIC_ACCOUNTING_COMMANDS[] = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700144 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700145
JP Abgrall0031cea2012-04-17 16:38:23 -0700146 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700147
JP Abgrall7e51cde2013-07-03 13:33:05 -0700148 "-A bw_costly_shared --jump bw_penalty_box",
JP Abgrallf66d6e92012-04-27 00:22:57 -0700149
JP Abgrall92009c82013-02-06 18:01:24 -0800150 "-t raw -A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
151 "-t mangle -A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700152};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700153
154BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700155}
156
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700157int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700158 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700159 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700160
Steve Block3fb42e02011-10-20 11:55:56 +0100161 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700162 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
163 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700164 return res;
165}
166
JP Abgrall26e0d492011-06-24 19:21:51 -0700167int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
168
169 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
170 strncpy(buffer, src, buffSize);
171 return buffer[buffSize - 1];
172}
173
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700174int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700175 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700176 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700177 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700178 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700179 char *next = buffer;
180 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700181 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800182 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700183
JP Abgrall0dad7c22011-06-24 11:58:14 -0700184 std::string fullCmd = cmd;
JP Abgrall26e0d492011-06-24 19:21:51 -0700185
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700186 switch (jumpHandling) {
187 case IptJumpReject:
JP Abgrall340d5cc2013-06-28 17:06:00 -0700188 /*
189 * Must be carefull what one rejects with, as uper layer protocols will just
190 * keep on hammering the device until the number of retries are done.
191 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
192 */
193 fullCmd += " --jump REJECT";
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700194 break;
195 case IptJumpReturn:
196 fullCmd += " --jump RETURN";
197 break;
198 case IptJumpNoAdd:
199 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700200 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700201
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700202 fullCmd.insert(0, " ");
203 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700204
Rom Lemarchand14150212013-01-24 10:01:04 -0800205 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
206 ALOGE("iptables command too long");
207 return -1;
208 }
209
210 argc = 0;
211 while ((tmp = strsep(&next, " "))) {
212 argv[argc++] = tmp;
213 if (argc >= MAX_CMD_ARGS) {
214 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700215 return -1;
216 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700217 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800218
219 argv[argc] = NULL;
220 res = android_fork_execvp(argc, (char **)argv, &status, false,
221 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800222 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
223 if (res && failureHandling == IptFailShow) {
224 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
225 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700226 }
227 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700228}
229
JP Abgrall0e540ec2013-08-26 15:13:10 -0700230void BandwidthController::flushCleanTables(bool doClean) {
231 /* Flush and remove the bw_costly_<iface> tables */
232 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700233
234 /* Some of the initialCommands are allowed to fail */
235 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
236 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
237
JP Abgrall0e540ec2013-08-26 15:13:10 -0700238 if (doClean) {
239 runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
240 IPT_CLEANUP_COMMANDS, RunCmdFailureOk);
241 }
242}
JP Abgrall0031cea2012-04-17 16:38:23 -0700243
JP Abgrall0e540ec2013-08-26 15:13:10 -0700244int BandwidthController::setupIptablesHooks(void) {
245
246 /* flush+clean is allowed to fail */
247 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700248 runCommands(sizeof(IPT_SETUP_COMMANDS) / sizeof(char*),
249 IPT_SETUP_COMMANDS, RunCmdFailureBad);
250
251 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700252}
253
254int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700255 int res;
JP Abgrall0031cea2012-04-17 16:38:23 -0700256 char value[PROPERTY_VALUE_MAX];
257
258 if (!force) {
259 property_get("persist.bandwidth.enable", value, "1");
260 if (!strcmp(value, "0"))
261 return 0;
262 }
JP Abgrall8a932722011-07-13 19:17:35 -0700263
JP Abgralldb7da582011-09-18 12:57:32 -0700264 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700265 sharedQuotaIfaces.clear();
266 quotaIfaces.clear();
267 naughtyAppUids.clear();
JP Abgralle4788732013-07-02 20:28:45 -0700268 niceAppUids.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700269 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700270 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700271 sharedQuotaBytes = sharedAlertBytes = 0;
272
JP Abgrall0e540ec2013-08-26 15:13:10 -0700273 flushCleanTables(false);
274 res = runCommands(sizeof(IPT_BASIC_ACCOUNTING_COMMANDS) / sizeof(char*),
JP Abgralldb7da582011-09-18 12:57:32 -0700275 IPT_BASIC_ACCOUNTING_COMMANDS, RunCmdFailureBad);
JP Abgrall8a932722011-07-13 19:17:35 -0700276
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700277 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700278
279}
280
281int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700282
283 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700284 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700285}
286
JP Abgrall8a932722011-07-13 19:17:35 -0700287int BandwidthController::runCommands(int numCommands, const char *commands[],
288 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700289 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700290 IptFailureLog failureLogging = IptFailShow;
291 if (cmdErrHandling == RunCmdFailureOk) {
292 failureLogging = IptFailHide;
293 }
Steve Block3fb42e02011-10-20 11:55:56 +0100294 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700295 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700296 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700297 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700298 return res;
299 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700300 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700301}
302
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700303std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700304 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700305 char *buff;
306 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700307
308 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700309 case IptOpInsert:
310 opFlag = "-I";
311 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800312 case IptOpAppend:
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700313 ALOGE("Append op not supported for %s uids", chain);
314 res = "";
315 return res;
JP Abgrall109899b2013-02-12 19:20:13 -0800316 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700317 case IptOpReplace:
318 opFlag = "-R";
319 break;
320 default:
321 case IptOpDelete:
322 opFlag = "-D";
323 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700324 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700325 asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
JP Abgrall8a932722011-07-13 19:17:35 -0700326 res = buff;
327 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700328 return res;
329}
330
JP Abgralle4788732013-07-02 20:28:45 -0700331int BandwidthController::enableHappyBox(void) {
332 char cmd[MAX_CMD_LEN];
333 int res = 0;
334
335 /*
336 * We tentatively delete before adding, which helps recovering
337 * from bad states (e.g. netd died).
338 */
339
340 /* Should not exist, but ignore result if already there. */
JP Abgrall7e51cde2013-07-03 13:33:05 -0700341 snprintf(cmd, sizeof(cmd), "-N bw_happy_box");
JP Abgralle4788732013-07-02 20:28:45 -0700342 runIpxtablesCmd(cmd, IptJumpNoAdd);
343
344 /* Should be empty, but clear in case something was wrong. */
345 niceAppUids.clear();
JP Abgrall7e51cde2013-07-03 13:33:05 -0700346 snprintf(cmd, sizeof(cmd), "-F bw_happy_box");
JP Abgralle4788732013-07-02 20:28:45 -0700347 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
348
JP Abgrall7e51cde2013-07-03 13:33:05 -0700349 snprintf(cmd, sizeof(cmd), "-D bw_penalty_box -j bw_happy_box");
JP Abgralle4788732013-07-02 20:28:45 -0700350 runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall7e51cde2013-07-03 13:33:05 -0700351 snprintf(cmd, sizeof(cmd), "-A bw_penalty_box -j bw_happy_box");
JP Abgralle4788732013-07-02 20:28:45 -0700352 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
353
354 /* Reject. Defaulting to prot-unreachable */
JP Abgrall7e51cde2013-07-03 13:33:05 -0700355 snprintf(cmd, sizeof(cmd), "-D bw_happy_box -j REJECT");
JP Abgralle4788732013-07-02 20:28:45 -0700356 runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall7e51cde2013-07-03 13:33:05 -0700357 snprintf(cmd, sizeof(cmd), "-A bw_happy_box -j REJECT");
JP Abgralle4788732013-07-02 20:28:45 -0700358 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
359
360 return res;
361}
362
363int BandwidthController::disableHappyBox(void) {
364 char cmd[MAX_CMD_LEN];
365
366 /* Best effort */
JP Abgrall7e51cde2013-07-03 13:33:05 -0700367 snprintf(cmd, sizeof(cmd), "-D bw_penalty_box -j bw_happy_box");
JP Abgralle4788732013-07-02 20:28:45 -0700368 runIpxtablesCmd(cmd, IptJumpNoAdd);
369 niceAppUids.clear();
JP Abgrall7e51cde2013-07-03 13:33:05 -0700370 snprintf(cmd, sizeof(cmd), "-F bw_happy_box");
JP Abgralle4788732013-07-02 20:28:45 -0700371 runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall7e51cde2013-07-03 13:33:05 -0700372 snprintf(cmd, sizeof(cmd), "-X bw_happy_box");
JP Abgralle4788732013-07-02 20:28:45 -0700373 runIpxtablesCmd(cmd, IptJumpNoAdd);
374
375 return 0;
376}
377
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700378int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700379 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700380}
381
382int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700383 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpRemove);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700384}
385
JP Abgralle4788732013-07-02 20:28:45 -0700386int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
387 return manipulateNiceApps(numUids, appUids, SpecialAppOpAdd);
388}
389
390int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
391 return manipulateNiceApps(numUids, appUids, SpecialAppOpRemove);
392}
393
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700394int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700395 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", naughtyAppUids, IptJumpReject, appOp);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700396}
397
JP Abgralle4788732013-07-02 20:28:45 -0700398int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700399 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", niceAppUids, IptJumpReturn, appOp);
JP Abgralle4788732013-07-02 20:28:45 -0700400}
401
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700402
403int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
404 const char *chain,
405 std::list<int /*appUid*/> &specialAppUids,
406 IptJumpOp jumpHandling, SpecialAppOp appOp) {
407
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700408 char cmd[MAX_CMD_LEN];
409 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700410 const char *failLogTemplate;
411 IptOp op;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700412 int appUids[numUids];
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700413 std::string iptCmd;
JP Abgrallb1d24092012-04-27 01:02:31 -0700414 std::list<int /*uid*/>::iterator it;
JP Abgrall8a932722011-07-13 19:17:35 -0700415
JP Abgrall26e0d492011-06-24 19:21:51 -0700416 switch (appOp) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700417 case SpecialAppOpAdd:
JP Abgrall8a932722011-07-13 19:17:35 -0700418 op = IptOpInsert;
JP Abgrallaf476f72013-07-03 12:23:55 -0700419 failLogTemplate = "Failed to add app uid %s(%d) to %s.";
JP Abgrall8a932722011-07-13 19:17:35 -0700420 break;
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700421 case SpecialAppOpRemove:
JP Abgrall8a932722011-07-13 19:17:35 -0700422 op = IptOpDelete;
JP Abgrallaf476f72013-07-03 12:23:55 -0700423 failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
JP Abgrall8a932722011-07-13 19:17:35 -0700424 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700425 default:
426 ALOGE("Unexpected app Op %d", appOp);
427 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700428 }
429
430 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700431 char *end;
432 appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
433 if (*end || !*appStrUids[uidNum]) {
434 ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
JP Abgrall26e0d492011-06-24 19:21:51 -0700435 goto fail_parse;
436 }
437 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700438
439 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700440 int uid = appUids[uidNum];
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700441 for (it = specialAppUids.begin(); it != specialAppUids.end(); it++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700442 if (*it == uid)
443 break;
444 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700445 bool found = (it != specialAppUids.end());
JP Abgrallb1d24092012-04-27 01:02:31 -0700446
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700447 if (appOp == SpecialAppOpRemove) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700448 if (!found) {
449 ALOGE("No such appUid %d to remove", uid);
450 return -1;
451 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700452 specialAppUids.erase(it);
JP Abgrallb1d24092012-04-27 01:02:31 -0700453 } else {
454 if (found) {
455 ALOGE("appUid %d exists already", uid);
456 return -1;
457 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700458 specialAppUids.push_front(uid);
JP Abgrallb1d24092012-04-27 01:02:31 -0700459 }
460
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700461 iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
462 if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700463 ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700464 goto fail_with_uidNum;
465 }
466 }
467 return 0;
468
JP Abgrall26e0d492011-06-24 19:21:51 -0700469fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700470 /* Try to remove the uid that failed in any case*/
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700471 iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
472 runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
JP Abgrall26e0d492011-06-24 19:21:51 -0700473fail_parse:
474 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700475}
476
JP Abgrall26e0d492011-06-24 19:21:51 -0700477std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700478 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700479 char *buff;
480 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700481
SynergyDev7776cea2014-03-16 15:48:51 -0700482 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700483
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700484 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700485 case IptOpInsert:
486 opFlag = "-I";
487 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800488 case IptOpAppend:
489 opFlag = "-A";
490 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700491 case IptOpReplace:
492 opFlag = "-R";
493 break;
494 default:
495 case IptOpDelete:
496 opFlag = "-D";
497 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700498 }
JP Abgrall8a932722011-07-13 19:17:35 -0700499
JP Abgrallbfa74662011-06-29 19:23:04 -0700500 // The requried IP version specific --jump REJECT ... will be added later.
SynergyDev7776cea2014-03-16 15:48:51 -0700501 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %" PRId64" --name %s", opFlag, costName, quota,
JP Abgrall8a932722011-07-13 19:17:35 -0700502 costName);
503 res = buff;
504 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700505 return res;
506}
507
JP Abgrall26e0d492011-06-24 19:21:51 -0700508int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700509 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700510 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700511 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700512 std::string costString;
513 const char *costCString;
514
JP Abgrall0dad7c22011-06-24 11:58:14 -0700515 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700516 switch (quotaType) {
517 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700518 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700519 costString += ifn;
520 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700521 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700522 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700523 * Creating a new one is allowed to fail in case it existed.
524 * This helps with netd restarts.
525 */
526 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700527 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700528 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700529 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700530 res = (res1 && res2) || (!res1 && !res2);
531
JP Abgrall7e51cde2013-07-03 13:33:05 -0700532 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700533 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700534 break;
535 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700536 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700537 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700538 default:
539 ALOGE("Unexpected quotatype %d", quotaType);
540 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700541 }
542
JP Abgrall8a932722011-07-13 19:17:35 -0700543 if (globalAlertBytes) {
544 /* The alert rule comes 1st */
545 ruleInsertPos = 2;
546 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700547
548 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700549 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700550
551 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700552 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700553
554 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700555 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700556
557 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700558 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700559 return res;
560}
561
JP Abgrall26e0d492011-06-24 19:21:51 -0700562int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700563 char cmd[MAX_CMD_LEN];
564 int res = 0;
565 std::string costString;
566 const char *costCString;
567
JP Abgrall26e0d492011-06-24 19:21:51 -0700568 switch (quotaType) {
569 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700570 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700571 costString += ifn;
572 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700573 break;
574 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700575 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700576 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700577 default:
578 ALOGE("Unexpected quotatype %d", quotaType);
579 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700580 }
581
JP Abgrall0031cea2012-04-17 16:38:23 -0700582 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700583 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700584 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700585 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700586
JP Abgrall7e51cde2013-07-03 13:33:05 -0700587 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700588 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700589 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700590 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700591 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700592 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700593 }
594 return res;
595}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700596
JP Abgrall0dad7c22011-06-24 11:58:14 -0700597int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700598 char cmd[MAX_CMD_LEN];
599 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700600 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700601 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700602 std::string ifaceName;
603 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700604 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700605 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700606
JP Abgrall8a932722011-07-13 19:17:35 -0700607 if (!maxBytes) {
608 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000609 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700610 return -1;
611 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700612 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000613 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700614 return -1;
615 }
616 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700617
618 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700619 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700620 }
621
622 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700623 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
624 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700625 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700626 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700627
JP Abgrall0dad7c22011-06-24 11:58:14 -0700628 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700629 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700630 if (sharedQuotaIfaces.empty()) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700631 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700632 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700633 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000634 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700635 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700636 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700637 sharedQuotaBytes = maxBytes;
638 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700639 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700640
641 }
642
643 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700644 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700645 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000646 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700647 goto fail;
648 }
649 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700650 }
651 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700652
653 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700654 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700655 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
656 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700657 * For now callers needs to choose if they want to "ndc bandwidth enable"
658 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700659 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700660 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700661 return -1;
662}
663
JP Abgrall8a932722011-07-13 19:17:35 -0700664/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700665int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700666 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700667 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700668 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700669 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700670 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700671
JP Abgrall8a932722011-07-13 19:17:35 -0700672 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000673 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700674 return -1;
675 }
JP Abgrall8a932722011-07-13 19:17:35 -0700676 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700677
JP Abgrall0dad7c22011-06-24 11:58:14 -0700678 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
679 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700680 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700681 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700682 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000683 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700684 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700685 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700686
JP Abgrall26e0d492011-06-24 19:21:51 -0700687 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700688 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700689
JP Abgrall0dad7c22011-06-24 11:58:14 -0700690 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700691 std::string quotaCmd;
JP Abgrallbfa74662011-06-29 19:23:04 -0700692 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700693 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall8a932722011-07-13 19:17:35 -0700694 sharedQuotaBytes = 0;
695 if (sharedAlertBytes) {
696 removeSharedAlert();
697 sharedAlertBytes = 0;
698 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700699 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700700 return res;
701}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700702
703int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
704 char ifn[MAX_IFACENAME_LEN];
705 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700706 std::string ifaceName;
707 const char *costName;
708 std::list<QuotaInfo>::iterator it;
709 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700710
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700711 if (!isNameLegal(iface)) {
712 ALOGE("setInterfaceQuota: Invalid iface \"%s\"", iface);
713 return -1;
714 }
715
JP Abgrall8a932722011-07-13 19:17:35 -0700716 if (!maxBytes) {
717 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000718 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700719 return -1;
720 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700721 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700722 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700723 }
724
JP Abgrall8a932722011-07-13 19:17:35 -0700725 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000726 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700727 return -1;
728 }
729 ifaceName = ifn;
730 costName = iface;
731
JP Abgrall0dad7c22011-06-24 11:58:14 -0700732 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700733 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700734 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700735 break;
736 }
737
738 if (it == quotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700739 /* Preparing the iface adds a penalty/happy box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700740 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700741 /*
JP Abgralle4788732013-07-02 20:28:45 -0700742 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700743 * or else a naughty app could just eat up the quota.
744 * So we append here.
745 */
JP Abgrall109899b2013-02-12 19:20:13 -0800746 quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700747 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700748 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000749 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700750 goto fail;
751 }
752
JP Abgrall8a932722011-07-13 19:17:35 -0700753 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700754
755 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700756 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700757 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000758 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700759 goto fail;
760 }
JP Abgrall8a932722011-07-13 19:17:35 -0700761 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700762 }
763 return 0;
764
765 fail:
766 /*
767 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
768 * rules in the kernel to see which ones need cleaning up.
769 * For now callers needs to choose if they want to "ndc bandwidth enable"
770 * which resets everything.
771 */
772 removeInterfaceSharedQuota(ifn);
773 return -1;
774}
775
JP Abgrall8a932722011-07-13 19:17:35 -0700776int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
777 return getInterfaceQuota("shared", bytes);
778}
779
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700780bool BandwidthController::isNameLegal(const char* name) {
781 size_t i;
782 size_t name_len = strlen(name);
783 if (name_len == 0) {
784 return false;
785 }
786
787 /* First character must be alphanumeric */
788 if (!isalnum(name[0])) {
789 return false;
790 }
791
792 for (i = 1; i < name_len; i++) {
793 if (!isalnum(name[i]) && (name[i] != '_') && (name[i] != '-') && (name[i] != ':')) {
794 return false;
795 }
796 }
797
798 return true;
799}
800
JP Abgrall8a932722011-07-13 19:17:35 -0700801int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
802 FILE *fp;
803 char *fname;
804 int scanRes;
805
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700806 if (!isNameLegal(costName)) {
807 ALOGE("getInterfaceQuota: Invalid costName \"%s\"", costName);
808 return -1;
809 }
810
JP Abgrall8a932722011-07-13 19:17:35 -0700811 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
812 fp = fopen(fname, "r");
813 free(fname);
814 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000815 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700816 return -1;
817 }
Mark Salyzynca0b5e22014-03-26 14:15:03 -0700818 scanRes = fscanf(fp, "%" SCNd64, bytes);
SynergyDev7776cea2014-03-16 15:48:51 -0700819 ALOGV("Read quota res=%d bytes=%" PRId64, scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700820 fclose(fp);
821 return scanRes == 1 ? 0 : -1;
822}
823
JP Abgrall0dad7c22011-06-24 11:58:14 -0700824int BandwidthController::removeInterfaceQuota(const char *iface) {
825
826 char ifn[MAX_IFACENAME_LEN];
827 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700828 std::string ifaceName;
829 const char *costName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700830 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700831
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700832 if (!isNameLegal(iface)) {
833 ALOGE("removeInterfaceQuota: Invalid iface \"%s\"", iface);
834 return -1;
835 }
836
JP Abgrall8a932722011-07-13 19:17:35 -0700837 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000838 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700839 return -1;
840 }
841 ifaceName = ifn;
842 costName = iface;
843
JP Abgrall0dad7c22011-06-24 11:58:14 -0700844 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700845 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700846 break;
847 }
848
849 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000850 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700851 return -1;
852 }
853
854 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700855 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700856
857 quotaIfaces.erase(it);
858
859 return res;
860}
JP Abgrall8a932722011-07-13 19:17:35 -0700861
862int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
863 FILE *fp;
864 char *fname;
865
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700866 if (!isNameLegal(quotaName)) {
867 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName);
868 return -1;
869 }
870
JP Abgrall8a932722011-07-13 19:17:35 -0700871 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
872 fp = fopen(fname, "w");
873 free(fname);
874 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000875 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700876 return -1;
877 }
SynergyDev7776cea2014-03-16 15:48:51 -0700878 fprintf(fp, "%" PRId64"\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700879 fclose(fp);
880 return 0;
881}
882
883int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
884 int res = 0;
885 const char *opFlag;
886 char *alertQuotaCmd;
887
888 switch (op) {
889 case IptOpInsert:
890 opFlag = "-I";
891 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800892 case IptOpAppend:
893 opFlag = "-A";
894 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700895 case IptOpReplace:
896 opFlag = "-R";
897 break;
898 default:
899 case IptOpDelete:
900 opFlag = "-D";
901 break;
902 }
903
JP Abgrall92009c82013-02-06 18:01:24 -0800904 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800905 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700906 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700907 free(alertQuotaCmd);
JP Abgrall92009c82013-02-06 18:01:24 -0800908 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800909 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700910 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700911 free(alertQuotaCmd);
912 return res;
913}
914
JP Abgrallc6c67342011-10-07 16:28:54 -0700915int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
916 int res = 0;
917 const char *opFlag;
JP Abgrall8a932722011-07-13 19:17:35 -0700918 char *alertQuotaCmd;
JP Abgrallc6c67342011-10-07 16:28:54 -0700919
920 switch (op) {
921 case IptOpInsert:
922 opFlag = "-I";
923 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800924 case IptOpAppend:
925 opFlag = "-A";
926 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700927 case IptOpReplace:
928 opFlag = "-R";
929 break;
930 default:
931 case IptOpDelete:
932 opFlag = "-D";
933 break;
934 }
935
JP Abgrall92009c82013-02-06 18:01:24 -0800936 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800937 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700938 res = runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrallc6c67342011-10-07 16:28:54 -0700939 free(alertQuotaCmd);
940 return res;
941}
942
943int BandwidthController::setGlobalAlert(int64_t bytes) {
944 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700945 int res = 0;
946
947 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000948 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700949 return -1;
950 }
951 if (globalAlertBytes) {
952 res = updateQuota(alertName, bytes);
953 } else {
954 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700955 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100956 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700957 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
958 }
JP Abgrall8a932722011-07-13 19:17:35 -0700959 }
960 globalAlertBytes = bytes;
961 return res;
962}
963
JP Abgrallc6c67342011-10-07 16:28:54 -0700964int BandwidthController::setGlobalAlertInForwardChain(void) {
965 const char *alertName = ALERT_GLOBAL_NAME;
966 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700967
JP Abgrallc6c67342011-10-07 16:28:54 -0700968 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100969 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700970
971 /*
972 * If there is no globalAlert active we are done.
973 * If there is an active globalAlert but this is not the 1st
974 * tether, we are also done.
975 */
976 if (!globalAlertBytes || globalAlertTetherCount != 1) {
977 return 0;
978 }
979
980 /* We only add the rule if this was the 1st tether added. */
981 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
982 return res;
983}
984
985int BandwidthController::removeGlobalAlert(void) {
986
987 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700988 int res = 0;
989
990 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000991 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700992 return -1;
993 }
994 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700995 if (globalAlertTetherCount) {
996 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
997 }
JP Abgrall8a932722011-07-13 19:17:35 -0700998 globalAlertBytes = 0;
999 return res;
1000}
1001
JP Abgrallc6c67342011-10-07 16:28:54 -07001002int BandwidthController::removeGlobalAlertInForwardChain(void) {
1003 int res = 0;
1004 const char *alertName = ALERT_GLOBAL_NAME;
1005
1006 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +00001007 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -07001008 return -1;
1009 }
1010
1011 globalAlertTetherCount--;
1012 /*
1013 * If there is no globalAlert active we are done.
1014 * If there is an active globalAlert but there are more
1015 * tethers, we are also done.
1016 */
1017 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
1018 return 0;
1019 }
1020
1021 /* We only detete the rule if this was the last tether removed. */
1022 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
1023 return res;
1024}
1025
JP Abgrall8a932722011-07-13 19:17:35 -07001026int BandwidthController::setSharedAlert(int64_t bytes) {
1027 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001028 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -07001029 return -1;
1030 }
1031 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001032 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001033 return -1;
1034 }
1035 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
1036}
1037
1038int BandwidthController::removeSharedAlert(void) {
1039 return removeCostlyAlert("shared", &sharedAlertBytes);
1040}
1041
1042int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
1043 std::list<QuotaInfo>::iterator it;
1044
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001045 if (!isNameLegal(iface)) {
1046 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
1047 return -1;
1048 }
1049
JP Abgrall8a932722011-07-13 19:17:35 -07001050 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001051 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001052 return -1;
1053 }
1054 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1055 if (it->ifaceName == iface)
1056 break;
1057 }
1058
1059 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001060 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -07001061 return -1;
1062 }
1063
1064 return setCostlyAlert(iface, bytes, &it->alert);
1065}
1066
1067int BandwidthController::removeInterfaceAlert(const char *iface) {
1068 std::list<QuotaInfo>::iterator it;
1069
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001070 if (!isNameLegal(iface)) {
1071 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
1072 return -1;
1073 }
1074
JP Abgrall8a932722011-07-13 19:17:35 -07001075 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1076 if (it->ifaceName == iface)
1077 break;
1078 }
1079
1080 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001081 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -07001082 return -1;
1083 }
1084
1085 return removeCostlyAlert(iface, &it->alert);
1086}
1087
1088int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1089 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -08001090 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -07001091 int res = 0;
1092 char *alertName;
1093
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001094 if (!isNameLegal(costName)) {
1095 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
1096 return -1;
1097 }
1098
JP Abgrall8a932722011-07-13 19:17:35 -07001099 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001100 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001101 return -1;
1102 }
1103 asprintf(&alertName, "%sAlert", costName);
1104 if (*alertBytes) {
1105 res = updateQuota(alertName, *alertBytes);
1106 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -07001107 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -08001108 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001109 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001110 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -08001111 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -07001112 }
1113 *alertBytes = bytes;
1114 free(alertName);
1115 return res;
1116}
1117
1118int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1119 char *alertQuotaCmd;
1120 char *chainName;
1121 char *alertName;
1122 int res = 0;
1123
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001124 if (!isNameLegal(costName)) {
1125 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
1126 return -1;
1127 }
1128
JP Abgrall8a932722011-07-13 19:17:35 -07001129 asprintf(&alertName, "%sAlert", costName);
1130 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001131 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001132 return -1;
1133 }
1134
JP Abgrall7e51cde2013-07-03 13:33:05 -07001135 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001136 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001137 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001138 free(alertQuotaCmd);
1139 free(chainName);
1140
1141 *alertBytes = 0;
1142 free(alertName);
1143 return res;
1144}
JP Abgralldb7da582011-09-18 12:57:32 -07001145
1146/*
1147 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001148 * Chain natctrl_tether_counters (4 references)
1149 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001150 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1151 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1152 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1153 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
1154 * It results in an error if invoked and no tethering counter rules exist. The constraint
1155 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001156 */
JP Abgrallbaeccc42013-06-25 09:44:10 -07001157int BandwidthController::parseForwardChainStats(SocketClient *cli, const TetherStats filter,
1158 FILE *fp, std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001159 int res;
1160 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
1161 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1162 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1163 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1164
JP Abgrallbaeccc42013-06-25 09:44:10 -07001165 TetherStats stats;
JP Abgralldb7da582011-09-18 12:57:32 -07001166 char *buffPtr;
1167 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001168 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001169
1170 bool filterPair = filter.intIface[0] && filter.extIface[0];
1171
1172 char *filterMsg = filter.getStatsLine();
1173 ALOGV("filter: %s", filterMsg);
1174 free(filterMsg);
1175
1176 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001177
1178 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
1179 /* Clean up, so a failed parse can still print info */
1180 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Mark Salyzynca0b5e22014-03-26 14:15:03 -07001181 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
JP Abgralldb7da582011-09-18 12:57:32 -07001182 &packets, &bytes, iface0, iface1, rest);
SynergyDev7776cea2014-03-16 15:48:51 -07001183 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%" PRId64" bytes=%" PRId64" rest=<%s> orig line=<%s>", res,
JP Abgralldb7da582011-09-18 12:57:32 -07001184 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001185 extraProcessingInfo += buffPtr;
1186
JP Abgralldb7da582011-09-18 12:57:32 -07001187 if (res != 5) {
1188 continue;
1189 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001190 /*
1191 * The following assumes that the 1st rule has in:extIface out:intIface,
1192 * which is what NatController sets up.
1193 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1194 */
1195 if (filter.intIface[0] && filter.extIface[0]) {
1196 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001197 ALOGV("2Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001198 stats.rxPackets = packets;
1199 stats.rxBytes = bytes;
1200 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001201 ALOGV("2Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001202 stats.txPackets = packets;
1203 stats.txBytes = bytes;
1204 }
1205 } else if (filter.intIface[0] || filter.extIface[0]) {
1206 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001207 ALOGV("1Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001208 stats.intIface = iface0;
1209 stats.extIface = iface1;
1210 stats.rxPackets = packets;
1211 stats.rxBytes = bytes;
1212 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001213 ALOGV("1Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001214 stats.intIface = iface1;
1215 stats.extIface = iface0;
1216 stats.txPackets = packets;
1217 stats.txBytes = bytes;
1218 }
1219 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1220 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001221 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001222 stats.intIface = iface0;
1223 stats.extIface = iface1;
1224 stats.rxPackets = packets;
1225 stats.rxBytes = bytes;
1226 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001227 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001228 stats.txPackets = packets;
1229 stats.txBytes = bytes;
1230 }
1231 }
1232 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001233 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001234 /* Send out stats, and prep for the next if needed. */
1235 char *msg = stats.getStatsLine();
1236 if (filterPair) {
1237 cli->sendMsg(ResponseCode::TetheringStatsResult, msg, false);
1238 return 0;
1239 } else {
1240 cli->sendMsg(ResponseCode::TetheringStatsListResult, msg, false);
1241 stats = filter;
1242 }
1243 free(msg);
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001244 statsFound++;
JP Abgralldb7da582011-09-18 12:57:32 -07001245 }
1246 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001247
1248 /* It is always an error to find only one side of the stats. */
1249 /* It is an error to find nothing when not filtering. */
1250 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1251 (!statsFound && !filterPair)) {
1252 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001253 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001254 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1255 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001256}
1257
JP Abgrallbaeccc42013-06-25 09:44:10 -07001258char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001259 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001260 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001261 rxBytes, rxPackets, txBytes, txPackets);
1262 return msg;
1263}
1264
JP Abgrallbaeccc42013-06-25 09:44:10 -07001265int BandwidthController::getTetherStats(SocketClient *cli, TetherStats &stats, std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001266 int res;
1267 std::string fullCmd;
1268 FILE *iptOutput;
1269 const char *cmd;
1270
JP Abgralldb7da582011-09-18 12:57:32 -07001271 /*
1272 * Why not use some kind of lib to talk to iptables?
1273 * Because the only libs are libiptc and libip6tc in iptables, and they are
1274 * not easy to use. They require the known iptables match modules to be
1275 * preloaded/linked, and require apparently a lot of wrapper code to get
1276 * the wanted info.
1277 */
1278 fullCmd = IPTABLES_PATH;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001279 fullCmd += " -nvx -L ";
1280 fullCmd += NatController::LOCAL_TETHER_COUNTERS_CHAIN;
JP Abgralldb7da582011-09-18 12:57:32 -07001281 iptOutput = popen(fullCmd.c_str(), "r");
1282 if (!iptOutput) {
Steve Block5ea0c052012-01-06 19:18:11 +00001283 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
JP Abgralla2a64f02011-11-11 20:36:16 -08001284 extraProcessingInfo += "Failed to run iptables.";
JP Abgralldb7da582011-09-18 12:57:32 -07001285 return -1;
1286 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001287 res = parseForwardChainStats(cli, stats, iptOutput, extraProcessingInfo);
JP Abgralldb7da582011-09-18 12:57:32 -07001288 pclose(iptOutput);
1289
1290 /* Currently NatController doesn't do ipv6 tethering, so we are done. */
1291 return res;
1292}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001293
1294void BandwidthController::flushExistingCostlyTables(bool doClean) {
1295 int res;
1296 std::string fullCmd;
1297 FILE *iptOutput;
1298 const char *cmd;
1299
1300 /* Only lookup ip4 table names as ip6 will have the same tables ... */
1301 fullCmd = IPTABLES_PATH;
1302 fullCmd += " -S";
1303 iptOutput = popen(fullCmd.c_str(), "r");
1304 if (!iptOutput) {
1305 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
1306 return;
1307 }
1308 /* ... then flush/clean both ip4 and ip6 iptables. */
1309 parseAndFlushCostlyTables(iptOutput, doClean);
1310 pclose(iptOutput);
1311}
1312
1313void BandwidthController::parseAndFlushCostlyTables(FILE *fp, bool doRemove) {
1314 int res;
1315 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
1316 char costlyIfaceName[MAX_IPT_OUTPUT_LINE_LEN];
1317 char cmd[MAX_CMD_LEN];
1318 char *buffPtr;
1319
1320 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
1321 costlyIfaceName[0] = '\0'; /* So that debugging output always works */
1322 res = sscanf(buffPtr, "-N bw_costly_%s", costlyIfaceName);
1323 ALOGV("parse res=%d costly=<%s> orig line=<%s>", res,
1324 costlyIfaceName, buffPtr);
1325 if (res != 1) {
1326 continue;
1327 }
1328 /* Exclusions: "shared" is not an ifacename */
1329 if (!strcmp(costlyIfaceName, "shared")) {
1330 continue;
1331 }
1332
1333 snprintf(cmd, sizeof(cmd), "-F bw_costly_%s", costlyIfaceName);
1334 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
1335 if (doRemove) {
1336 snprintf(cmd, sizeof(cmd), "-X bw_costly_%s", costlyIfaceName);
1337 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
1338 }
1339 }
1340}