• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 <cstdint>
20 #include <functional>
21 #include <list>
22 #include <memory>
23 #include <mutex>
24 #include <string>
25 #include <vector>
26 #include <thread>
27 #include <condition_variable>
28 
29 #include "singleton.h"
30 #include "system_ability.h"
31 
32 #include "http_proxy.h"
33 #include "net_activate.h"
34 #include "net_conn_constants.h"
35 #include "net_conn_event_handler.h"
36 #include "net_conn_service_iface.h"
37 #include "net_conn_service_stub.h"
38 #include "net_supplier.h"
39 #include "netsys_controller_callback.h"
40 #include "network.h"
41 #include "dns_result_call_back.h"
42 #include "net_factoryreset_callback.h"
43 #include "net_policy_callback_stub.h"
44 #include "net_policy_service.h"
45 #include "common_event_data.h"
46 #include "common_event_manager.h"
47 #include "common_event_subscriber.h"
48 #include "common_event_support.h"
49 #include "os_account_manager.h"
50 #include "app_state_aware.h"
51 
52 namespace OHOS {
53 namespace NetManagerStandard {
54 using EventReceiver = std::function<void(const EventFwk::CommonEventData&)>;
55 class NetConnService : public SystemAbility,
56                        public INetActivateCallback,
57                        public NetConnServiceStub,
58                        public std::enable_shared_from_this<NetConnService> {
59     DECLARE_SYSTEM_ABILITY(NetConnService)
60 
61     NetConnService();
62     virtual ~NetConnService();
63     using NET_SUPPLIER_MAP = std::map<uint32_t, sptr<NetSupplier>>;
64     using NET_NETWORK_MAP = std::map<int32_t, std::shared_ptr<Network>>;
65     using NET_ACTIVATE_MAP = std::map<uint32_t, std::shared_ptr<NetActivate>>;
66     using NET_UIDREQUEST_MAP = std::map<uint32_t, uint32_t>;
67     using NET_UIDACTIVATE_MAP = std::map<uint32_t, std::vector<std::shared_ptr<NetActivate>>>;
68 
69 public:
70     class NetConnListener : public EventFwk::CommonEventSubscriber {
71     public:
72         NetConnListener(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, EventReceiver receiver);
73         void OnReceiveEvent(const EventFwk::CommonEventData &data) override;
74 
75     private:
76         EventReceiver eventReceiver_;
77     };
GetInstance()78     static std::shared_ptr<NetConnService> &GetInstance()
79     {
80         static std::shared_ptr<NetConnService> instance = std::make_shared<NetConnService>();
81         return instance;
82     }
83     void OnStart() override;
84     void OnStop() override;
85     /**
86      * The interface in NetConnService can be called when the system is ready
87      *
88      * @return Returns 0, the system is ready, otherwise the system is not ready
89      */
90     int32_t SystemReady() override;
91 
92     /**
93      * Disallow or allow a app to create AF_INET or AF_INET6 socket
94      *
95      * @param uid App's uid which need to be disallowed ot allowed to create AF_INET or AF_INET6 socket
96      * @param allow 0 means disallow, 1 means allow
97      * @return return 0 if OK, return error number if not OK
98      */
99     int32_t SetInternetPermission(uint32_t uid, uint8_t allow) override;
100 
101     /**
102      * The interface is register the network
103      *
104      * @param bearerType Bearer Network Type
105      * @param ident Unique identification of mobile phone card
106      * @param netCaps Network capabilities registered by the network supplier
107      * @param supplierId out param, return supplier id
108      *
109      * @return function result
110      */
111     int32_t RegisterNetSupplier(NetBearType bearerType, const std::string &ident, const std::set<NetCap> &netCaps,
112                                 uint32_t &supplierId) override;
113 
114     /**
115      * The interface is unregister the network
116      *
117      * @param supplierId The id of the network supplier
118      *
119      * @return Returns 0, unregister the network successfully, otherwise it will fail
120      */
121     int32_t UnregisterNetSupplier(uint32_t supplierId) override;
122 
123     /**
124      * Register supplier callback
125      *
126      * @param supplierId The id of the network supplier
127      * @param callback INetSupplierCallback callback interface
128      *
129      * @return Returns 0, unregister the network successfully, otherwise it will fail
130      */
131     int32_t RegisterNetSupplierCallback(uint32_t supplierId, const sptr<INetSupplierCallback> &callback) override;
132 
133     /**
134      * Register net connection callback
135      *
136      * @param netSpecifier specifier information
137      * @param callback The callback of INetConnCallback interface
138      *
139      * @return Returns 0, successfully register net connection callback, otherwise it will failed
140      */
141     int32_t RegisterNetConnCallback(const sptr<INetConnCallback> callback) override;
142 
143     /**
144      * Register net connection callback by NetSpecifier
145      *
146      * @param netSpecifier specifier information
147      * @param callback The callback of INetConnCallback interface
148      * @param timeoutMS net connection time out
149      *
150      * @return Returns 0, successfully register net connection callback, otherwise it will failed
151      */
152     int32_t RegisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> callback,
153                                     const uint32_t &timeoutMS) override;
154 
155     /**
156      * Request net connection callback by NetSpecifier
157      *
158      * @param netSpecifier specifier information
159      * @param callback The callback of INetConnCallback interface
160      * @param timeoutMS net connection time out
161      *
162      * @return Returns 0, successfully register net connection callback, otherwise it will failed
163      */
164     int32_t RequestNetConnection(const sptr<NetSpecifier> netSpecifier, const sptr<INetConnCallback> callback,
165                                     const uint32_t timeoutMS) override;
166     /**
167      * Unregister net connection callback
168      *
169      * @return Returns 0, successfully unregister net connection callback, otherwise it will fail
170      */
171     int32_t UnregisterNetConnCallback(const sptr<INetConnCallback> &callback) override;
172 
173     int32_t UpdateNetStateForTest(const sptr<NetSpecifier> &netSpecifier, int32_t netState) override;
174 
175     /**
176      * update net capabilities
177      *
178      * @param netCaps netcap set
179      * @param supplierId The id of the network supplier
180      * @return Returns 0, update net caps of the network successfully, otherwise it will fail
181      */
182     int32_t UpdateNetCaps(const std::set<NetCap> &netCaps, const uint32_t supplierId) override;
183 
184     /**
185      * The interface is update network connection status information
186      *
187      * @param supplierId The id of the network supplier
188      * @param netSupplierInfo network connection status information
189      *
190      * @return Returns 0, successfully update the network connection status information, otherwise it will fail
191      */
192     int32_t UpdateNetSupplierInfo(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo) override;
193 
194     /**
195      * The interface is update network link attribute information
196      *
197      * @param supplierId The id of the network supplier
198      * @param netLinkInfo network link attribute information
199      *
200      * @return Returns 0, successfully update the network link attribute information, otherwise it will fail
201      */
202     int32_t UpdateNetLinkInfo(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo) override;
203 
204     /**
205      * The interface names which NetBearType is equal than bearerType
206      *
207      * @param bearerType Network bearer type
208      * @param ifaceNames save the obtained ifaceNames
209      * @return Returns 0, successfully get the network link attribute iface name, otherwise it will fail
210      */
211     int32_t GetIfaceNames(NetBearType bearerType, std::list<std::string> &ifaceNames) override;
212 
213     /**
214      * The interface is get the iface name for network
215      *
216      * @param bearerType Network bearer type
217      * @param ident Unique identification of mobile phone card
218      * @param ifaceName save the obtained ifaceName
219      * @return Returns 0, successfully get the network link attribute iface name, otherwise it will fail
220      */
221     int32_t GetIfaceNameByType(NetBearType bearerType, const std::string &ident, std::string &ifaceName) override;
222 
223     /**
224      * The interface is to get all iface and ident maps
225      *
226      * @param bearerType the type of network
227      * @param ifaceNameIdentMaps the map of ifaceName and ident
228      * @return Returns 0 success. Otherwise fail.
229      * @permission ohos.permission.CONNECTIVITY_INTERNAL
230      * @systemapi Hide this for inner system use.
231      */
232     int32_t GetIfaceNameIdentMaps(NetBearType bearerType,
233                                   SafeMap<std::string, std::string> &ifaceNameIdentMaps) override;
234 
235     /**
236      * register network detection return result method
237      *
238      * @param netId  Network ID
239      * @param callback The callback of INetDetectionCallback interface
240      * @return int32_t  Returns 0, unregister the network successfully, otherwise it will fail
241      */
242     int32_t RegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback) override;
243 
244     /**
245      * unregister network detection return result method
246      *
247      * @param netId Network ID
248      * @param callback  The callback of INetDetectionCallback interface
249      * @return int32_t  Returns 0, unregister the network successfully, otherwise it will fail
250      */
251     int32_t UnRegisterNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback) override;
252 
253     /**
254      * The interface of network detection called by the application
255      *
256      * @param netId network ID
257      * @return int32_t Whether the network probe is successful
258      */
259     int32_t NetDetection(int32_t netId) override;
260     int32_t GetDefaultNet(int32_t &netId) override;
261     int32_t HasDefaultNet(bool &flag) override;
262     int32_t GetAddressesByName(const std::string &host, int32_t netId, std::vector<INetAddr> &addrList) override;
263     int32_t GetAddressByName(const std::string &host, int32_t netId, INetAddr &addr) override;
264     int32_t GetSpecificNet(NetBearType bearerType, std::list<int32_t> &netIdList) override;
265     int32_t GetSpecificNetByIdent(NetBearType bearerType, const std::string &ident,
266         std::list<int32_t> &netIdList) override;
267     int32_t GetAllNetsAsync(std::list<int32_t> &netIdList);
268     int32_t GetAllNets(std::list<int32_t> &netIdList) override;
269     int32_t GetSpecificUidNet(int32_t uid, int32_t &netId) override;
270     int32_t GetConnectionProperties(int32_t netId, NetLinkInfo &info) override;
271     int32_t GetNetCapabilities(int32_t netId, NetAllCapabilities &netAllCap) override;
272     int32_t BindSocket(int32_t socketFd, int32_t netId) override;
273     void HandleDetectionResult(uint32_t supplierId, NetDetectionStatus netState);
274     int32_t RestrictBackgroundChanged(bool isRestrictBackground);
275     /**
276      * Set airplane mode
277      *
278      * @param state airplane state
279      * @return Returns 0, successfully set airplane mode, otherwise it will fail
280      */
281     int32_t SetAirplaneMode(bool state) override;
282     /**
283      * Dump
284      *
285      * @param fd file description
286      * @param args unused
287      * @return Returns 0, successfully get dump info, otherwise it will fail
288      */
289     int32_t Dump(int32_t fd, const std::vector<std::u16string> &args) override;
290     /**
291      * Is default network metered
292      *
293      * @param save the metered state
294      * @return Returns 0, Successfully get whether the default network is metered, otherwise it will fail
295      */
296     int32_t IsDefaultNetMetered(bool &isMetered) override;
297 
298     /**
299      * Set http proxy server
300      *
301      * @param httpProxy the http proxy server
302      * @return NETMANAGER_SUCCESS if OK, NET_CONN_ERR_HTTP_PROXY_INVALID if httpProxy is null string
303      */
304     int32_t SetGlobalHttpProxy(const HttpProxy &httpProxy) override;
305 
306     /**
307      * Get http proxy server
308      *
309      * @param httpProxy output param, the http proxy server
310      * @return NETMANAGER_SUCCESS if OK, NET_CONN_ERR_NO_HTTP_PROXY if httpProxy is null string
311      */
312     int32_t GetGlobalHttpProxy(HttpProxy &httpProxy) override;
313 
314     /**
315      * Obtains the default proxy settings.
316      *
317      * <p>If a global proxy is set, the global proxy parameters are returned.
318      * If the process is bound to a network using {@link setAppNet},
319      * the {@link Network} proxy settings are returned.
320      * In other cases, the default proxy settings of network are returned.
321      *
322      * @param bindNetId App bound network ID
323      * @param httpProxy output param, the http proxy server
324      * @return Returns NETMANAGER_SUCCESS even if HttpProxy is empty
325      */
326     int32_t GetDefaultHttpProxy(int32_t bindNetId, HttpProxy &httpProxy) override;
327 
328     /**
329      * Get net id by identifier
330      *
331      * @param ident Net identifier
332      * @param netIdList output param, the net id list
333      * @return NETMANAGER_SUCCESS if OK, ERR_NO_NET_IDENT if ident is null string
334      */
335     int32_t GetNetIdByIdentifier(const std::string &ident, std::list<int32_t> &netIdList) override;
336 
337     /**
338      * Activate network timeout
339      *
340      * @param reqId Net request id
341      */
342     void OnNetActivateTimeOut(uint32_t reqId) override;
343 
344     /**
345      * The interface of network detection called when DNS health check failed
346      *
347      * @param netId network ID
348      * @return int32_t Whether the network probe is successful
349      */
350     int32_t NetDetectionForDnsHealth(int32_t netId, bool dnsHealthSuccess);
351 
352     int32_t SetAppNet(int32_t netId) override;
353     int32_t RegisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback) override;
354     int32_t UnregisterNetInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback) override;
355     int32_t GetNetInterfaceConfiguration(const std::string &iface, NetInterfaceConfiguration &config) override;
356     int32_t SetNetInterfaceIpAddress(const std::string &iface, const std::string &ipAddress) override;
357     int32_t SetInterfaceUp(const std::string &iface) override;
358     int32_t SetInterfaceDown(const std::string &iface) override;
359     int32_t AddNetworkRoute(int32_t netId, const std::string &ifName,
360                             const std::string &destination, const std::string &nextHop) override;
361     int32_t RemoveNetworkRoute(int32_t netId, const std::string &ifName,
362                                const std::string &destination, const std::string &nextHop) override;
363     int32_t AddInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
364                                 int32_t prefixLength) override;
365     int32_t DelInterfaceAddress(const std::string &ifName, const std::string &ipAddr,
366                                 int32_t prefixLength) override;
367     int32_t AddStaticArp(const std::string &ipAddr, const std::string &macAddr,
368                          const std::string &ifName) override;
369     int32_t DelStaticArp(const std::string &ipAddr, const std::string &macAddr,
370                          const std::string &ifName) override;
371     int32_t RegisterSlotType(uint32_t supplierId, int32_t type) override;
372     int32_t GetSlotType(std::string &type) override;
373     int32_t FactoryResetNetwork() override;
374     int32_t RegisterNetFactoryResetCallback(const sptr<INetFactoryResetCallback> &callback) override;
375     int32_t IsPreferCellularUrl(const std::string& url, bool& preferCellular) override;
376     int32_t RegisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback) override;
377     int32_t UnregisterPreAirplaneCallback(const sptr<IPreAirplaneCallback> callback) override;
378     bool IsIfaceNameInUse(const std::string &ifaceName, int32_t netId);
379     int32_t DecreaseSupplierScore(NetBearType bearerType, const std::string &ident,
380                                   uint32_t &supplierId) override;
381     int32_t IncreaseSupplierScore(uint32_t supplierId) override;
382     std::string GetNetCapabilitiesAsString(const uint32_t supplierId);
383     int32_t EnableVnicNetwork(const sptr<NetLinkInfo> &netLinkInfo, const std::set<int32_t> &uids) override;
384     int32_t DisableVnicNetwork() override;
385     int32_t EnableDistributedClientNet(const std::string &virnicAddr, const std::string &iif) override;
386     int32_t EnableDistributedServerNet(const std::string &iif, const std::string &devIface,
387                                        const std::string &dstAddr) override;
388     int32_t DisableDistributedNet(bool isServer) override;
389     int32_t CloseSocketsUid(int32_t netId, uint32_t uid) override;
390     int32_t SetPacUrl(const std::string &pacUrl) override;
391     int32_t GetPacUrl(std::string &pacUrl) override;
392     int32_t SetAppIsFrozened(uint32_t uid, bool isFrozened) override;
393     int32_t EnableAppFrozenedCallbackLimitation(bool flag) override;
394     bool IsAppFrozenedCallbackLimitation();
395 
396 private:
397     class NetInterfaceStateCallback : public NetsysControllerCallback {
398     public:
399         NetInterfaceStateCallback() = default;
400         ~NetInterfaceStateCallback() = default;
401         int32_t OnInterfaceAddressUpdated(const std::string &addr, const std::string &ifName, int flags,
402                                           int scope) override;
403         int32_t OnInterfaceAddressRemoved(const std::string &addr, const std::string &ifName, int flags,
404                                           int scope) override;
405         int32_t OnInterfaceAdded(const std::string &iface) override;
406         int32_t OnInterfaceRemoved(const std::string &iface) override;
407         int32_t OnInterfaceChanged(const std::string &iface, bool up) override;
408         int32_t OnInterfaceLinkStateChanged(const std::string &iface, bool up) override;
409         int32_t OnRouteChanged(bool updated, const std::string &route, const std::string &gateway,
410                                const std::string &ifName) override;
411         int32_t OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult) override;
412         int32_t OnBandwidthReachedLimit(const std::string &limitName, const std::string &iface) override;
413 
414         int32_t RegisterInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback);
415         int32_t UnregisterInterfaceCallback(const sptr<INetInterfaceStateCallback> &callback);
416 
417     private:
418     class NetIfaceStateCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
419         public:
NetIfaceStateCallbackDeathRecipient(NetInterfaceStateCallback & client)420             explicit NetIfaceStateCallbackDeathRecipient(NetInterfaceStateCallback &client) : client_(client) {}
421             ~NetIfaceStateCallbackDeathRecipient() override = default;
OnRemoteDied(const wptr<IRemoteObject> & remote)422             void OnRemoteDied(const wptr<IRemoteObject> &remote) override
423             {
424                 client_.OnNetIfaceStateRemoteDied(remote);
425             }
426 
427         private:
428             NetInterfaceStateCallback &client_;
429         };
430 
431         std::mutex mutex_;
432         std::vector<sptr<INetInterfaceStateCallback>> ifaceStateCallbacks_;
433         sptr<IRemoteObject::DeathRecipient> netIfaceStateDeathRecipient_ = nullptr;
434 
435         void OnNetIfaceStateRemoteDied(const wptr<IRemoteObject> &remoteObject);
436         void AddIfaceDeathRecipient(const sptr<INetInterfaceStateCallback> &callback);
437     };
438 
439     class NetPolicyCallback : public NetPolicyCallbackStub {
440     public:
NetPolicyCallback(std::weak_ptr<NetConnService> netConnService)441         NetPolicyCallback(std::weak_ptr<NetConnService> netConnService) : netConnService_(netConnService) {}
442         int32_t NetUidPolicyChange(uint32_t uid, uint32_t policy) override;
443 
444     private:
445         void SendNetPolicyChange(uint32_t uid, uint32_t policy);
446 
447     private:
448         std::weak_ptr<NetConnService> netConnService_;
449     };
450 
451 protected:
452     void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
453     void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
454 
455 private:
456     enum RegisterType {
457         INVALIDTYPE,
458         REGISTER,
459         REQUEST,
460     };
461     enum UserIdType {
462         ACTIVE,
463         LOCAL,
464         SPECIFY,
465     };
466     bool Init();
467     void SetCurlOptions(CURL *curl, HttpProxy tempProxy);
468     void GetHttpUrlFromConfig(std::string &httpUrl);
469     std::list<sptr<NetSupplier>> GetNetSupplierFromList(NetBearType bearerType, const std::string &ident = "");
470     sptr<NetSupplier> GetNetSupplierFromList(NetBearType bearerType, const std::string &ident,
471                                              const std::set<NetCap> &netCaps);
472     int32_t ActivateNetwork(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
473                             const uint32_t &timeoutMS, const int32_t registerType = REGISTER,
474                             const uint32_t callingUid = 0);
475     void CallbackForSupplier(sptr<NetSupplier> &supplier, CallbackType type);
476     void CallbackForAvailable(sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback);
477     uint32_t FindBestNetworkForRequest(sptr<NetSupplier> &supplier, std::shared_ptr<NetActivate> &netActivateNetwork);
478     uint32_t FindInternalNetworkForRequest(std::shared_ptr<NetActivate> &netActivateNetwork,
479                                            sptr<NetSupplier> &supplier);
480     void SendRequestToAllNetwork(std::shared_ptr<NetActivate> request);
481     void SendBestScoreAllNetwork(uint32_t reqId, int32_t bestScore, uint32_t supplierId, uint32_t uid);
482     void SendAllRequestToNetwork(sptr<NetSupplier> supplier);
483     void FindBestNetworkForAllRequest();
484     void MakeDefaultNetWork(sptr<NetSupplier> &oldService, sptr<NetSupplier> &newService);
485     void NotFindBestSupplier(uint32_t reqId, const std::shared_ptr<NetActivate> &active,
486                              const sptr<NetSupplier> &supplier, const sptr<INetConnCallback> &callback);
487     void CreateDefaultRequest();
488     int32_t RegUnRegNetDetectionCallback(int32_t netId, const sptr<INetDetectionCallback> &callback, bool isReg);
489     int32_t GenerateNetId();
490     int32_t GenerateInternalNetId();
491     bool FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId);
492     bool FindSameCallback(const sptr<INetConnCallback> &callback, uint32_t &reqId,
493                           RegisterType &registerType, uint32_t &uid);
494     void GetDumpMessage(std::string &message);
495     sptr<NetSupplier> FindNetSupplier(uint32_t supplierId);
496     int32_t RegisterNetSupplierAsync(NetBearType bearerType, const std::string &ident, const std::set<NetCap> &netCaps,
497                                      uint32_t &supplierId, int32_t callingUid);
498     int32_t UnregisterNetSupplierAsync(uint32_t supplierId, bool ignoreUid, int32_t callingUid);
499     int32_t RegisterNetSupplierCallbackAsync(uint32_t supplierId, const sptr<INetSupplierCallback> &callback);
500     int32_t RegisterNetConnCallbackAsync(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
501                                          const uint32_t &timeoutMS, const uint32_t callingUid);
502     int32_t RequestNetConnectionAsync(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback,
503                                          const uint32_t &timeoutMS, const uint32_t callingUid);
504     int32_t UpdateNetCapsAsync(const std::set<NetCap> &netCaps, const uint32_t supplierId);
505     int32_t UnregisterNetConnCallbackAsync(const sptr<INetConnCallback> &callback, const uint32_t callingUid);
506     int32_t RegUnRegNetDetectionCallbackAsync(int32_t netId, const sptr<INetDetectionCallback> &callback, bool isReg);
507     int32_t UpdateNetStateForTestAsync(const sptr<NetSpecifier> &netSpecifier, int32_t netState);
508     int32_t UpdateNetSupplierInfoAsync(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo,
509                                        int32_t callingUid);
510     int32_t UpdateNetLinkInfoAsync(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo, int32_t callingUid);
511     int32_t NetDetectionAsync(int32_t netId);
512     int32_t RestrictBackgroundChangedAsync(bool restrictBackground);
513     int32_t DecreaseSupplierScoreAsync(NetBearType bearerType, const std::string &ident,
514                                        uint32_t& supplierId);
515     int32_t IncreaseSupplierScoreAsync(uint32_t supplierId);
516     void SendHttpProxyChangeBroadcast(const HttpProxy &httpProxy);
517     void RequestAllNetworkExceptDefault();
518     void LoadGlobalHttpProxy(UserIdType userIdType, HttpProxy &httpProxy);
519     void UpdateGlobalHttpProxy(const HttpProxy &httpProxy);
520     int32_t SetGlobalHttpProxyOld(HttpProxy httpProxy, int32_t activeUserId);
521     int32_t SetGlobalHttpProxyInner(const HttpProxy &httpProxy);
522     void ActiveHttpProxy();
523     void CreateActiveHttpProxyThread();
524     void DecreaseNetConnCallbackCntForUid(const uint32_t callingUid,
525         const RegisterType registerType = REGISTER);
526     int32_t IncreaseNetConnCallbackCntForUid(const uint32_t callingUid,
527         const RegisterType registerType = REGISTER);
528 
529     void RecoverNetSys();
530     void OnNetSysRestart();
531 
532     bool IsSupplierMatchRequestAndNetwork(sptr<NetSupplier> ns);
533     std::vector<std::string> GetPreferredRegex();
534     bool IsValidDecValue(const std::string &inputValue);
535     int32_t GetDelayNotifyTime();
536     int32_t NetDetectionForDnsHealthSync(int32_t netId, bool dnsHealthSuccess);
537     std::vector<sptr<NetSupplier>> FindSupplierWithInternetByBearerType(
538         NetBearType bearerType, const std::string &ident);
539     uint32_t FindSupplierForConnected(std::vector<sptr<NetSupplier>> &suppliers);
540     int32_t GetLocalUserId(int32_t &userId);
541     int32_t GetActiveUserId(int32_t &userId);
542     bool IsValidUserId(int32_t userId);
543     int32_t GetValidUserIdFromProxy(const HttpProxy &httpProxy);
IsPrimaryUserId(const int32_t userId)544     inline bool IsPrimaryUserId(const int32_t userId)
545     {
546         return userId == PRIMARY_USER_ID;
547     }
548     uint32_t FindSupplierToReduceScore(std::vector<sptr<NetSupplier>>& suppliers, uint32_t& supplierId);
549     int32_t EnableVnicNetworkAsync(const sptr<NetLinkInfo> &netLinkInfo, const std::set<int32_t> &uids);
550     int32_t DisableVnicNetworkAsync();
551     int32_t EnableDistributedClientNetAsync(const std::string &virnicAddr, const std::string &iif);
552     int32_t EnableDistributedServerNetAsync(const std::string &iif, const std::string &devIface,
553                                             const std::string &dstAddr);
554     int32_t DisableDistributedNetAsync(bool isServer);
555     int32_t CloseSocketsUidAsync(int32_t netId, uint32_t uid);
556     int32_t SetAppIsFrozenedAsync(uint32_t uid, bool isFrozened);
557     int32_t EnableAppFrozenedCallbackLimitationAsync(bool flag);
558     void HandleCallback(sptr<NetSupplier> &supplier, sptr<NetHandle> &netHandle,
559                         sptr<INetConnCallback> callback, CallbackType type);
560     std::shared_ptr<NetActivate> CreateNetActivateRequest(const sptr<NetSpecifier> &netSpecifier,
561                             const sptr<INetConnCallback> &callback,
562                             const uint32_t &timeoutMS, const int32_t registerType,
563                             const uint32_t callingUid);
564 
565     // for NET_CAPABILITY_INTERNAL_DEFAULT
566     bool IsInRequestNetUids(int32_t uid);
567     int32_t CheckAndCompareUid(sptr<NetSupplier> &supplier, int32_t callingUid);
568 #ifdef FEATURE_SUPPORT_POWERMANAGER
569     void StopAllNetDetection();
570     void StartAllNetDetection();
571 #endif
572     void DecreaseNetActivatesForUid(const uint32_t callingUid, const sptr<INetConnCallback> &callback);
573     void DecreaseNetActivates(const uint32_t callingUid, const sptr<INetConnCallback> &callback, uint32_t reqId);
574 private:
575     enum ServiceRunningState {
576         STATE_STOPPED = 0,
577         STATE_RUNNING,
578     };
579 
580     bool registerToService_;
581     ServiceRunningState state_;
582     sptr<NetSpecifier> defaultNetSpecifier_ = nullptr;
583     std::shared_ptr<NetActivate> defaultNetActivate_ = nullptr;
584     sptr<NetSupplier> defaultNetSupplier_ = nullptr;
585     NET_SUPPLIER_MAP netSuppliers_;
586     NET_ACTIVATE_MAP netActivates_;
587     std::shared_mutex netActivatesMutex_;
588     NET_UIDREQUEST_MAP netUidRequest_;
589     NET_UIDREQUEST_MAP internalDefaultUidRequest_;
590     NET_NETWORK_MAP networks_;
591     NET_UIDACTIVATE_MAP netUidActivates_;
592     std::mutex uidActivateMutex_;
593     std::atomic<bool> vnicCreated = false;
594     sptr<NetConnServiceIface> serviceIface_ = nullptr;
595     std::atomic<int32_t> netIdLastValue_ = MIN_NET_ID - 1;
596     std::atomic<int32_t> internalNetIdLastValue_ = MIN_INTERNAL_NET_ID;
597     std::atomic<bool> isDataShareReady_ = false;
598     SafeMap<int32_t, HttpProxy> globalHttpProxyCache_;
599     std::recursive_mutex netManagerMutex_;
600     std::mutex netUidRequestMutex_;
601     std::shared_ptr<AppExecFwk::EventRunner> netConnEventRunner_ = nullptr;
602     std::shared_ptr<NetConnEventHandler> netConnEventHandler_ = nullptr;
603     sptr<NetInterfaceStateCallback> interfaceStateCallback_ = nullptr;
604     sptr<NetDnsResultCallback> dnsResultCallback_ = nullptr;
605     sptr<NetFactoryResetCallback> netFactoryResetCallback_ = nullptr;
606     sptr<NetPolicyCallback> policyCallback_ = nullptr;
607     std::atomic_bool httpProxyThreadNeedRun_ = false;
608     std::condition_variable httpProxyThreadCv_;
609     std::mutex httpProxyThreadMutex_;
610     static constexpr uint32_t HTTP_PROXY_ACTIVE_PERIOD_S = 120;
611     static constexpr uint32_t HTTP_PROXY_ACTIVE_PERIOD_IN_SLEEP_S = 240;
612     std::map<int32_t, sptr<IPreAirplaneCallback>> preAirplaneCallbacks_;
613     std::mutex preAirplaneCbsMutex_;
614     std::shared_ptr<NetConnListener> subscriber_ = nullptr;
615 
616     bool hasSARemoved_ = false;
617     std::atomic<bool> isInSleep_ = false;
618     static constexpr int32_t INVALID_USER_ID = -1;
619     static constexpr int32_t ROOT_USER_ID = 0;
620     int32_t currentUserId_ = INVALID_USER_ID;
621     bool isFallbackProbeWithProxy_ = false;
622     AppStateAwareCallback appStateAwareCallback_;
623     std::atomic<bool> enableAppFrozenedCallbackLimitation_ = false;
624 
625 private:
626     class ConnCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
627     public:
ConnCallbackDeathRecipient(NetConnService & client)628         explicit ConnCallbackDeathRecipient(NetConnService &client) : client_(client) {}
629         ~ConnCallbackDeathRecipient() override = default;
OnRemoteDied(const wptr<IRemoteObject> & remote)630         void OnRemoteDied(const wptr<IRemoteObject> &remote) override
631         {
632             client_.OnRemoteDied(remote);
633         }
634 
635     private:
636         NetConnService &client_;
637     };
638     class NetSupplierCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
639     public:
NetSupplierCallbackDeathRecipient(NetConnService & client)640         explicit NetSupplierCallbackDeathRecipient(NetConnService &client) : client_(client) {}
641         ~NetSupplierCallbackDeathRecipient() override = default;
OnRemoteDied(const wptr<IRemoteObject> & remote)642         void OnRemoteDied(const wptr<IRemoteObject> &remote) override
643         {
644             client_.OnNetSupplierRemoteDied(remote);
645         }
646 
647     private:
648         NetConnService &client_;
649     };
650 
651     void OnRemoteDied(const wptr<IRemoteObject> &remoteObject);
652     void OnNetSupplierRemoteDied(const wptr<IRemoteObject> &remoteObject);
653     void AddClientDeathRecipient(const sptr<INetConnCallback> &callback);
654     void AddNetSupplierDeathRecipient(const sptr<INetSupplierCallback> &callback);
655     void RemoveNetSupplierDeathRecipient(const sptr<INetSupplierCallback> &callback);
656     void RemoveClientDeathRecipient(const sptr<INetConnCallback> &callback);
657     void RemoveALLClientDeathRecipient();
658     void OnReceiveEvent(const EventFwk::CommonEventData &data);
659     void SubscribeCommonEvent(const std::string &eventName, EventReceiver receiver);
660     void HandlePowerMgrEvent(int code);
661     void HandleScreenEvent(bool isScreenOn);
662     std::mutex remoteMutex_;
663     sptr<IRemoteObject::DeathRecipient> deathRecipient_ = nullptr;
664     sptr<IRemoteObject::DeathRecipient> netSuplierDeathRecipient_ = nullptr;
665     std::vector<sptr<INetConnCallback>> remoteCallback_;
666     bool CheckIfSettingsDataReady();
667     std::mutex dataShareMutexWait;
668     std::condition_variable dataShareWait;
669 };
670 } // namespace NetManagerStandard
671 } // namespace OHOS
672 #endif // NET_CONN_SERVICE_H
673