blob: 1115cbcde3d6667ce249083b4177a777d32556c0 [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
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090044#include "android-base/stringprintf.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070045#define LOG_TAG "BandwidthController"
46#include <cutils/log.h>
47#include <cutils/properties.h>
Rom Lemarchand14150212013-01-24 10:01:04 -080048#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049
JP Abgrall0031cea2012-04-17 16:38:23 -070050#include "NetdConstants.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070051#include "BandwidthController.h"
JP Abgrallbaeccc42013-06-25 09:44:10 -070052#include "NatController.h" /* For LOCAL_TETHER_COUNTERS_CHAIN */
53#include "ResponseCode.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070054
JP Abgralldb7da582011-09-18 12:57:32 -070055/* Alphabetical */
SynergyDev7776cea2014-03-16 15:48:51 -070056#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s"
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";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090062
63namespace {
64
65const char ALERT_GLOBAL_NAME[] = "globalAlert";
66const int MAX_CMD_ARGS = 32;
67const int MAX_CMD_LEN = 1024;
68const int MAX_IFACENAME_LEN = 64;
69const int MAX_IPT_OUTPUT_LINE_LEN = 256;
JP Abgralldb7da582011-09-18 12:57:32 -070070
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070071/**
72 * Some comments about the rules:
73 * * Ordering
74 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070075 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070076 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
77 * - bw_happy_box rejects everything by default.
JP Abgrall29e8de22012-05-03 12:52:15 -070078 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070079 *
80 * * global quota vs per interface quota
81 * - global quota for all costly interfaces uses a single costly chain:
82 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070083 * iptables -N bw_costly_shared
84 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
85 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
86 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -070087 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -070088 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090089 * iptables -A bw_penalty_box --jump bw_happy_box
JP Abgrall8a932722011-07-13 19:17:35 -070090 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070091 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -070092 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
93 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070094 *
95 * - quota per interface. This is achieve by having "costly" chains per quota.
96 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -070097 * iptables -N bw_costly_iface0
98 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
99 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
100 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700101 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700102 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700103 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700104 * * bw_penalty_box handling:
105 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900106 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700107 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700108 * --jump REJECT --reject-with icmp-port-unreachable
109 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700110 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900111 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700112 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700113 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700114 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900115 *
116 * * Turning data saver on and off:
117 * - Adds or removes a REJECT at the end of the bw_costly_shared chain
118 * iptables -A bw_costly_shared --jump REJECT --reject-with icmp-port-unreachable
119 * iptables -D bw_costly_shared --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700120 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900121
122const char *IPT_FLUSH_COMMANDS[] = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700123 /*
124 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700125 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700126 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700127 */
JP Abgrall0031cea2012-04-17 16:38:23 -0700128 "-F bw_INPUT",
129 "-F bw_OUTPUT",
130 "-F bw_FORWARD",
JP Abgrall7e51cde2013-07-03 13:33:05 -0700131 "-F bw_happy_box",
132 "-F bw_penalty_box",
133 "-F bw_costly_shared",
JP Abgrallf66d6e92012-04-27 00:22:57 -0700134
135 "-t raw -F bw_raw_PREROUTING",
136 "-t mangle -F bw_mangle_POSTROUTING",
JP Abgrall0031cea2012-04-17 16:38:23 -0700137};
138
139/* The cleanup commands assume flushing has been done. */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900140const char *IPT_CLEANUP_COMMANDS[] = {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700141 "-X bw_happy_box",
142 "-X bw_penalty_box",
143 "-X bw_costly_shared",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700144};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700145
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900146const char *IPT_SETUP_COMMANDS[] = {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700147 "-N bw_happy_box",
148 "-N bw_penalty_box",
149 "-N bw_costly_shared",
JP Abgrall0dad7c22011-06-24 11:58:14 -0700150};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700151
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900152const char *IPT_BASIC_ACCOUNTING_COMMANDS[] = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700153 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700154
JP Abgrall0031cea2012-04-17 16:38:23 -0700155 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700156
JP Abgrall92009c82013-02-06 18:01:24 -0800157 "-t raw -A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
158 "-t mangle -A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700159};
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700160
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900161const char *COSTLY_SHARED_COMMANDS[] = {
162 "-A bw_costly_shared --jump bw_penalty_box",
163 "-A bw_costly_shared --jump bw_happy_box",
164 "-A bw_costly_shared --jump RETURN",
165};
166
167const std::string kDataSaverEnableCommand = android::base::StringPrintf(
168 "-R bw_costly_shared %zu", ARRAY_SIZE(COSTLY_SHARED_COMMANDS));
169
170} // namespace
171
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700172BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700173}
174
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700175int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700176 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700177 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700178
Steve Block3fb42e02011-10-20 11:55:56 +0100179 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700180 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
181 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700182 return res;
183}
184
JP Abgrall26e0d492011-06-24 19:21:51 -0700185int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
186
187 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
188 strncpy(buffer, src, buffSize);
189 return buffer[buffSize - 1];
190}
191
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700192int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700193 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700194 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700195 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700196 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700197 char *next = buffer;
198 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700199 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800200 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700201
JP Abgrall0dad7c22011-06-24 11:58:14 -0700202 std::string fullCmd = cmd;
JP Abgrall26e0d492011-06-24 19:21:51 -0700203
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700204 switch (jumpHandling) {
205 case IptJumpReject:
JP Abgrall340d5cc2013-06-28 17:06:00 -0700206 /*
207 * Must be carefull what one rejects with, as uper layer protocols will just
208 * keep on hammering the device until the number of retries are done.
209 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
210 */
211 fullCmd += " --jump REJECT";
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700212 break;
213 case IptJumpReturn:
214 fullCmd += " --jump RETURN";
215 break;
216 case IptJumpNoAdd:
217 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700218 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700219
Paul Jensen94b2ab92015-08-04 10:35:05 -0400220 fullCmd.insert(0, " -w ");
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700221 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700222
Rom Lemarchand14150212013-01-24 10:01:04 -0800223 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
224 ALOGE("iptables command too long");
225 return -1;
226 }
227
228 argc = 0;
229 while ((tmp = strsep(&next, " "))) {
230 argv[argc++] = tmp;
231 if (argc >= MAX_CMD_ARGS) {
232 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700233 return -1;
234 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700235 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800236
237 argv[argc] = NULL;
238 res = android_fork_execvp(argc, (char **)argv, &status, false,
239 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800240 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
241 if (res && failureHandling == IptFailShow) {
242 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
243 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700244 }
245 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700246}
247
JP Abgrall0e540ec2013-08-26 15:13:10 -0700248void BandwidthController::flushCleanTables(bool doClean) {
249 /* Flush and remove the bw_costly_<iface> tables */
250 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700251
252 /* Some of the initialCommands are allowed to fail */
253 runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
254 IPT_FLUSH_COMMANDS, RunCmdFailureOk);
255
JP Abgrall0e540ec2013-08-26 15:13:10 -0700256 if (doClean) {
257 runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
258 IPT_CLEANUP_COMMANDS, RunCmdFailureOk);
259 }
260}
JP Abgrall0031cea2012-04-17 16:38:23 -0700261
JP Abgrall0e540ec2013-08-26 15:13:10 -0700262int BandwidthController::setupIptablesHooks(void) {
263
264 /* flush+clean is allowed to fail */
265 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700266 runCommands(sizeof(IPT_SETUP_COMMANDS) / sizeof(char*),
267 IPT_SETUP_COMMANDS, RunCmdFailureBad);
268
269 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700270}
271
272int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700273 int res;
JP Abgrall0031cea2012-04-17 16:38:23 -0700274 char value[PROPERTY_VALUE_MAX];
275
276 if (!force) {
277 property_get("persist.bandwidth.enable", value, "1");
278 if (!strcmp(value, "0"))
279 return 0;
280 }
JP Abgrall8a932722011-07-13 19:17:35 -0700281
JP Abgralldb7da582011-09-18 12:57:32 -0700282 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700283 sharedQuotaIfaces.clear();
284 quotaIfaces.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700285 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700286 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700287 sharedQuotaBytes = sharedAlertBytes = 0;
288
JP Abgrall0e540ec2013-08-26 15:13:10 -0700289 flushCleanTables(false);
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900290 res = runCommands(ARRAY_SIZE(IPT_BASIC_ACCOUNTING_COMMANDS),
JP Abgralldb7da582011-09-18 12:57:32 -0700291 IPT_BASIC_ACCOUNTING_COMMANDS, RunCmdFailureBad);
JP Abgrall8a932722011-07-13 19:17:35 -0700292
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900293 res |= runCommands(ARRAY_SIZE(COSTLY_SHARED_COMMANDS),
294 COSTLY_SHARED_COMMANDS, RunCmdFailureBad);
295
296 char cmd[MAX_CMD_LEN];
297 snprintf(cmd, sizeof(cmd),
298 "-A bw_happy_box -m owner --uid-owner %d-%d", 0, MAX_SYSTEM_UID);
299 runIpxtablesCmd(cmd, IptJumpReturn);
300
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700301 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700302
303}
304
305int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700306
307 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700308 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700309}
310
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900311int BandwidthController::enableDataSaver(bool enable) {
312 return runIpxtablesCmd(kDataSaverEnableCommand.c_str(),
313 enable ? IptJumpReject : IptJumpReturn, IptFailShow);
314}
315
JP Abgrall8a932722011-07-13 19:17:35 -0700316int BandwidthController::runCommands(int numCommands, const char *commands[],
317 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700318 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700319 IptFailureLog failureLogging = IptFailShow;
320 if (cmdErrHandling == RunCmdFailureOk) {
321 failureLogging = IptFailHide;
322 }
Steve Block3fb42e02011-10-20 11:55:56 +0100323 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700324 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700325 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700326 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700327 return res;
328 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700329 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700330}
331
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700332std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700333 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700334 char *buff;
335 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700336
337 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700338 case IptOpInsert:
339 opFlag = "-I";
340 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800341 case IptOpAppend:
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700342 ALOGE("Append op not supported for %s uids", chain);
343 res = "";
344 return res;
JP Abgrall109899b2013-02-12 19:20:13 -0800345 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700346 case IptOpReplace:
347 opFlag = "-R";
348 break;
349 default:
350 case IptOpDelete:
351 opFlag = "-D";
352 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700353 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700354 asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
JP Abgrall8a932722011-07-13 19:17:35 -0700355 res = buff;
356 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700357 return res;
358}
359
360int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700361 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700362}
363
364int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700365 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpRemove);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700366}
367
JP Abgralle4788732013-07-02 20:28:45 -0700368int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
369 return manipulateNiceApps(numUids, appUids, SpecialAppOpAdd);
370}
371
372int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
373 return manipulateNiceApps(numUids, appUids, SpecialAppOpRemove);
374}
375
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700376int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900377 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", IptJumpReject, appOp);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700378}
379
JP Abgralle4788732013-07-02 20:28:45 -0700380int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900381 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", IptJumpReturn, appOp);
JP Abgralle4788732013-07-02 20:28:45 -0700382}
383
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700384
385int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
386 const char *chain,
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700387 IptJumpOp jumpHandling, SpecialAppOp appOp) {
388
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700389 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700390 const char *failLogTemplate;
391 IptOp op;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700392 int appUids[numUids];
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700393 std::string iptCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700394
JP Abgrall26e0d492011-06-24 19:21:51 -0700395 switch (appOp) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700396 case SpecialAppOpAdd:
JP Abgrall8a932722011-07-13 19:17:35 -0700397 op = IptOpInsert;
JP Abgrallaf476f72013-07-03 12:23:55 -0700398 failLogTemplate = "Failed to add app uid %s(%d) to %s.";
JP Abgrall8a932722011-07-13 19:17:35 -0700399 break;
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700400 case SpecialAppOpRemove:
JP Abgrall8a932722011-07-13 19:17:35 -0700401 op = IptOpDelete;
JP Abgrallaf476f72013-07-03 12:23:55 -0700402 failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
JP Abgrall8a932722011-07-13 19:17:35 -0700403 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700404 default:
405 ALOGE("Unexpected app Op %d", appOp);
406 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700407 }
408
409 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700410 char *end;
411 appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
412 if (*end || !*appStrUids[uidNum]) {
413 ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
JP Abgrall26e0d492011-06-24 19:21:51 -0700414 goto fail_parse;
415 }
416 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700417
418 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700419 int uid = appUids[uidNum];
JP Abgrallb1d24092012-04-27 01:02:31 -0700420
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700421 iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
422 if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700423 ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700424 goto fail_with_uidNum;
425 }
426 }
427 return 0;
428
JP Abgrall26e0d492011-06-24 19:21:51 -0700429fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700430 /* Try to remove the uid that failed in any case*/
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700431 iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
432 runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
JP Abgrall26e0d492011-06-24 19:21:51 -0700433fail_parse:
434 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700435}
436
JP Abgrall26e0d492011-06-24 19:21:51 -0700437std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700438 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700439 char *buff;
440 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700441
SynergyDev7776cea2014-03-16 15:48:51 -0700442 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700443
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700444 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700445 case IptOpInsert:
446 opFlag = "-I";
447 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800448 case IptOpAppend:
449 opFlag = "-A";
450 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700451 case IptOpReplace:
452 opFlag = "-R";
453 break;
454 default:
455 case IptOpDelete:
456 opFlag = "-D";
457 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700458 }
JP Abgrall8a932722011-07-13 19:17:35 -0700459
JP Abgrallbfa74662011-06-29 19:23:04 -0700460 // The requried IP version specific --jump REJECT ... will be added later.
SynergyDev7776cea2014-03-16 15:48:51 -0700461 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %" PRId64" --name %s", opFlag, costName, quota,
JP Abgrall8a932722011-07-13 19:17:35 -0700462 costName);
463 res = buff;
464 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700465 return res;
466}
467
JP Abgrall26e0d492011-06-24 19:21:51 -0700468int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700469 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700470 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700471 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700472 std::string costString;
473 const char *costCString;
474
JP Abgrall0dad7c22011-06-24 11:58:14 -0700475 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700476 switch (quotaType) {
477 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700478 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700479 costString += ifn;
480 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700481 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700482 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700483 * Creating a new one is allowed to fail in case it existed.
484 * This helps with netd restarts.
485 */
486 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700487 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700488 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700489 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700490 res = (res1 && res2) || (!res1 && !res2);
491
JP Abgrall7e51cde2013-07-03 13:33:05 -0700492 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700493 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700494 break;
495 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700496 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700497 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700498 default:
499 ALOGE("Unexpected quotatype %d", quotaType);
500 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700501 }
502
JP Abgrall8a932722011-07-13 19:17:35 -0700503 if (globalAlertBytes) {
504 /* The alert rule comes 1st */
505 ruleInsertPos = 2;
506 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700507
508 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700509 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700510
511 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700512 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700513
514 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700515 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700516
517 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700518 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900519
520 snprintf(cmd, sizeof(cmd), "-D bw_FORWARD -o %s --jump %s", ifn, costCString);
521 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
522 snprintf(cmd, sizeof(cmd), "-A bw_FORWARD -o %s --jump %s", ifn, costCString);
523 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
524
JP Abgrall0dad7c22011-06-24 11:58:14 -0700525 return res;
526}
527
JP Abgrall26e0d492011-06-24 19:21:51 -0700528int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700529 char cmd[MAX_CMD_LEN];
530 int res = 0;
531 std::string costString;
532 const char *costCString;
533
JP Abgrall26e0d492011-06-24 19:21:51 -0700534 switch (quotaType) {
535 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700536 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700537 costString += ifn;
538 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700539 break;
540 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700541 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700542 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700543 default:
544 ALOGE("Unexpected quotatype %d", quotaType);
545 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700546 }
547
JP Abgrall0031cea2012-04-17 16:38:23 -0700548 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700549 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900550 for (const auto tableName : {LOCAL_OUTPUT, LOCAL_FORWARD}) {
551 snprintf(cmd, sizeof(cmd), "-D %s -o %s --jump %s", tableName, ifn, costCString);
552 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
553 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700554
JP Abgrall7e51cde2013-07-03 13:33:05 -0700555 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700556 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700557 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700558 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700559 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700560 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700561 }
562 return res;
563}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700564
JP Abgrall0dad7c22011-06-24 11:58:14 -0700565int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700566 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700567 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700568 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700569 std::string ifaceName;
570 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700571 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700572 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700573
JP Abgrall8a932722011-07-13 19:17:35 -0700574 if (!maxBytes) {
575 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000576 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700577 return -1;
578 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700579 if (!isIfaceName(iface))
580 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700581 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000582 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700583 return -1;
584 }
585 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700586
587 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700588 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700589 }
590
591 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700592 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
593 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700594 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700595 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700596
JP Abgrall0dad7c22011-06-24 11:58:14 -0700597 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700598 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700599 if (sharedQuotaIfaces.empty()) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700600 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700601 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700602 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000603 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700604 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700605 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700606 sharedQuotaBytes = maxBytes;
607 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700608 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700609
610 }
611
612 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700613 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700614 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000615 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700616 goto fail;
617 }
618 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700619 }
620 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700621
622 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700623 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700624 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
625 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700626 * For now callers needs to choose if they want to "ndc bandwidth enable"
627 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700628 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700629 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700630 return -1;
631}
632
JP Abgrall8a932722011-07-13 19:17:35 -0700633/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700634int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700635 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700636 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700637 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700638 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700639 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700640
JP Abgrall69261cb2014-06-19 18:35:24 -0700641 if (!isIfaceName(iface))
642 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700643 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000644 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700645 return -1;
646 }
JP Abgrall8a932722011-07-13 19:17:35 -0700647 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700648
JP Abgrall0dad7c22011-06-24 11:58:14 -0700649 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
650 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700651 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700652 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700653 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000654 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700655 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700656 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700657
JP Abgrall26e0d492011-06-24 19:21:51 -0700658 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700659 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700660
JP Abgrall0dad7c22011-06-24 11:58:14 -0700661 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700662 std::string quotaCmd;
JP Abgrallbfa74662011-06-29 19:23:04 -0700663 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700664 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall8a932722011-07-13 19:17:35 -0700665 sharedQuotaBytes = 0;
666 if (sharedAlertBytes) {
667 removeSharedAlert();
668 sharedAlertBytes = 0;
669 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700670 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700671 return res;
672}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700673
674int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
675 char ifn[MAX_IFACENAME_LEN];
676 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700677 std::string ifaceName;
678 const char *costName;
679 std::list<QuotaInfo>::iterator it;
680 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700681
JP Abgrall69261cb2014-06-19 18:35:24 -0700682 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700683 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700684
JP Abgrall8a932722011-07-13 19:17:35 -0700685 if (!maxBytes) {
686 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000687 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700688 return -1;
689 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700690 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700691 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700692 }
693
JP Abgrall8a932722011-07-13 19:17:35 -0700694 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000695 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700696 return -1;
697 }
698 ifaceName = ifn;
699 costName = iface;
700
JP Abgrall0dad7c22011-06-24 11:58:14 -0700701 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700702 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700703 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700704 break;
705 }
706
707 if (it == quotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700708 /* Preparing the iface adds a penalty/happy box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700709 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700710 /*
JP Abgralle4788732013-07-02 20:28:45 -0700711 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700712 * or else a naughty app could just eat up the quota.
713 * So we append here.
714 */
JP Abgrall109899b2013-02-12 19:20:13 -0800715 quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700716 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700717 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000718 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700719 goto fail;
720 }
721
JP Abgrall8a932722011-07-13 19:17:35 -0700722 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700723
724 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700725 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700726 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000727 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700728 goto fail;
729 }
JP Abgrall8a932722011-07-13 19:17:35 -0700730 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700731 }
732 return 0;
733
734 fail:
735 /*
736 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
737 * rules in the kernel to see which ones need cleaning up.
738 * For now callers needs to choose if they want to "ndc bandwidth enable"
739 * which resets everything.
740 */
741 removeInterfaceSharedQuota(ifn);
742 return -1;
743}
744
JP Abgrall8a932722011-07-13 19:17:35 -0700745int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
746 return getInterfaceQuota("shared", bytes);
747}
748
749int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
750 FILE *fp;
751 char *fname;
752 int scanRes;
753
JP Abgrall69261cb2014-06-19 18:35:24 -0700754 if (!isIfaceName(costName))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700755 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700756
JP Abgrall8a932722011-07-13 19:17:35 -0700757 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800758 fp = fopen(fname, "re");
JP Abgrall8a932722011-07-13 19:17:35 -0700759 free(fname);
760 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000761 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700762 return -1;
763 }
Mark Salyzynca0b5e22014-03-26 14:15:03 -0700764 scanRes = fscanf(fp, "%" SCNd64, bytes);
SynergyDev7776cea2014-03-16 15:48:51 -0700765 ALOGV("Read quota res=%d bytes=%" PRId64, scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700766 fclose(fp);
767 return scanRes == 1 ? 0 : -1;
768}
769
JP Abgrall0dad7c22011-06-24 11:58:14 -0700770int BandwidthController::removeInterfaceQuota(const char *iface) {
771
772 char ifn[MAX_IFACENAME_LEN];
773 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700774 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700775 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700776
JP Abgrall69261cb2014-06-19 18:35:24 -0700777 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700778 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700779 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000780 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700781 return -1;
782 }
783 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700784
JP Abgrall0dad7c22011-06-24 11:58:14 -0700785 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700786 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700787 break;
788 }
789
790 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000791 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700792 return -1;
793 }
794
795 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700796 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700797
798 quotaIfaces.erase(it);
799
800 return res;
801}
JP Abgrall8a932722011-07-13 19:17:35 -0700802
803int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
804 FILE *fp;
805 char *fname;
806
JP Abgrall69261cb2014-06-19 18:35:24 -0700807 if (!isIfaceName(quotaName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700808 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName);
809 return -1;
810 }
811
JP Abgrall8a932722011-07-13 19:17:35 -0700812 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800813 fp = fopen(fname, "we");
JP Abgrall8a932722011-07-13 19:17:35 -0700814 free(fname);
815 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000816 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700817 return -1;
818 }
SynergyDev7776cea2014-03-16 15:48:51 -0700819 fprintf(fp, "%" PRId64"\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700820 fclose(fp);
821 return 0;
822}
823
824int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
825 int res = 0;
826 const char *opFlag;
827 char *alertQuotaCmd;
828
829 switch (op) {
830 case IptOpInsert:
831 opFlag = "-I";
832 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800833 case IptOpAppend:
834 opFlag = "-A";
835 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700836 case IptOpReplace:
837 opFlag = "-R";
838 break;
839 default:
840 case IptOpDelete:
841 opFlag = "-D";
842 break;
843 }
844
JP Abgrall92009c82013-02-06 18:01:24 -0800845 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800846 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700847 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700848 free(alertQuotaCmd);
JP Abgrall92009c82013-02-06 18:01:24 -0800849 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800850 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700851 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700852 free(alertQuotaCmd);
853 return res;
854}
855
JP Abgrallc6c67342011-10-07 16:28:54 -0700856int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
857 int res = 0;
858 const char *opFlag;
JP Abgrall8a932722011-07-13 19:17:35 -0700859 char *alertQuotaCmd;
JP Abgrallc6c67342011-10-07 16:28:54 -0700860
861 switch (op) {
862 case IptOpInsert:
863 opFlag = "-I";
864 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800865 case IptOpAppend:
866 opFlag = "-A";
867 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700868 case IptOpReplace:
869 opFlag = "-R";
870 break;
871 default:
872 case IptOpDelete:
873 opFlag = "-D";
874 break;
875 }
876
JP Abgrall92009c82013-02-06 18:01:24 -0800877 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800878 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700879 res = runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrallc6c67342011-10-07 16:28:54 -0700880 free(alertQuotaCmd);
881 return res;
882}
883
884int BandwidthController::setGlobalAlert(int64_t bytes) {
885 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700886 int res = 0;
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 if (globalAlertBytes) {
893 res = updateQuota(alertName, bytes);
894 } else {
895 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700896 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100897 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700898 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
899 }
JP Abgrall8a932722011-07-13 19:17:35 -0700900 }
901 globalAlertBytes = bytes;
902 return res;
903}
904
JP Abgrallc6c67342011-10-07 16:28:54 -0700905int BandwidthController::setGlobalAlertInForwardChain(void) {
906 const char *alertName = ALERT_GLOBAL_NAME;
907 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700908
JP Abgrallc6c67342011-10-07 16:28:54 -0700909 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100910 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700911
912 /*
913 * If there is no globalAlert active we are done.
914 * If there is an active globalAlert but this is not the 1st
915 * tether, we are also done.
916 */
917 if (!globalAlertBytes || globalAlertTetherCount != 1) {
918 return 0;
919 }
920
921 /* We only add the rule if this was the 1st tether added. */
922 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
923 return res;
924}
925
926int BandwidthController::removeGlobalAlert(void) {
927
928 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700929 int res = 0;
930
931 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000932 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700933 return -1;
934 }
935 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700936 if (globalAlertTetherCount) {
937 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
938 }
JP Abgrall8a932722011-07-13 19:17:35 -0700939 globalAlertBytes = 0;
940 return res;
941}
942
JP Abgrallc6c67342011-10-07 16:28:54 -0700943int BandwidthController::removeGlobalAlertInForwardChain(void) {
944 int res = 0;
945 const char *alertName = ALERT_GLOBAL_NAME;
946
947 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000948 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700949 return -1;
950 }
951
952 globalAlertTetherCount--;
953 /*
954 * If there is no globalAlert active we are done.
955 * If there is an active globalAlert but there are more
956 * tethers, we are also done.
957 */
958 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
959 return 0;
960 }
961
962 /* We only detete the rule if this was the last tether removed. */
963 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
964 return res;
965}
966
JP Abgrall8a932722011-07-13 19:17:35 -0700967int BandwidthController::setSharedAlert(int64_t bytes) {
968 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000969 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700970 return -1;
971 }
972 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000973 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700974 return -1;
975 }
976 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
977}
978
979int BandwidthController::removeSharedAlert(void) {
980 return removeCostlyAlert("shared", &sharedAlertBytes);
981}
982
983int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
984 std::list<QuotaInfo>::iterator it;
985
JP Abgrall69261cb2014-06-19 18:35:24 -0700986 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700987 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
988 return -1;
989 }
990
JP Abgrall8a932722011-07-13 19:17:35 -0700991 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000992 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700993 return -1;
994 }
995 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
996 if (it->ifaceName == iface)
997 break;
998 }
999
1000 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001001 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -07001002 return -1;
1003 }
1004
1005 return setCostlyAlert(iface, bytes, &it->alert);
1006}
1007
1008int BandwidthController::removeInterfaceAlert(const char *iface) {
1009 std::list<QuotaInfo>::iterator it;
1010
JP Abgrall69261cb2014-06-19 18:35:24 -07001011 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001012 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
1013 return -1;
1014 }
1015
JP Abgrall8a932722011-07-13 19:17:35 -07001016 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1017 if (it->ifaceName == iface)
1018 break;
1019 }
1020
1021 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001022 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -07001023 return -1;
1024 }
1025
1026 return removeCostlyAlert(iface, &it->alert);
1027}
1028
1029int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1030 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -08001031 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -07001032 int res = 0;
1033 char *alertName;
1034
JP Abgrall69261cb2014-06-19 18:35:24 -07001035 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001036 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
1037 return -1;
1038 }
1039
JP Abgrall8a932722011-07-13 19:17:35 -07001040 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001041 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001042 return -1;
1043 }
1044 asprintf(&alertName, "%sAlert", costName);
1045 if (*alertBytes) {
1046 res = updateQuota(alertName, *alertBytes);
1047 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -07001048 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -08001049 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001050 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001051 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -08001052 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -07001053 }
1054 *alertBytes = bytes;
1055 free(alertName);
1056 return res;
1057}
1058
1059int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1060 char *alertQuotaCmd;
1061 char *chainName;
1062 char *alertName;
1063 int res = 0;
1064
JP Abgrall69261cb2014-06-19 18:35:24 -07001065 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001066 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
1067 return -1;
1068 }
1069
JP Abgrall8a932722011-07-13 19:17:35 -07001070 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001071 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001072 return -1;
1073 }
1074
Jesper Hanssona9d791f2012-04-27 13:54:27 +02001075 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -07001076 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001077 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001078 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001079 free(alertQuotaCmd);
1080 free(chainName);
1081
1082 *alertBytes = 0;
1083 free(alertName);
1084 return res;
1085}
JP Abgralldb7da582011-09-18 12:57:32 -07001086
1087/*
1088 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001089 * Chain natctrl_tether_counters (4 references)
1090 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001091 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1092 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1093 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1094 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
1095 * It results in an error if invoked and no tethering counter rules exist. The constraint
1096 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001097 */
JP Abgrallbaeccc42013-06-25 09:44:10 -07001098int BandwidthController::parseForwardChainStats(SocketClient *cli, const TetherStats filter,
1099 FILE *fp, std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001100 int res;
1101 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
1102 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1103 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1104 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1105
JP Abgrallbaeccc42013-06-25 09:44:10 -07001106 TetherStats stats;
JP Abgralldb7da582011-09-18 12:57:32 -07001107 char *buffPtr;
1108 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001109 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001110
1111 bool filterPair = filter.intIface[0] && filter.extIface[0];
1112
1113 char *filterMsg = filter.getStatsLine();
1114 ALOGV("filter: %s", filterMsg);
1115 free(filterMsg);
1116
1117 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001118
1119 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
1120 /* Clean up, so a failed parse can still print info */
1121 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Mark Salyzynca0b5e22014-03-26 14:15:03 -07001122 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
JP Abgralldb7da582011-09-18 12:57:32 -07001123 &packets, &bytes, iface0, iface1, rest);
SynergyDev7776cea2014-03-16 15:48:51 -07001124 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 -07001125 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001126 extraProcessingInfo += buffPtr;
1127
JP Abgralldb7da582011-09-18 12:57:32 -07001128 if (res != 5) {
1129 continue;
1130 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001131 /*
1132 * The following assumes that the 1st rule has in:extIface out:intIface,
1133 * which is what NatController sets up.
1134 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1135 */
1136 if (filter.intIface[0] && filter.extIface[0]) {
1137 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001138 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 -07001139 stats.rxPackets = packets;
1140 stats.rxBytes = bytes;
1141 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001142 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 -07001143 stats.txPackets = packets;
1144 stats.txBytes = bytes;
1145 }
1146 } else if (filter.intIface[0] || filter.extIface[0]) {
1147 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001148 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 -07001149 stats.intIface = iface0;
1150 stats.extIface = iface1;
1151 stats.rxPackets = packets;
1152 stats.rxBytes = bytes;
1153 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001154 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 -07001155 stats.intIface = iface1;
1156 stats.extIface = iface0;
1157 stats.txPackets = packets;
1158 stats.txBytes = bytes;
1159 }
1160 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1161 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001162 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 -07001163 stats.intIface = iface0;
1164 stats.extIface = iface1;
1165 stats.rxPackets = packets;
1166 stats.rxBytes = bytes;
1167 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001168 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 -07001169 stats.txPackets = packets;
1170 stats.txBytes = bytes;
1171 }
1172 }
1173 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001174 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001175 /* Send out stats, and prep for the next if needed. */
1176 char *msg = stats.getStatsLine();
1177 if (filterPair) {
1178 cli->sendMsg(ResponseCode::TetheringStatsResult, msg, false);
1179 return 0;
1180 } else {
1181 cli->sendMsg(ResponseCode::TetheringStatsListResult, msg, false);
1182 stats = filter;
1183 }
1184 free(msg);
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001185 statsFound++;
JP Abgralldb7da582011-09-18 12:57:32 -07001186 }
1187 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001188
1189 /* It is always an error to find only one side of the stats. */
1190 /* It is an error to find nothing when not filtering. */
1191 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1192 (!statsFound && !filterPair)) {
1193 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001194 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001195 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1196 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001197}
1198
JP Abgrallbaeccc42013-06-25 09:44:10 -07001199char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001200 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001201 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001202 rxBytes, rxPackets, txBytes, txPackets);
1203 return msg;
1204}
1205
JP Abgrallbaeccc42013-06-25 09:44:10 -07001206int BandwidthController::getTetherStats(SocketClient *cli, TetherStats &stats, std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001207 int res;
1208 std::string fullCmd;
1209 FILE *iptOutput;
JP Abgralldb7da582011-09-18 12:57:32 -07001210
JP Abgralldb7da582011-09-18 12:57:32 -07001211 /*
1212 * Why not use some kind of lib to talk to iptables?
1213 * Because the only libs are libiptc and libip6tc in iptables, and they are
1214 * not easy to use. They require the known iptables match modules to be
1215 * preloaded/linked, and require apparently a lot of wrapper code to get
1216 * the wanted info.
1217 */
1218 fullCmd = IPTABLES_PATH;
Yusuke Sato99b40502015-08-19 13:47:30 -07001219 fullCmd += " -nvx -w -L ";
JP Abgrallbaeccc42013-06-25 09:44:10 -07001220 fullCmd += NatController::LOCAL_TETHER_COUNTERS_CHAIN;
JP Abgralldb7da582011-09-18 12:57:32 -07001221 iptOutput = popen(fullCmd.c_str(), "r");
1222 if (!iptOutput) {
Steve Block5ea0c052012-01-06 19:18:11 +00001223 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
JP Abgralla2a64f02011-11-11 20:36:16 -08001224 extraProcessingInfo += "Failed to run iptables.";
JP Abgralldb7da582011-09-18 12:57:32 -07001225 return -1;
1226 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001227 res = parseForwardChainStats(cli, stats, iptOutput, extraProcessingInfo);
JP Abgralldb7da582011-09-18 12:57:32 -07001228 pclose(iptOutput);
1229
1230 /* Currently NatController doesn't do ipv6 tethering, so we are done. */
1231 return res;
1232}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001233
1234void BandwidthController::flushExistingCostlyTables(bool doClean) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001235 std::string fullCmd;
1236 FILE *iptOutput;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001237
1238 /* Only lookup ip4 table names as ip6 will have the same tables ... */
1239 fullCmd = IPTABLES_PATH;
Yusuke Sato99b40502015-08-19 13:47:30 -07001240 fullCmd += " -w -S";
JP Abgrall0e540ec2013-08-26 15:13:10 -07001241 iptOutput = popen(fullCmd.c_str(), "r");
1242 if (!iptOutput) {
1243 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
1244 return;
1245 }
1246 /* ... then flush/clean both ip4 and ip6 iptables. */
1247 parseAndFlushCostlyTables(iptOutput, doClean);
1248 pclose(iptOutput);
1249}
1250
1251void BandwidthController::parseAndFlushCostlyTables(FILE *fp, bool doRemove) {
1252 int res;
1253 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
1254 char costlyIfaceName[MAX_IPT_OUTPUT_LINE_LEN];
1255 char cmd[MAX_CMD_LEN];
1256 char *buffPtr;
1257
1258 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
1259 costlyIfaceName[0] = '\0'; /* So that debugging output always works */
1260 res = sscanf(buffPtr, "-N bw_costly_%s", costlyIfaceName);
1261 ALOGV("parse res=%d costly=<%s> orig line=<%s>", res,
1262 costlyIfaceName, buffPtr);
1263 if (res != 1) {
1264 continue;
1265 }
1266 /* Exclusions: "shared" is not an ifacename */
1267 if (!strcmp(costlyIfaceName, "shared")) {
1268 continue;
1269 }
1270
1271 snprintf(cmd, sizeof(cmd), "-F bw_costly_%s", costlyIfaceName);
1272 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
1273 if (doRemove) {
1274 snprintf(cmd, sizeof(cmd), "-X bw_costly_%s", costlyIfaceName);
1275 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
1276 }
1277 }
1278}