• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef NET_CONN_SERVICE_H
17 #define NET_CONN_SERVICE_H
18 
19 #include <functional>
20 #include <list>
21 #include <memory>
22 #include <mutex>
23 #include <string>
24 #include <vector>
25 
26 #include "singleton.h"
27 #include "system_ability.h"
28 
29 #include "http_proxy.h"
30 #include "net_activate.h"
31 #include "net_conn_event_handler.h"
32 #include "net_conn_service_iface.h"
33 #include "net_conn_service_stub.h"
34 #include "net_score.h"
35 #include "net_supplier.h"
36 #include "netsys_controller_callback.h"
37 #include "network.h"
38 #include "dns_result_call_back.h"
39 #include "net_factoryreset_callback.h"
40 
41 namespace OHOS {
42 namespace NetManagerStandard {
43 
44 class NetConnService : public SystemAbility,
45                        public INetActivateCallback,
46                        public NetConnServiceStub,
47                        public std::enable_shared_from_this<NetConnService> {
48     DECLARE_SYSTEM_ABILITY(NetConnService)
49 
50     NetConnService();
51     virtual ~NetConnService();
52     using NET_SUPPLIER_MAP = std::map<uint32_t, sptr<NetSupplier>>;
53     using NET_NETWORK_MAP = std::map<int32_t, std::shared_ptr<Network>>;
54     using NET_ACTIVATE_MAP = std::map<uint32_t, std::shared_ptr<NetActivate>>;
55     using NET_UIDREQUEST_MAP = std::map<uint32_t, uint32_t>;
56 
57 public:
GetInstance()58     static std::shared_ptr<NetConnService> &GetInstance()
59     {
60         static std::shared_ptr<NetConnService> instance = std::make_shared<NetConnService>();
61         return instance;
62     }
63     void OnStart() override;
64     void OnStop() override;
65     /**
66      * The interface in NetConnService can be called when the system is ready
67      *
68      * @return Returns 0, the system is ready, otherwise the system is not ready
69      */
70     int32_t SystemReady() override;
71 
72     /**
73      * Disallow or allow a app to create AF_INET or AF_INET6 socket
74      *
75      * @param uid App's uid which need to be disallowed ot allowed to create AF_INET or AF_INET6 socket
76      * @param allow 0 means disallow, 1 means allow
77      * @return return 0 if OK, return error number if not OK
78      */
79     int32_t SetInternetPermission(uint32_t uid, uint8_t allow) override;
80 
81     /**
82      * The interface is register the network
83      *
84      * @param bearerType Bearer Network Type
85      * @param ident Unique identification of mobile phone card
86      * @param netCaps Network capabilities registered by the network supplier
87      * @param supplierId out param, return supplier id
88      *
89      * @return function result
90      */
91     int32_t RegisterNetSupplier(NetBearType bearerType, const std::string &ident, const std::set<NetCap> &netCaps,
92                                 uint32_t &supplierId) override;
93 
94     /**
95      * The interface is unregister the network
96      *
97      * @param supplierId The id of the network supplier
98      *
99      * @return Returns 0, unregister the network successfully, otherwise it will fail
100      */
101     int32_t UnregisterNetSupplier(uint32_t supplierId) override;
102 
103     /**
104      * Register supplier callback
105      *
106      * @param supplierId The id of the network supplier
107      * @param callback INetSupplierCallback callback interface
108      *
109      * @return Returns 0, unregister the network successfully, otherwise it will fail
110      */
111     int32_t RegisterNetSupplierCallback(uint32_t supplierId, const sptr<INetSupplierCallback> &callback) override;
112 
113     /**
114      * Register net connection callback
115      *
116      * @param netSpecifier specifier information
117      * @param callback The callback of INetConnCallback interface
118      *
119      * @return Returns 0, successfully register net connection callback, otherwise it will failed
120      */
121     int32_t RegisterNetConnCallback(const sptr<INetConnCallback> &callback) override;
122 
123     /**
124      * Register net connection callback by NetSpecifier
125      *
126      * @param netSpecifier specifier information
127      * @param callback The callback of INetConnCallback interface
128      * @param timeoutMS net connection time out
129      *
130      * @return Returns 0, successfully register net connection callback, otherwise it will failed
131      */
132     int32_t RegisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
133                                     const uint32_t &timeoutMS) override;
134 
135     /**
136      * Unregister net connection callback
137      *
138      * @return Returns 0, successfully unregister net connection callback, otherwise it will fail
139      */
140     int32_t UnregisterNetConnCallback(const sptr<INetConnCallback> &callback) override;
141 
142     int32_t UpdateNetStateForTest(const sptr<NetSpecifier> &netSpecifier, int32_t netState) override;
143     /**
144      * The interface is update network connection status information
145      *
146      * @param supplierId The id of the network supplier
147      * @param netSupplierInfo network connection status information
148      *
149      * @return Returns 0, successfully update the network connection status information, otherwise it will fail
150      */
151     int32_t UpdateNetSupplierInfo(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo) override;
152 
153     /**
154      * The interface is update network link attribute information
155      *
156      * @param supplierId The id of the network supplier
157      * @param netLinkInfo network link attribute information
158      *
159      * @return Returns 0, successfully update the network link attribute information, otherwise it will fail
160      */
161     int32_t UpdateNetLinkInfo(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo) override;
162 
163     /**
164      * The interface names which NetBearType is equal than bearerType
165      *
166      * @param bearerType Network bearer type
167      * @param ifaceNames save the obtained ifaceNames
168      * @return Returns 0, successfully get the network link attribute iface name, otherwise it will fail
169      */
170     int32_t GetIfaceNames(NetBearType bearerType, std::list<std::string> &ifaceNames) override;
171 
172     /**
173      * The interface is get the iface name for network
174      *
175      * @param bearerType Network bearer type
176      * @param ident Unique identification of mobile phone card
177      * @param ifaceName save the obtained ifaceName
178      * @return Returns 0, successfully get the network link attribute iface name, otherwise it will fail
179      */
180     int32_t GetIfaceNameByType(NetBearType bearerType, const std::string &ident, std::string &ifaceName) override;
181 
182     /**
183      * register network detection return result method
184      *
185      * @param netId  Network ID
186      * @param callback The callback of INetDetectionCallback interface
187      * @return int32_t  Returns 0, unregister the network successfully, otherwise it will fail
188      */
189     int32_t RegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback) override;
190 
191     /**
192      * unregister network detection return result method
193      *
194      * @param netId Network ID
195      * @param callback  The callback of INetDetectionCallback interface
196      * @return int32_t  Returns 0, unregister the network successfully, otherwise it will fail
197      */
198     int32_t UnRegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback) override;
199 
200     /**
201      * The interface of network detection called by the application
202      *
203      * @param netId network ID
204      * @return int32_t Whether the network probe is successful
205      */
206     int32_t NetDetection(int32_t netId) override;
207     int32_t GetDefaultNet(int32_t &netId) override;
208     int32_t HasDefaultNet(bool &flag) override;
209     int32_t GetAddressesByName(const std::string &host, int32_t netId, std::vector<INetAddr> &addrList) override;
210     int32_t GetAddressByName(const std::string &host, int32_t netId, INetAddr &addr) override;
211     int32_t GetSpecificNet(NetBearType bearerType, std::list<int32_t> &netIdList) override;
212     int32_t GetAllNets(std::list<int32_t> &netIdList) override;
213     int32_t GetSpecificUidNet(int32_t uid, int32_t &netId) override;
214     int32_t GetConnectionProperties(int32_t netId, NetLinkInfo &info) override;
215     int32_t GetNetCapabilities(int32_t netId, NetAllCapabilities &netAllCap) override;
216     int32_t BindSocket(int32_t socketFd, int32_t netId) override;
217     void HandleDetectionResult(uint32_t supplierId, bool ifValid);
218     int32_t RestrictBackgroundChanged(bool isRestrictBackground);
219     /**
220      * Set airplane mode
221      *
222      * @param state airplane state
223      * @return Returns 0, successfully set airplane mode, otherwise it will fail
224      */
225     int32_t SetAirplaneMode(bool state) override;
226     /**
227      * Dump
228      *
229      * @param fd file description
230      * @param args unused
231      * @return Returns 0, successfully get dump info, otherwise it will fail
232      */
233     int32_t Dump(int32_t fd, const std::vector<std::u16string> &args) override;
234     /**
235      * Is default network metered
236      *
237      * @param save the metered state
238      * @return Returns 0, Successfully get whether the default network is metered, otherwise it will fail
239      */
240     int32_t IsDefaultNetMetered(bool &isMetered) override;
241 
242     /**
243      * Set http proxy server
244      *
245      * @param httpProxy the http proxy server
246      * @return NETMANAGER_SUCCESS if OK, NET_CONN_ERR_HTTP_PROXY_INVALID if httpProxy is null string
247      */
248     int32_t SetGlobalHttpProxy(const HttpProxy &httpProxy) override;
249 
250     /**
251      * Get http proxy server
252      *
253      * @param httpProxy output param, the http proxy server
254      * @return NETMANAGER_SUCCESS if OK, NET_CONN_ERR_NO_HTTP_PROXY if httpProxy is null string
255      */
256     int32_t GetGlobalHttpProxy(HttpProxy &httpProxy) override;
257 
258     /**
259      * Obtains the default proxy settings.
260      *
261      * <p>If a global proxy is set, the global proxy parameters are returned.
262      * If the process is bound to a network using {@link setAppNet},
263      * the {@link Network} proxy settings are returned.
264      * In other cases, the default proxy settings of network are returned.
265      *
266      * @param bindNetId App bound network ID
267      * @param httpProxy output param, the http proxy server
268      * @return Returns NETMANAGER_SUCCESS even if HttpProxy is empty
269      */
270     int32_t GetDefaultHttpProxy(int32_t bindNetId, HttpProxy &httpProxy) override;
271 
272     /**
273      * Get net id by identifier
274      *
275      * @param ident Net identifier
276      * @param netIdList output param, the net id list
277      * @return NETMANAGER_SUCCESS if OK, ERR_NO_NET_IDENT if ident is null string
278      */
279     int32_t GetNetIdByIdentifier(const std::string &ident, std::list<int32_t> &netIdList) override;
280 
281     /**
282      * Activate network timeout
283      *
284      * @param reqId Net request id
285      */
286     void OnNetActivateTimeOut(uint32_t reqId) override;
287 
288     /**
289      * The interface of network detection called when DNS health check failed
290      *
291      * @param netId network ID
292      * @return int32_t Whether the network probe is successful
293      */
294     int32_t NetDetectionForDnsHealth(int32_t netId, bool dnsHealthSuccess);
295 
296     int32_t SetAppNet(int32_t netId) override;
297     int32_t RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback) override;
298     int32_t GetNetInterfaceConfiguration(const std::string &iface, NetInterfaceConfiguration &config) override;
299     int32_t AddNetworkRoute(int32_t netId, const std::string &ifName,
300                             const std::string &destination, const std::string &nextHop) override;
301     int32_t RemoveNetworkRoute(int32_t netId, const std::string &ifName,
302                                const std::string &destination, const std::string &nextHop) override;
303     int32_t AddInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
304                                 int32_t prefixLength) override;
305     int32_t DelInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
306                                 int32_t prefixLength) override;
307     int32_t AddStaticArp(const std::string &ipAddr, const std::string &macAddr,
308                          const std::string &ifName) override;
309     int32_t DelStaticArp(const std::string &ipAddr, const std::string &macAddr,
310                          const std::string &ifName) override;
311     int32_t RegisterSlotType(uint32_t supplierId, int32_t type) override;
312     int32_t GetSlotType(std::string &type) override;
313     int32_t FactoryResetNetwork() override;
314     int32_t RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> &callback) override;
315     int32_t IsPreferCellularUrl(const std::string& url, bool& preferCellular) override;
316 
317 private:
318     class NetInterfaceStateCallback : public NetsysControllerCallback {
319     public:
320         NetInterfaceStateCallback() = default;
321         ~NetInterfaceStateCallback() = default;
322         int32_t OnInterfaceAddressUpdated(const std::string &addr, const std::string &ifName, int flags,
323                                           int scope) override;
324         int32_t OnInterfaceAddressRemoved(const std::string &addr, const std::string &ifName, int flags,
325                                           int scope) override;
326         int32_t OnInterfaceAdded(const std::string &iface) override;
327         int32_t OnInterfaceRemoved(const std::string &iface) override;
328         int32_t OnInterfaceChanged(const std::string &iface, bool up) override;
329         int32_t OnInterfaceLinkStateChanged(const std::string &iface, bool up) override;
330         int32_t OnRouteChanged(bool updated, const std::string &route, const std::string &gateway,
331                                const std::string &ifName) override;
332         int32_t OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult) override;
333         int32_t OnBandwidthReachedLimit(const std::string &limitName, const std::string &iface) override;
334 
335         int32_t RegisterInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback);
336 
337     private:
338         std::mutex mutex_;
339         std::vector<sptr<INetInterfaceStateCallback>> ifaceStateCallbacks_;
340     };
341 
342 protected:
343     void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
344     void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
345 
346 private:
347     bool Init();
348     void RecoverInfo();
349     std::list<sptr<NetSupplier>> GetNetSupplierFromList(NetBearType bearerType, const std::string &ident = "");
350     sptr<NetSupplier> GetNetSupplierFromList(NetBearType bearerType, const std::string &ident,
351                                              const std::set<NetCap> &netCaps);
352     int32_t ActivateNetwork(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
353                             const uint32_t &timeoutMS);
354     void CallbackForSupplier(sptr<NetSupplier> &supplier, CallbackType type);
355     void CallbackForAvailable(sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback);
356     uint32_t FindBestNetworkForRequest(sptr<NetSupplier> &supplier, std::shared_ptr<NetActivate> &netActivateNetwork);
357     void SendRequestToAllNetwork(std::shared_ptr<NetActivate> request);
358     void SendBestScoreAllNetwork(uint32_t reqId, int32_t bestScore, uint32_t supplierId);
359     void SendAllRequestToNetwork(sptr<NetSupplier> supplier);
360     void FindBestNetworkForAllRequest();
361     void MakeDefaultNetWork(sptr<NetSupplier> &oldService, sptr<NetSupplier> &newService);
362     void NotFindBestSupplier(uint32_t reqId, const std::shared_ptr<NetActivate> &active,
363                              const sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback);
364     void CreateDefaultRequest();
365     int32_t RegUnRegNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback, bool isReg);
366     int32_t GenerateNetId();
367     bool FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId);
368     void GetDumpMessage(std::string &message);
369     sptr<NetSupplier> FindNetSupplier(uint32_t supplierId);
370     int32_t RegisterNetSupplierAsync(NetBearType bearerType, const std::string &ident, const std::set<NetCap> &netCaps,
371                                      uint32_t &supplierId);
372     int32_t UnregisterNetSupplierAsync(uint32_t supplierId);
373     int32_t RegisterNetSupplierCallbackAsync(uint32_t supplierId, const sptr<INetSupplierCallback> &callback);
374     int32_t RegisterNetConnCallbackAsync(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
375                                          const uint32_t &timeoutMS, const uint32_t callingUid);
376     int32_t UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> &callback, const uint32_t callingUid);
377     int32_t RegUnRegNetDetectionCallbackAsync(int32_t netId, const sptr<INetDetectionCallback> &callback, bool isReg);
378     int32_t UpdateNetStateForTestAsync(const sptr<NetSpecifier> &netSpecifier, int32_t netState);
379     int32_t UpdateNetSupplierInfoAsync(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo);
380     int32_t UpdateNetLinkInfoAsync(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo);
381     int32_t NetDetectionAsync(int32_t netId);
382     int32_t RestrictBackgroundChangedAsync(bool restrictBackground);
383     void SendHttpProxyChangeBroadcast(const HttpProxy &httpProxy);
384     void RequestAllNetworkExceptDefault();
385     void LoadGlobalHttpProxy();
386     void UpdateGlobalHttpProxy(const HttpProxy &httpProxy);
387     void ActiveHttpProxy();
388     void DecreaseNetConnCallbackCntForUid(const uint32_t callingUid);
389     int32_t IncreaseNetConnCallbackCntForUid(const uint32_t callingUid);
390 
391     void OnNetSysRestart();
392 
393     bool IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns);
394     std::vector<std::string> GetPreferredUrl();
395 
396 private:
397     enum ServiceRunningState {
398         STATE_STOPPED = 0,
399         STATE_RUNNING,
400     };
401 
402     bool registerToService_;
403     ServiceRunningState state_;
404     sptr<NetSpecifier> defaultNetSpecifier_ = nullptr;
405     std::shared_ptr<NetActivate> defaultNetActivate_ = nullptr;
406     sptr<NetSupplier> defaultNetSupplier_ = nullptr;
407     NET_SUPPLIER_MAP netSuppliers_;
408     NET_ACTIVATE_MAP netActivates_;
409     NET_UIDREQUEST_MAP netUidRequest_;
410     NET_NETWORK_MAP networks_;
411     std::unique_ptr<NetScore> netScore_ = nullptr;
412     sptr<NetConnServiceIface> serviceIface_ = nullptr;
413     std::atomic<int32_t> netIdLastValue_ = MIN_NET_ID - 1;
414     std::atomic<bool> isGlobalProxyLoaded_ = false;
415     HttpProxy globalHttpProxy_;
416     std::mutex globalHttpProxyMutex_;
417     std::mutex netManagerMutex_;
418     std::shared_ptr<AppExecFwk::EventRunner> netConnEventRunner_ = nullptr;
419     std::shared_ptr<NetConnEventHandler> netConnEventHandler_ = nullptr;
420     std::shared_ptr<AppExecFwk::EventRunner> netActEventRunner_ = nullptr;
421     std::shared_ptr<AppExecFwk::EventHandler> netActEventHandler_ = nullptr;
422     sptr<NetInterfaceStateCallback> interfaceStateCallback_ = nullptr;
423     sptr<NetDnsResultCallback> dnsResultCallback_ = nullptr;
424     sptr<NetFactoryResetCallback> netFactoryResetCallback_ = nullptr;
425     std::atomic_bool httpProxyThreadNeedRun_ = false;
426     std::condition_variable httpProxyThreadCv_;
427     std::mutex httpProxyThreadMutex_;
428     static constexpr const uint32_t HTTP_PROXY_ACTIVE_PERIOD_S = 300;
429 
430     bool hasSARemoved_ = false;
431 };
432 } // namespace NetManagerStandard
433 } // namespace OHOS
434 #endif // NET_CONN_SERVICE_H
435