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