Home | History | Annotate | Download | only in server
      1 /*
      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 #ifndef _BANDWIDTH_CONTROLLER_H
     17 #define _BANDWIDTH_CONTROLLER_H
     18 
     19 #include <list>
     20 #include <string>
     21 #include <utility>  // for pair
     22 
     23 #include <sysutils/SocketClient.h>
     24 #include <utils/RWLock.h>
     25 
     26 #include "NetdConstants.h"
     27 
     28 class BandwidthController {
     29 public:
     30     android::RWLock lock;
     31 
     32     class TetherStats {
     33     public:
     34         TetherStats(void)
     35                 : rxBytes(-1), rxPackets(-1),
     36                     txBytes(-1), txPackets(-1) {};
     37         TetherStats(std::string intIfn, std::string extIfn,
     38                 int64_t rxB, int64_t rxP,
     39                 int64_t txB, int64_t txP)
     40                         : intIface(intIfn), extIface(extIfn),
     41                             rxBytes(rxB), rxPackets(rxP),
     42                             txBytes(txB), txPackets(txP) {};
     43         /* Internal interface. Same as NatController's notion. */
     44         std::string intIface;
     45         /* External interface. Same as NatController's notion. */
     46         std::string extIface;
     47         int64_t rxBytes, rxPackets;
     48         int64_t txBytes, txPackets;
     49         /*
     50          * Allocates a new string representing this:
     51          * intIface extIface rx_bytes rx_packets tx_bytes tx_packets
     52          * The caller is responsible for free()'ing the returned ptr.
     53          */
     54         char *getStatsLine(void) const;
     55 
     56         bool addStatsIfMatch(const TetherStats& other) {
     57             if (intIface == other.intIface && extIface == other.extIface) {
     58                 rxBytes   += other.rxBytes;
     59                 rxPackets += other.rxPackets;
     60                 txBytes   += other.txBytes;
     61                 txPackets += other.txPackets;
     62                 return true;
     63             }
     64             return false;
     65         }
     66     };
     67 
     68     BandwidthController();
     69 
     70     int setupIptablesHooks(void);
     71 
     72     int enableBandwidthControl(bool force);
     73     int disableBandwidthControl(void);
     74     int enableDataSaver(bool enable);
     75 
     76     int setInterfaceSharedQuota(const char *iface, int64_t bytes);
     77     int getInterfaceSharedQuota(int64_t *bytes);
     78     int removeInterfaceSharedQuota(const char *iface);
     79 
     80     int setInterfaceQuota(const char *iface, int64_t bytes);
     81     int getInterfaceQuota(const char *iface, int64_t *bytes);
     82     int removeInterfaceQuota(const char *iface);
     83 
     84     int addNaughtyApps(int numUids, char *appUids[]);
     85     int removeNaughtyApps(int numUids, char *appUids[]);
     86     int addNiceApps(int numUids, char *appUids[]);
     87     int removeNiceApps(int numUids, char *appUids[]);
     88 
     89     int setGlobalAlert(int64_t bytes);
     90     int removeGlobalAlert(void);
     91     int setGlobalAlertInForwardChain(void);
     92     int removeGlobalAlertInForwardChain(void);
     93 
     94     int setSharedAlert(int64_t bytes);
     95     int removeSharedAlert(void);
     96 
     97     int setInterfaceAlert(const char *iface, int64_t bytes);
     98     int removeInterfaceAlert(const char *iface);
     99 
    100     /*
    101      * For single pair of ifaces, stats should have ifaceIn and ifaceOut initialized.
    102      * For all pairs, stats should have ifaceIn=ifaceOut="".
    103      * Sends out to the cli the single stat (TetheringStatsReluts) or a list of stats
    104      * (TetheringStatsListResult+CommandOkay).
    105      * Error is to be handled on the outside.
    106      * It results in an error if invoked and no tethering counter rules exist.
    107      */
    108     int getTetherStats(SocketClient *cli, TetherStats &stats, std::string &extraProcessingInfo);
    109 
    110     static const char* LOCAL_INPUT;
    111     static const char* LOCAL_FORWARD;
    112     static const char* LOCAL_OUTPUT;
    113     static const char* LOCAL_RAW_PREROUTING;
    114     static const char* LOCAL_MANGLE_POSTROUTING;
    115 
    116 protected:
    117     class QuotaInfo {
    118     public:
    119       QuotaInfo(std::string ifn, int64_t q, int64_t a)
    120               : ifaceName(ifn), quota(q), alert(a) {};
    121         std::string ifaceName;
    122         int64_t quota;
    123         int64_t alert;
    124     };
    125 
    126     enum IptIpVer { IptIpV4, IptIpV6 };
    127     enum IptOp { IptOpInsert, IptOpReplace, IptOpDelete, IptOpAppend };
    128     enum IptJumpOp { IptJumpReject, IptJumpReturn, IptJumpNoAdd };
    129     enum SpecialAppOp { SpecialAppOpAdd, SpecialAppOpRemove };
    130     enum QuotaType { QuotaUnique, QuotaShared };
    131     enum RunCmdErrHandling { RunCmdFailureBad, RunCmdFailureOk };
    132 #if LOG_NDEBUG
    133     enum IptFailureLog { IptFailShow, IptFailHide };
    134 #else
    135     enum IptFailureLog { IptFailShow, IptFailHide = IptFailShow };
    136 #endif
    137 
    138     int manipulateSpecialApps(int numUids, char *appStrUids[],
    139                                const char *chain,
    140                                IptJumpOp jumpHandling, SpecialAppOp appOp);
    141     int manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp);
    142     int manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp);
    143 
    144     int prepCostlyIface(const char *ifn, QuotaType quotaType);
    145     int cleanupCostlyIface(const char *ifn, QuotaType quotaType);
    146 
    147     std::string makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain);
    148     std::string makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota);
    149 
    150     int runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes);
    151     int runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes);
    152 
    153     /* Runs for both ipv4 and ipv6 iptables */
    154     int runCommands(int numCommands, const char *commands[], RunCmdErrHandling cmdErrHandling);
    155     /* Runs for both ipv4 and ipv6 iptables, appends -j REJECT --reject-with ...  */
    156     static int runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
    157                                IptFailureLog failureHandling = IptFailShow);
    158     static int runIptablesCmd(const char *cmd, IptJumpOp jumpHandling, IptIpVer iptIpVer,
    159                               IptFailureLog failureHandling = IptFailShow);
    160 
    161 
    162     // Provides strncpy() + check overflow.
    163     static int StrncpyAndCheck(char *buffer, const char *src, size_t buffSize);
    164 
    165     int updateQuota(const char *alertName, int64_t bytes);
    166 
    167     int setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes);
    168     int removeCostlyAlert(const char *costName, int64_t *alertBytes);
    169 
    170     typedef std::vector<TetherStats> TetherStatsList;
    171 
    172     static void addStats(TetherStatsList& statsList, const TetherStats& stats);
    173 
    174     static int addForwardChainStats(const TetherStats& filter,
    175                                     TetherStatsList& statsList, FILE *fp,
    176                                     std::string &extraProcessingInfo);
    177 
    178 
    179     /*
    180      * stats should never have only intIface initialized. Other 3 combos are ok.
    181      * fp should be a file to the apropriate FORWARD chain of iptables rules.
    182      * extraProcessingInfo: contains raw parsed data, and error info.
    183      * This strongly requires that setup of the rules is in a specific order:
    184      *  in:intIface out:extIface
    185      *  in:extIface out:intIface
    186      * and the rules are grouped in pairs when more that one tethering was setup.
    187      */
    188     static int parseForwardChainStats(SocketClient *cli, const TetherStats filter, FILE *fp,
    189                                       std::string &extraProcessingInfo);
    190 
    191     /*
    192      * Attempt to find the bw_costly_* tables that need flushing,
    193      * and flush them.
    194      * If doClean then remove the tables also.
    195      * Deals with both ip4 and ip6 tables.
    196      */
    197     void flushExistingCostlyTables(bool doClean);
    198     static void parseAndFlushCostlyTables(FILE *fp, bool doRemove);
    199 
    200     /*
    201      * Attempt to flush our tables.
    202      * If doClean then remove them also.
    203      * Deals with both ip4 and ip6 tables.
    204      */
    205     void flushCleanTables(bool doClean);
    206 
    207     /*------------------*/
    208 
    209     std::list<std::string> sharedQuotaIfaces;
    210     int64_t sharedQuotaBytes;
    211     int64_t sharedAlertBytes;
    212     int64_t globalAlertBytes;
    213     /*
    214      * This tracks the number of tethers setup.
    215      * The FORWARD chain is updated in the following cases:
    216      *  - The 1st time a globalAlert is setup and there are tethers setup.
    217      *  - Anytime a globalAlert is removed and there are tethers setup.
    218      *  - The 1st tether is setup and there is a globalAlert active.
    219      *  - The last tether is removed and there is a globalAlert active.
    220      */
    221     int globalAlertTetherCount;
    222 
    223     std::list<QuotaInfo> quotaIfaces;
    224 
    225     // For testing.
    226     friend class BandwidthControllerTest;
    227     static int (*execFunction)(int, char **, int *, bool, bool);
    228     static FILE *(*popenFunction)(const char *, const char *);
    229     static int (*iptablesRestoreFunction)(IptablesTarget, const std::string&);
    230 };
    231 
    232 #endif
    233