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