OSDN Git Service

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