BandwidthController.cpp 38.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
// #define LOG_NDEBUG 0
18 19 20 21 22 23 24

/*
 * The CommandListener, FrameworkListener don't allow for
 * multiple calls in parallel to reach the BandwidthController.
 * If they ever were to allow it, then netd/ would need some tweaking.
 */

25
#include <errno.h>
26
#include <fcntl.h>
27
#include <stdio.h>
28
#include <stdlib.h>
29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <string.h>

#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/pkt_sched.h>

#define LOG_TAG "BandwidthController"
#include <cutils/log.h>
#include <cutils/properties.h>
43
#include <logwrap/logwrap.h>
44

45
#include "NetdConstants.h"
46
#include "BandwidthController.h"
47 48
#include "NatController.h"  /* For LOCAL_TETHER_COUNTERS_CHAIN */
#include "ResponseCode.h"
49

50
/* Alphabetical */
51
#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %lld --name %s"
52
const char BandwidthController::ALERT_GLOBAL_NAME[] = "globalAlert";
53 54 55 56 57
const char* BandwidthController::LOCAL_INPUT = "bw_INPUT";
const char* BandwidthController::LOCAL_FORWARD = "bw_FORWARD";
const char* BandwidthController::LOCAL_OUTPUT = "bw_OUTPUT";
const char* BandwidthController::LOCAL_RAW_PREROUTING = "bw_raw_PREROUTING";
const char* BandwidthController::LOCAL_MANGLE_POSTROUTING = "bw_mangle_POSTROUTING";
58 59 60 61 62
const int  BandwidthController::MAX_CMD_ARGS = 32;
const int  BandwidthController::MAX_CMD_LEN = 1024;
const int  BandwidthController::MAX_IFACENAME_LEN = 64;
const int  BandwidthController::MAX_IPT_OUTPUT_LINE_LEN = 256;

63 64 65 66
/**
 * Some comments about the rules:
 *  * Ordering
 *    - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
67
 *      E.g. "-I bw_INPUT -i rmnet0 --jump costly"
68
 *    - quota'd rules in the costly chain should be before penalty_box lookups.
69
 *    - happy_box rejects everything by default.
70
 *    - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
71 72 73 74
 *
 * * global quota vs per interface quota
 *   - global quota for all costly interfaces uses a single costly chain:
 *    . initial rules
75
 *      iptables -N costly_shared
76 77
 *      iptables -I bw_INPUT -i iface0 --jump costly_shared
 *      iptables -I bw_OUTPUT -o iface0 --jump costly_shared
78 79 80
 *      iptables -I costly_shared -m quota \! --quota 500000 \
 *          --jump REJECT --reject-with icmp-net-prohibited
 *      iptables -A costly_shared --jump penalty_box
81 82
 *      If the happy box is enabled,
 *        iptables -A penalty_box --jump happy_box
83
 *
84
 *    . adding a new iface to this, E.g.:
85 86
 *      iptables -I bw_INPUT -i iface1 --jump costly_shared
 *      iptables -I bw_OUTPUT -o iface1 --jump costly_shared
87 88 89 90
 *
 *   - quota per interface. This is achieve by having "costly" chains per quota.
 *     E.g. adding a new costly interface iface0 with its own quota:
 *      iptables -N costly_iface0
91 92
 *      iptables -I bw_INPUT -i iface0 --jump costly_iface0
 *      iptables -I bw_OUTPUT -o iface0 --jump costly_iface0
93
 *      iptables -A costly_iface0 -m quota \! --quota 500000 \
94
 *          --jump REJECT --reject-with icmp-port-unreachable
95
 *      iptables -A costly_iface0 --jump penalty_box
96 97 98
 *
 * * penalty_box handling:
 *  - only one penalty_box for all interfaces
99 100 101 102 103 104 105 106 107
 *   E.g  Adding an app, it has to preserve the appened happy_box, so "-I":
 *    iptables -I penalty_box -m owner --uid-owner app_3 \
 *        --jump REJECT --reject-with icmp-port-unreachable
 *
 * * happy_box handling:
 *  - The happy_box goes at the end of the penalty box.
 *   E.g  Adding a happy app,
 *    iptables -I happy_box -m owner --uid-owner app_3 \
 *        --jump RETURN
108
 */
109 110 111 112 113
const char *BandwidthController::IPT_FLUSH_COMMANDS[] = {
    /*
     * Cleanup rules.
     * Should normally include costly_<iface>, but we rely on the way they are setup
     * to allow coexistance.
114
     */
115 116 117
    "-F bw_INPUT",
    "-F bw_OUTPUT",
    "-F bw_FORWARD",
118
    "-F happy_box",
119 120
    "-F penalty_box",
    "-F costly_shared",
121

122 123 124 125
    /* Just a couple that are the most common. */
    "-F costly_rmnet0",
    "-F costly_wlan0",

126 127
    "-t raw -F bw_raw_PREROUTING",
    "-t mangle -F bw_mangle_POSTROUTING",
128 129 130 131
};

/* The cleanup commands assume flushing has been done. */
const char *BandwidthController::IPT_CLEANUP_COMMANDS[] = {
132
    "-X happy_box",
133 134
    "-X penalty_box",
    "-X costly_shared",
135 136 137 138

    /* Just a couple that are the most common. */
    "-X costly_rmnet0",
    "-X costly_wlan0",
139
};
140

141
const char *BandwidthController::IPT_SETUP_COMMANDS[] = {
142
    "-N happy_box",
143
    "-N penalty_box",
144
    "-N costly_shared",
145 146
};

147
const char *BandwidthController::IPT_BASIC_ACCOUNTING_COMMANDS[] = {
148
    "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
149

150
    "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
151

152
    "-A costly_shared --jump penalty_box",
153

154 155
    "-t raw -A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
    "-t mangle -A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
156
};
157 158 159 160

BandwidthController::BandwidthController(void) {
}

161
int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
162
                                         IptFailureLog failureHandling) {
163
    int res = 0;
164

165
    ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
166 167
    res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
    res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
168 169 170
    return res;
}

171 172 173 174 175 176 177
int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {

    memset(buffer, '\0', buffSize);  // strncpy() is not filling leftover with '\0'
    strncpy(buffer, src, buffSize);
    return buffer[buffSize - 1];
}

178
int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
179
                                        IptIpVer iptVer, IptFailureLog failureHandling) {
180
    char buffer[MAX_CMD_LEN];
181
    const char *argv[MAX_CMD_ARGS];
182
    int argc = 0;
183 184
    char *next = buffer;
    char *tmp;
185
    int res;
186
    int status = 0;
187

188
    std::string fullCmd = cmd;
189

190 191
    switch (jumpHandling) {
    case IptJumpReject:
192 193 194 195 196 197
        /*
         * Must be carefull what one rejects with, as uper layer protocols will just
         * keep on hammering the device until the number of retries are done.
         * For port-unreachable (default), TCP should consider as an abort (RFC1122).
         */
        fullCmd += " --jump REJECT";
198 199 200 201 202 203
        break;
    case IptJumpReturn:
        fullCmd += " --jump RETURN";
        break;
    case IptJumpNoAdd:
        break;
204 205
    }

206 207
    fullCmd.insert(0, " ");
    fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
208

209 210 211 212 213 214 215 216 217 218
    if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
        ALOGE("iptables command too long");
        return -1;
    }

    argc = 0;
    while ((tmp = strsep(&next, " "))) {
        argv[argc++] = tmp;
        if (argc >= MAX_CMD_ARGS) {
            ALOGE("iptables argument overflow");
219 220
            return -1;
        }
221
    }
222

223 224 225
    argv[argc] = NULL;
    res = android_fork_execvp(argc, (char **)argv, &status, false,
            failureHandling == IptFailShow);
226 227 228 229
    res = res || !WIFEXITED(status) || WEXITSTATUS(status);
    if (res && failureHandling == IptFailShow) {
      ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
            fullCmd.c_str());
230 231
    }
    return res;
232 233
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
int BandwidthController::setupIptablesHooks(void) {

    /* Some of the initialCommands are allowed to fail */
    runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
            IPT_FLUSH_COMMANDS, RunCmdFailureOk);

    runCommands(sizeof(IPT_CLEANUP_COMMANDS) / sizeof(char*),
            IPT_CLEANUP_COMMANDS, RunCmdFailureOk);

    runCommands(sizeof(IPT_SETUP_COMMANDS) / sizeof(char*),
            IPT_SETUP_COMMANDS, RunCmdFailureBad);

    return 0;
}

int BandwidthController::enableBandwidthControl(bool force) {
250
    int res;
251 252 253 254 255 256 257
    char value[PROPERTY_VALUE_MAX];

    if (!force) {
            property_get("persist.bandwidth.enable", value, "1");
            if (!strcmp(value, "0"))
                    return 0;
    }
258

259
    /* Let's pretend we started from scratch ... */
260 261 262
    sharedQuotaIfaces.clear();
    quotaIfaces.clear();
    naughtyAppUids.clear();
263
    niceAppUids.clear();
264
    globalAlertBytes = 0;
265
    globalAlertTetherCount = 0;
266 267
    sharedQuotaBytes = sharedAlertBytes = 0;

268 269
    res = runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
            IPT_FLUSH_COMMANDS, RunCmdFailureOk);
270

271
    res |= runCommands(sizeof(IPT_BASIC_ACCOUNTING_COMMANDS) / sizeof(char*),
272
            IPT_BASIC_ACCOUNTING_COMMANDS, RunCmdFailureBad);
273

274
    return res;
275 276 277 278

}

int BandwidthController::disableBandwidthControl(void) {
279 280
    runCommands(sizeof(IPT_FLUSH_COMMANDS) / sizeof(char*),
            IPT_FLUSH_COMMANDS, RunCmdFailureOk);
281
    return 0;
282 283
}

284 285
int BandwidthController::runCommands(int numCommands, const char *commands[],
                                     RunCmdErrHandling cmdErrHandling) {
286
    int res = 0;
287 288 289 290
    IptFailureLog failureLogging = IptFailShow;
    if (cmdErrHandling == RunCmdFailureOk) {
        failureLogging = IptFailHide;
    }
291
    ALOGV("runCommands(): %d commands", numCommands);
292
    for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
293
        res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
294
        if (res && cmdErrHandling != RunCmdFailureOk)
295 296
            return res;
    }
297
    return 0;
298 299
}

300
std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
301
    std::string res;
302 303
    char *buff;
    const char *opFlag;
304 305

    switch (op) {
306 307 308
    case IptOpInsert:
        opFlag = "-I";
        break;
309
    case IptOpAppend:
310 311 312
        ALOGE("Append op not supported for %s uids", chain);
        res = "";
        return res;
313
        break;
314 315 316 317 318 319 320
    case IptOpReplace:
        opFlag = "-R";
        break;
    default:
    case IptOpDelete:
        opFlag = "-D";
        break;
321
    }
322
    asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
323 324
    res = buff;
    free(buff);
325 326 327
    return res;
}

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
int BandwidthController::enableHappyBox(void) {
    char cmd[MAX_CMD_LEN];
    int res = 0;

    /*
     * We tentatively delete before adding, which helps recovering
     * from bad states (e.g. netd died).
     */

    /* Should not exist, but ignore result if already there. */
    snprintf(cmd, sizeof(cmd), "-N happy_box");
    runIpxtablesCmd(cmd, IptJumpNoAdd);

    /* Should be empty, but clear in case something was wrong. */
    niceAppUids.clear();
    snprintf(cmd, sizeof(cmd), "-F happy_box");
    res |= runIpxtablesCmd(cmd, IptJumpNoAdd);

    snprintf(cmd, sizeof(cmd), "-D penalty_box -j happy_box");
    runIpxtablesCmd(cmd, IptJumpNoAdd);
    snprintf(cmd, sizeof(cmd), "-A penalty_box -j happy_box");
    res |= runIpxtablesCmd(cmd, IptJumpNoAdd);

    /* Reject. Defaulting to prot-unreachable */
    snprintf(cmd, sizeof(cmd), "-D happy_box -j REJECT");
    runIpxtablesCmd(cmd, IptJumpNoAdd);
    snprintf(cmd, sizeof(cmd), "-A happy_box -j REJECT");
    res |= runIpxtablesCmd(cmd, IptJumpNoAdd);

    return res;
}

int BandwidthController::disableHappyBox(void) {
    char cmd[MAX_CMD_LEN];

    /* Best effort */
    snprintf(cmd, sizeof(cmd), "-D penalty_box -j happy_box");
    runIpxtablesCmd(cmd, IptJumpNoAdd);
    niceAppUids.clear();
    snprintf(cmd, sizeof(cmd), "-F happy_box");
    runIpxtablesCmd(cmd, IptJumpNoAdd);
    snprintf(cmd, sizeof(cmd), "-X happy_box");
    runIpxtablesCmd(cmd, IptJumpNoAdd);

    return 0;
}

375
int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
376
    return manipulateNaughtyApps(numUids, appUids, SpecialAppOpAdd);
377 378 379
}

int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
380
    return manipulateNaughtyApps(numUids, appUids, SpecialAppOpRemove);
381 382
}

383 384 385 386 387 388 389 390
int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
    return manipulateNiceApps(numUids, appUids, SpecialAppOpAdd);
}

int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
    return manipulateNiceApps(numUids, appUids, SpecialAppOpRemove);
}

391 392 393 394
int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
    return manipulateSpecialApps(numUids, appStrUids, "penalty_box", naughtyAppUids, IptJumpReject, appOp);
}

395 396 397 398
int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
    return manipulateSpecialApps(numUids, appStrUids, "happy_box", niceAppUids, IptJumpReturn, appOp);
}

399 400 401 402 403 404

int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
                                               const char *chain,
                                               std::list<int /*appUid*/> &specialAppUids,
                                               IptJumpOp jumpHandling, SpecialAppOp appOp) {

405 406
    char cmd[MAX_CMD_LEN];
    int uidNum;
407 408
    const char *failLogTemplate;
    IptOp op;
409
    int appUids[numUids];
410
    std::string iptCmd;
411
    std::list<int /*uid*/>::iterator it;
412

413
    switch (appOp) {
414
    case SpecialAppOpAdd:
415
        op = IptOpInsert;
416
        failLogTemplate = "Failed to add app uid %s(%d) to %s.";
417
        break;
418
    case SpecialAppOpRemove:
419
        op = IptOpDelete;
420
        failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
421
        break;
422 423 424
    default:
        ALOGE("Unexpected app Op %d", appOp);
        return -1;
425 426
    }

427
    for (uidNum = 0; uidNum < numUids; uidNum++) {
428 429 430 431
        char *end;
        appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
        if (*end || !*appStrUids[uidNum]) {
            ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
432 433 434 435 436
            goto fail_parse;
        }
    }

    for (uidNum = 0; uidNum < numUids; uidNum++) {
437
        int uid = appUids[uidNum];
438
        for (it = specialAppUids.begin(); it != specialAppUids.end(); it++) {
439 440 441
            if (*it == uid)
                break;
        }
442
        bool found = (it != specialAppUids.end());
443

444
        if (appOp == SpecialAppOpRemove) {
445 446 447 448
            if (!found) {
                ALOGE("No such appUid %d to remove", uid);
                return -1;
            }
449
            specialAppUids.erase(it);
450 451 452 453 454
        } else {
            if (found) {
                ALOGE("appUid %d exists already", uid);
                return -1;
            }
455
            specialAppUids.push_front(uid);
456 457
        }

458 459
        iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
        if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
460
            ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
461 462 463 464 465
            goto fail_with_uidNum;
        }
    }
    return 0;

466
fail_with_uidNum:
467
    /* Try to remove the uid that failed in any case*/
468 469
    iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
    runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
470 471
fail_parse:
    return -1;
472 473
}

474
std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
475
    std::string res;
476 477
    char *buff;
    const char *opFlag;
478

479
    ALOGV("makeIptablesQuotaCmd(%d, %lld)", op, quota);
480

481
    switch (op) {
482 483 484
    case IptOpInsert:
        opFlag = "-I";
        break;
485 486 487
    case IptOpAppend:
        opFlag = "-A";
        break;
488 489 490 491 492 493 494
    case IptOpReplace:
        opFlag = "-R";
        break;
    default:
    case IptOpDelete:
        opFlag = "-D";
        break;
495
    }
496

497
    // The requried IP version specific --jump REJECT ... will be added later.
498 499 500 501
    asprintf(&buff, "%s costly_%s -m quota2 ! --quota %lld --name %s", opFlag, costName, quota,
             costName);
    res = buff;
    free(buff);
502 503 504
    return res;
}

505
int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
506
    char cmd[MAX_CMD_LEN];
507
    int res = 0, res1, res2;
508
    int ruleInsertPos = 1;
509 510 511 512
    std::string costString;
    const char *costCString;

    /* The "-N costly" is created upfront, no need to handle it here. */
513 514
    switch (quotaType) {
    case QuotaUnique:
515
        costString = "costly_";
516 517
        costString += ifn;
        costCString = costString.c_str();
518 519 520 521 522 523
        /*
         * Flush the costly_<iface> is allowed to fail in case it didn't exist.
         * Creating a new one is allowed to fail in case it existed.
         * This helps with netd restarts.
         */
        snprintf(cmd, sizeof(cmd), "-F %s", costCString);
524
        res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
525
        snprintf(cmd, sizeof(cmd), "-N %s", costCString);
526
        res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
527 528
        res = (res1 && res2) || (!res1 && !res2);

529
        snprintf(cmd, sizeof(cmd), "-A %s -j penalty_box", costCString);
530
        res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
531 532
        break;
    case QuotaShared:
533
        costCString = "costly_shared";
534
        break;
535 536 537
    default:
        ALOGE("Unexpected quotatype %d", quotaType);
        return -1;
538 539
    }

540 541 542 543
    if (globalAlertBytes) {
        /* The alert rule comes 1st */
        ruleInsertPos = 2;
    }
544 545

    snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
546
    runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
547 548

    snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
549
    res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
550 551

    snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
552
    runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
553 554

    snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
555
    res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
556 557 558
    return res;
}

559
int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
560 561 562 563 564
    char cmd[MAX_CMD_LEN];
    int res = 0;
    std::string costString;
    const char *costCString;

565 566
    switch (quotaType) {
    case QuotaUnique:
567
        costString = "costly_";
568 569
        costString += ifn;
        costCString = costString.c_str();
570 571
        break;
    case QuotaShared:
572
        costCString = "costly_shared";
573
        break;
574 575 576
    default:
        ALOGE("Unexpected quotatype %d", quotaType);
        return -1;
577 578
    }

579
    snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
580
    res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
581
    snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
582
    res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
583

584
    /* The "-N costly_shared" is created upfront, no need to handle it here. */
585
    if (quotaType == QuotaUnique) {
586
        snprintf(cmd, sizeof(cmd), "-F %s", costCString);
587
        res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
588
        snprintf(cmd, sizeof(cmd), "-X %s", costCString);
589
        res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
590 591 592
    }
    return res;
}
593

594
int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
595 596
    char cmd[MAX_CMD_LEN];
    char ifn[MAX_IFACENAME_LEN];
597
    int res = 0;
598
    std::string quotaCmd;
599 600
    std::string ifaceName;
    ;
601
    const char *costName = "shared";
602
    std::list<std::string>::iterator it;
603

604 605
    if (!maxBytes) {
        /* Don't talk about -1, deprecate it. */
606
        ALOGE("Invalid bytes value. 1..max_int64.");
607 608
        return -1;
    }
609
    if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
610
        ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
611 612 613
        return -1;
    }
    ifaceName = ifn;
614 615

    if (maxBytes == -1) {
616
        return removeInterfaceSharedQuota(ifn);
617 618 619
    }

    /* Insert ingress quota. */
620 621
    for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
        if (*it == ifaceName)
622
            break;
623
    }
624

625
    if (it == sharedQuotaIfaces.end()) {
626
        res |= prepCostlyIface(ifn, QuotaShared);
627 628
        if (sharedQuotaIfaces.empty()) {
            quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
629
            res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
630
            if (res) {
631
                ALOGE("Failed set quota rule");
632
                goto fail;
633
            }
634 635
            sharedQuotaBytes = maxBytes;
        }
636
        sharedQuotaIfaces.push_front(ifaceName);
637 638 639 640

    }

    if (maxBytes != sharedQuotaBytes) {
641
        res |= updateQuota(costName, maxBytes);
642
        if (res) {
643
            ALOGE("Failed update quota for %s", costName);
644 645 646
            goto fail;
        }
        sharedQuotaBytes = maxBytes;
647 648
    }
    return 0;
649 650

    fail:
651 652 653
    /*
     * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
     * rules in the kernel to see which ones need cleaning up.
654 655
     * For now callers needs to choose if they want to "ndc bandwidth enable"
     * which resets everything.
656
     */
657
    removeInterfaceSharedQuota(ifn);
658 659 660
    return -1;
}

661
/* It will also cleanup any shared alerts */
662
int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
663
    char ifn[MAX_IFACENAME_LEN];
664
    int res = 0;
665
    std::string ifaceName;
666
    std::list<std::string>::iterator it;
667
    const char *costName = "shared";
668

669
    if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
670
        ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
671 672
        return -1;
    }
673
    ifaceName = ifn;
674

675 676
    for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
        if (*it == ifaceName)
677
            break;
678
    }
679
    if (it == sharedQuotaIfaces.end()) {
680
        ALOGE("No such iface %s to delete", ifn);
681
        return -1;
682
    }
683

684
    res |= cleanupCostlyIface(ifn, QuotaShared);
685
    sharedQuotaIfaces.erase(it);
686

687
    if (sharedQuotaIfaces.empty()) {
688
        std::string quotaCmd;
689
        quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
690
        res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
691 692 693 694 695
        sharedQuotaBytes = 0;
        if (sharedAlertBytes) {
            removeSharedAlert();
            sharedAlertBytes = 0;
        }
696
    }
697 698
    return res;
}
699 700 701 702

int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
    char ifn[MAX_IFACENAME_LEN];
    int res = 0;
703 704 705 706
    std::string ifaceName;
    const char *costName;
    std::list<QuotaInfo>::iterator it;
    std::string quotaCmd;
707

708 709
    if (!maxBytes) {
        /* Don't talk about -1, deprecate it. */
710
        ALOGE("Invalid bytes value. 1..max_int64.");
711 712
        return -1;
    }
713
    if (maxBytes == -1) {
714
        return removeInterfaceQuota(iface);
715 716
    }

717
    if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
718
        ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
719 720 721 722 723
        return -1;
    }
    ifaceName = ifn;
    costName = iface;

724 725
    /* Insert ingress quota. */
    for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
726
        if (it->ifaceName == ifaceName)
727 728 729 730
            break;
    }

    if (it == quotaIfaces.end()) {
731
        /* Preparing the iface adds a penalty/happy box check */
732
        res |= prepCostlyIface(ifn, QuotaUnique);
733
        /*
734
         * The rejecting quota limit should go after the penalty/happy box checks
735 736 737
         * or else a naughty app could just eat up the quota.
         * So we append here.
         */
738
        quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
739
        res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
740
        if (res) {
741
            ALOGE("Failed set quota rule");
742 743 744
            goto fail;
        }

745
        quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
746 747

    } else {
748
        res |= updateQuota(costName, maxBytes);
749
        if (res) {
750
            ALOGE("Failed update quota for %s", iface);
751 752
            goto fail;
        }
753
        it->quota = maxBytes;
754 755 756 757 758 759 760 761 762 763 764 765 766 767
    }
    return 0;

    fail:
    /*
     * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
     * rules in the kernel to see which ones need cleaning up.
     * For now callers needs to choose if they want to "ndc bandwidth enable"
     * which resets everything.
     */
    removeInterfaceSharedQuota(ifn);
    return -1;
}

768 769 770 771 772 773 774 775 776 777 778 779 780
int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
    return getInterfaceQuota("shared", bytes);
}

int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
    FILE *fp;
    char *fname;
    int scanRes;

    asprintf(&fname, "/proc/net/xt_quota/%s", costName);
    fp = fopen(fname, "r");
    free(fname);
    if (!fp) {
781
        ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
782 783 784
        return -1;
    }
    scanRes = fscanf(fp, "%lld", bytes);
785
    ALOGV("Read quota res=%d bytes=%lld", scanRes, *bytes);
786 787 788 789
    fclose(fp);
    return scanRes == 1 ? 0 : -1;
}

790 791 792 793
int BandwidthController::removeInterfaceQuota(const char *iface) {

    char ifn[MAX_IFACENAME_LEN];
    int res = 0;
794 795 796
    std::string ifaceName;
    const char *costName;
    std::list<QuotaInfo>::iterator it;
797

798
    if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
799
        ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
800 801 802 803
        return -1;
    }
    ifaceName = ifn;
    costName = iface;
804 805

    for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
806
        if (it->ifaceName == ifaceName)
807 808 809 810
            break;
    }

    if (it == quotaIfaces.end()) {
811
        ALOGE("No such iface %s to delete", ifn);
812 813 814 815
        return -1;
    }

    /* This also removes the quota command of CostlyIface chain. */
816
    res |= cleanupCostlyIface(ifn, QuotaUnique);
817 818 819 820 821

    quotaIfaces.erase(it);

    return res;
}
822 823 824 825 826 827 828 829 830

int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
    FILE *fp;
    char *fname;

    asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
    fp = fopen(fname, "w");
    free(fname);
    if (!fp) {
831
        ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
        return -1;
    }
    fprintf(fp, "%lld\n", bytes);
    fclose(fp);
    return 0;
}

int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
    int res = 0;
    const char *opFlag;
    char *alertQuotaCmd;

    switch (op) {
    case IptOpInsert:
        opFlag = "-I";
        break;
848 849 850
    case IptOpAppend:
        opFlag = "-A";
        break;
851 852 853 854 855 856 857 858 859
    case IptOpReplace:
        opFlag = "-R";
        break;
    default:
    case IptOpDelete:
        opFlag = "-D";
        break;
    }

860
    asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
861
        bytes, alertName);
862
    res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
863
    free(alertQuotaCmd);
864
    asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
865
        bytes, alertName);
866
    res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
867 868 869 870
    free(alertQuotaCmd);
    return res;
}

871 872 873
int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
    int res = 0;
    const char *opFlag;
874
    char *alertQuotaCmd;
875 876 877 878 879

    switch (op) {
    case IptOpInsert:
        opFlag = "-I";
        break;
880 881 882
    case IptOpAppend:
        opFlag = "-A";
        break;
883 884 885 886 887 888 889 890 891
    case IptOpReplace:
        opFlag = "-R";
        break;
    default:
    case IptOpDelete:
        opFlag = "-D";
        break;
    }

892
    asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
893
        bytes, alertName);
894
    res = runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
895 896 897 898 899 900
    free(alertQuotaCmd);
    return res;
}

int BandwidthController::setGlobalAlert(int64_t bytes) {
    const char *alertName = ALERT_GLOBAL_NAME;
901 902 903
    int res = 0;

    if (!bytes) {
904
        ALOGE("Invalid bytes value. 1..max_int64.");
905 906 907 908 909 910
        return -1;
    }
    if (globalAlertBytes) {
        res = updateQuota(alertName, bytes);
    } else {
        res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
911
        if (globalAlertTetherCount) {
912
            ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
913 914
            res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
        }
915 916 917 918 919
    }
    globalAlertBytes = bytes;
    return res;
}

920 921 922 923 924
int BandwidthController::setGlobalAlertInForwardChain(void) {
    const char *alertName = ALERT_GLOBAL_NAME;
    int res = 0;

    globalAlertTetherCount++;
925
    ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940

    /*
     * If there is no globalAlert active we are done.
     * If there is an active globalAlert but this is not the 1st
     * tether, we are also done.
     */
    if (!globalAlertBytes || globalAlertTetherCount != 1) {
        return 0;
    }

    /* We only add the rule if this was the 1st tether added. */
    res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
    return res;
}

941 942
int BandwidthController::removeGlobalAlert(void) {

943
    const char *alertName = ALERT_GLOBAL_NAME;
944 945 946
    int res = 0;

    if (!globalAlertBytes) {
947
        ALOGE("No prior alert set");
948 949 950
        return -1;
    }
    res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
951 952 953
    if (globalAlertTetherCount) {
        res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
    }
954 955 956 957
    globalAlertBytes = 0;
    return res;
}

958 959 960 961 962
int BandwidthController::removeGlobalAlertInForwardChain(void) {
    int res = 0;
    const char *alertName = ALERT_GLOBAL_NAME;

    if (!globalAlertTetherCount) {
963
        ALOGE("No prior alert set");
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
        return -1;
    }

    globalAlertTetherCount--;
    /*
     * If there is no globalAlert active we are done.
     * If there is an active globalAlert but there are more
     * tethers, we are also done.
     */
    if (!globalAlertBytes || globalAlertTetherCount >= 1) {
        return 0;
    }

    /* We only detete the rule if this was the last tether removed. */
    res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
    return res;
}

982 983
int BandwidthController::setSharedAlert(int64_t bytes) {
    if (!sharedQuotaBytes) {
984
        ALOGE("Need to have a prior shared quota set to set an alert");
985 986 987
        return -1;
    }
    if (!bytes) {
988
        ALOGE("Invalid bytes value. 1..max_int64.");
989 990 991 992 993 994 995 996 997 998 999 1000 1001
        return -1;
    }
    return setCostlyAlert("shared", bytes, &sharedAlertBytes);
}

int BandwidthController::removeSharedAlert(void) {
    return removeCostlyAlert("shared", &sharedAlertBytes);
}

int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
    std::list<QuotaInfo>::iterator it;

    if (!bytes) {
1002
        ALOGE("Invalid bytes value. 1..max_int64.");
1003 1004 1005 1006 1007 1008 1009 1010
        return -1;
    }
    for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
        if (it->ifaceName == iface)
            break;
    }

    if (it == quotaIfaces.end()) {
1011
        ALOGE("Need to have a prior interface quota set to set an alert");
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        return -1;
    }

    return setCostlyAlert(iface, bytes, &it->alert);
}

int BandwidthController::removeInterfaceAlert(const char *iface) {
    std::list<QuotaInfo>::iterator it;

    for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
        if (it->ifaceName == iface)
            break;
    }

    if (it == quotaIfaces.end()) {
1027
        ALOGE("No prior alert set for interface %s", iface);
1028 1029 1030 1031 1032 1033 1034 1035
        return -1;
    }

    return removeCostlyAlert(iface, &it->alert);
}

int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
    char *alertQuotaCmd;
1036
    char *chainName;
1037 1038 1039 1040
    int res = 0;
    char *alertName;

    if (!bytes) {
1041
        ALOGE("Invalid bytes value. 1..max_int64.");
1042 1043 1044 1045 1046 1047
        return -1;
    }
    asprintf(&alertName, "%sAlert", costName);
    if (*alertBytes) {
        res = updateQuota(alertName, *alertBytes);
    } else {
1048 1049
        asprintf(&chainName, "costly_%s", costName);
        asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
1050
        res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
1051
        free(alertQuotaCmd);
1052
        free(chainName);
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    }
    *alertBytes = bytes;
    free(alertName);
    return res;
}

int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
    char *alertQuotaCmd;
    char *chainName;
    char *alertName;
    int res = 0;

    asprintf(&alertName, "%sAlert", costName);
    if (!*alertBytes) {
1067
        ALOGE("No prior alert set for %s alert", costName);
1068 1069 1070 1071
        return -1;
    }

    asprintf(&chainName, "costly_%s", costName);
1072
    asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
1073
    res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
1074 1075 1076 1077 1078 1079 1080
    free(alertQuotaCmd);
    free(chainName);

    *alertBytes = 0;
    free(alertName);
    return res;
}
1081 1082 1083

/*
 * Parse the ptks and bytes out of:
1084 1085 1086 1087 1088 1089
 *   Chain natctrl_tether_counters (4 references)
 *       pkts      bytes target     prot opt in     out     source               destination
 *         26     2373 RETURN     all  --  wlan0  rmnet0  0.0.0.0/0            0.0.0.0/0            counter wlan0_rmnet0: 0 bytes
 *         27     2002 RETURN     all  --  rmnet0 wlan0   0.0.0.0/0            0.0.0.0/0            counter rmnet0_wlan0: 0 bytes
 *       1040   107471 RETURN     all  --  bt-pan rmnet0  0.0.0.0/0            0.0.0.0/0            counter bt-pan_rmnet0: 0 bytes
 *       1450  1708806 RETURN     all  --  rmnet0 bt-pan  0.0.0.0/0            0.0.0.0/0            counter rmnet0_bt-pan: 0 bytes
1090
 */
1091 1092
int BandwidthController::parseForwardChainStats(SocketClient *cli, const TetherStats filter,
                                                FILE *fp, std::string &extraProcessingInfo) {
1093 1094 1095 1096 1097 1098
    int res;
    char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
    char iface0[MAX_IPT_OUTPUT_LINE_LEN];
    char iface1[MAX_IPT_OUTPUT_LINE_LEN];
    char rest[MAX_IPT_OUTPUT_LINE_LEN];

1099
    TetherStats stats;
1100 1101
    char *buffPtr;
    int64_t packets, bytes;
1102 1103 1104 1105 1106 1107 1108 1109 1110
    int statsFound = 0;

    bool filterPair = filter.intIface[0] && filter.extIface[0];

    char *filterMsg = filter.getStatsLine();
    ALOGV("filter: %s",  filterMsg);
    free(filterMsg);

    stats = filter;
1111 1112 1113 1114

    while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
        /* Clean up, so a failed parse can still print info */
        iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
1115
        res = sscanf(buffPtr, "%lld %lld RETURN all -- %s %s 0.%s",
1116
                &packets, &bytes, iface0, iface1, rest);
1117
        ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%lld bytes=%lld rest=<%s> orig line=<%s>", res,
1118
             iface0, iface1, packets, bytes, rest, buffPtr);
1119 1120
        extraProcessingInfo += buffPtr;

1121 1122 1123
        if (res != 5) {
            continue;
        }
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        /*
         * The following assumes that the 1st rule has in:extIface out:intIface,
         * which is what NatController sets up.
         * If not filtering, the 1st match rx, and sets up the pair for the tx side.
         */
        if (filter.intIface[0] && filter.extIface[0]) {
            if (filter.intIface == iface0 && filter.extIface == iface1) {
                ALOGV("2Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
                stats.rxPackets = packets;
                stats.rxBytes = bytes;
            } else if (filter.intIface == iface1 && filter.extIface == iface0) {
                ALOGV("2Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
                stats.txPackets = packets;
                stats.txBytes = bytes;
            }
        } else if (filter.intIface[0] || filter.extIface[0]) {
            if (filter.intIface == iface0 || filter.extIface == iface1) {
                ALOGV("1Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
                stats.intIface = iface0;
                stats.extIface = iface1;
                stats.rxPackets = packets;
                stats.rxBytes = bytes;
            } else if (filter.intIface == iface1 || filter.extIface == iface0) {
                ALOGV("1Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
                stats.intIface = iface1;
                stats.extIface = iface0;
                stats.txPackets = packets;
                stats.txBytes = bytes;
            }
        } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
            if (!stats.intIface[0]) {
                ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
                stats.intIface = iface0;
                stats.extIface = iface1;
                stats.rxPackets = packets;
                stats.rxBytes = bytes;
            } else if (stats.intIface == iface1 && stats.extIface == iface0) {
                ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%lld rx_packets=%lld ", iface0, iface1, bytes, packets);
                stats.txPackets = packets;
                stats.txBytes = bytes;
            }
        }
        if (stats.rxBytes != -1 && stats.txBytes != -1) {
            ALOGV("rx_bytes=%lld tx_bytes=%lld filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
            /* Send out stats, and prep for the next if needed. */
            char *msg = stats.getStatsLine();
            if (filterPair) {
                cli->sendMsg(ResponseCode::TetheringStatsResult, msg, false);
                return 0;
            } else {
                cli->sendMsg(ResponseCode::TetheringStatsListResult, msg, false);
                stats = filter;
            }
            free(msg);
            statsFound++;
1179 1180
        }
    }
1181 1182 1183 1184 1185 1186
    /* We found some stats, and the last one isn't a partial stats. */
    if (statsFound && (stats.rxBytes == -1 || stats.txBytes == -1)) {
        cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
        return 0;
    }
    return -1;
1187 1188
}

1189
char *BandwidthController::TetherStats::getStatsLine(void) const {
1190
    char *msg;
1191
    asprintf(&msg, "%s %s %lld %lld %lld %lld", intIface.c_str(), extIface.c_str(),
1192 1193 1194 1195
            rxBytes, rxPackets, txBytes, txPackets);
    return msg;
}

1196
int BandwidthController::getTetherStats(SocketClient *cli, TetherStats &stats, std::string &extraProcessingInfo) {
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    int res;
    std::string fullCmd;
    FILE *iptOutput;
    const char *cmd;

    /*
     * Why not use some kind of lib to talk to iptables?
     * Because the only libs are libiptc and libip6tc in iptables, and they are
     * not easy to use. They require the known iptables match modules to be
     * preloaded/linked, and require apparently a lot of wrapper code to get
     * the wanted info.
     */
    fullCmd = IPTABLES_PATH;
1210 1211
    fullCmd += " -nvx -L ";
    fullCmd += NatController::LOCAL_TETHER_COUNTERS_CHAIN;
1212 1213
    iptOutput = popen(fullCmd.c_str(), "r");
    if (!iptOutput) {
1214
            ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
1215
            extraProcessingInfo += "Failed to run iptables.";
1216 1217
        return -1;
    }
1218
    res = parseForwardChainStats(cli, stats, iptOutput, extraProcessingInfo);
1219 1220 1221 1222 1223
    pclose(iptOutput);

    /* Currently NatController doesn't do ipv6 tethering, so we are done. */
    return res;
}