OSDN Git Service

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