• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 #include "wifi_net_agent.h"
17 #include <cinttypes>
18 #include <algorithm>
19 #include "inet_addr.h"
20 #include "ip_tools.h"
21 #include "iservice_registry.h"
22 #include "netsys_native_service_proxy.h"
23 #include "net_conn_client.h"
24 #include "system_ability_definition.h"
25 #include "wifi_common_util.h"
26 #include "wifi_logger.h"
27 #include "wifi_config_center.h"
28 #include "ipv6_address.h"
29 #include "wifi_global_func.h"
30 #include "wifi_app_state_aware.h"
31 
32 DEFINE_WIFILOG_LABEL("WifiNetAgent");
33 
34 namespace OHOS {
35 namespace Wifi {
36 constexpr const char *WIFI_NET_CONN_MGR_WORK_THREAD = "WIFI_NET_CONN_MGR_WORK_THREAD";
37 using namespace NetManagerStandard;
38 
39 #define INVALID_SUPPLIER_ID 0
40 #define ACCEPT_UNVALIDATED 7
41 
GetInstance()42 WifiNetAgent &WifiNetAgent::GetInstance()
43 {
44     static WifiNetAgent gWifiNetAgent;
45     return gWifiNetAgent;
46 }
47 
WifiNetAgent()48 WifiNetAgent::WifiNetAgent()
49 {
50     netAgentEventHandler_ = std::make_unique<WifiEventHandler>(WIFI_NET_CONN_MGR_WORK_THREAD);
51 }
~WifiNetAgent()52 WifiNetAgent::~WifiNetAgent()
53 {
54     if (netAgentEventHandler_) {
55         netAgentEventHandler_.reset();
56     }
57 }
58 
RegisterNetConnObserver(int instId)59 bool WifiNetAgent::RegisterNetConnObserver(int instId)
60 {
61     if (instId != INSTID_WLAN0) {
62         WIFI_LOGI("RegisterNetConnObserver instId is not 0.");
63         return false;
64     }
65 
66     bool isBtNet = IsDefaultBtNet();
67     WifiConfigCenter::GetInstance().SetAutoConnect(!isBtNet);
68 
69     if (netConnCallback_ == nullptr) {
70         netConnCallback_ = new (std::nothrow)NetInfoObserver();
71         if (netConnCallback_ == nullptr) {
72             WIFI_LOGE("RegisterNetConnObserver netConnCallback is null.");
73             return false;
74         }
75     }
76 
77     NetManagerStandard::NetSpecifier netSpecifier;
78     NetManagerStandard::NetAllCapabilities netAllCapabilities;
79     netAllCapabilities.netCaps_.insert(NetManagerStandard::NetCap::NET_CAPABILITY_INTERNET);
80     netSpecifier.ident_ = "";
81     netSpecifier.netCapabilities_ = netAllCapabilities;
82     sptr<NetManagerStandard::NetSpecifier> specifier = new NetManagerStandard::NetSpecifier(netSpecifier);
83     NetManagerStandard::NetConnClient::GetInstance().RegisterNetConnCallback(specifier, netConnCallback_, 0);
84     WIFI_LOGI("RegisterNetConnObserver success.");
85     return true;
86 }
87 
NetAvailable(sptr<NetManagerStandard::NetHandle> & netHandle)88 int32_t WifiNetAgent::NetInfoObserver::NetAvailable(sptr<NetManagerStandard::NetHandle> &netHandle)
89 {
90     bool isBtNet = IsDefaultBtNet();
91     WifiConfigCenter::GetInstance().SetAutoConnect(!isBtNet);
92     WIFI_LOGI("NetAvailable, isBtNet:%{public}d.", isBtNet);
93     return 0;
94 }
95 
IsDefaultBtNet()96 bool WifiNetAgent::IsDefaultBtNet()
97 {
98     NetManagerStandard::NetHandle defaultNet;
99     NetManagerStandard::NetConnClient::GetInstance().GetDefaultNet(defaultNet);
100     NetManagerStandard::NetAllCapabilities netAllCap;
101     NetConnClient::GetInstance().GetNetCapabilities(defaultNet, netAllCap);
102     return netAllCap.bearerTypes_.find(NetManagerStandard::BEARER_BLUETOOTH) != netAllCap.bearerTypes_.end();
103 }
104 
RegisterNetSupplier(int instId)105 bool WifiNetAgent::RegisterNetSupplier(int instId)
106 {
107     TimeStats timeStats(__func__);
108     WIFI_LOGI("Enter RegisterNetSupplier.");
109     std::unique_lock<std::mutex> lock(netAgentMutex_);
110 
111     using NetManagerStandard::NetBearType;
112     using NetManagerStandard::NetCap;
113     std::string ident = WifiConfigCenter::GetInstance().GetStaIfaceName(instId);
114     // wlan1 is not used as a standalone channel.
115     std::set<NetCap> netCaps = (instId == 0) ? std::set<NetCap>{NetCap::NET_CAPABILITY_INTERNET} : std::set<NetCap>{};
116     uint32_t& supplierIdNow = (instId == 0) ? supplierId : supplierIdForWlan1;
117     if (supplierIdNow != INVALID_SUPPLIER_ID) {
118         WIFI_LOGI("RegisterNetSupplier supplierId alread exist.");
119         return true;
120     }
121     int32_t result = NetConnClient::GetInstance().RegisterNetSupplier(NetBearType::BEARER_WIFI,
122                                                                       ident, netCaps, supplierIdNow);
123     if (result == NETMANAGER_SUCCESS) {
124         WIFI_LOGI("Register %{public}s successful, supplierId is [%{public}d]", ident.c_str(), supplierIdNow);
125         return true;
126     }
127     WIFI_LOGI("Register NetSupplier failed");
128     return false;
129 }
130 
RegisterNetSupplierCallback(int instId)131 bool WifiNetAgent::RegisterNetSupplierCallback(int instId)
132 {
133     TimeStats timeStats(__func__);
134     WIFI_LOGI("Enter RegisterNetSupplierCallback.");
135     std::unique_lock<std::mutex> lock(netAgentMutex_);
136     sptr<NetConnCallback> pNetConnCallback = (std::make_unique<NetConnCallback>()).release();
137     if (pNetConnCallback == nullptr) {
138         WIFI_LOGE("pNetConnCallback is null\n");
139         return false;
140     }
141 
142     uint32_t& supplierIdNow = (instId == 0) ? supplierId : supplierIdForWlan1;
143     int32_t result = NetConnClient::GetInstance().RegisterNetSupplierCallback(supplierIdNow, pNetConnCallback);
144     if (result == NETMANAGER_SUCCESS) {
145         WIFI_LOGI("Register NetSupplierCallback successful");
146         return true;
147     }
148     WIFI_LOGE("Register NetSupplierCallback failed [%{public}d]", result);
149     return false;
150 }
151 
UnregisterNetSupplier(int instId)152 void WifiNetAgent::UnregisterNetSupplier(int instId)
153 {
154     TimeStats timeStats(__func__);
155     WIFI_LOGI("Enter UnregisterNetSupplier.");
156     std::unique_lock<std::mutex> lock(netAgentMutex_);
157     uint32_t& supplierIdNow = (instId == 0) ? supplierId : supplierIdForWlan1;
158     int32_t result = NetConnClient::GetInstance().UnregisterNetSupplier(supplierIdNow);
159     WIFI_LOGI("Unregister network result:%{public}d", result);
160     supplierIdNow = INVALID_SUPPLIER_ID;
161 }
162 
UpdateNetSupplierInfo(const sptr<NetManagerStandard::NetSupplierInfo> & netSupplierInfo,int instId)163 void WifiNetAgent::UpdateNetSupplierInfo(const sptr<NetManagerStandard::NetSupplierInfo> &netSupplierInfo, int instId)
164 {
165     TimeStats timeStats(__func__);
166     WIFI_LOGI("Enter UpdateNetSupplierInfo.");
167     std::unique_lock<std::mutex> lock(netAgentMutex_);
168     if (instId >= 0 && instId < STA_INSTANCE_MAX_NUM) {
169         isWifiAvailable_[instId] = netSupplierInfo->isAvailable_;
170     }
171     uint32_t& supplierIdNow = (instId == 0) ? supplierId : supplierIdForWlan1;
172     int32_t result = NetConnClient::GetInstance().UpdateNetSupplierInfo(supplierIdNow, netSupplierInfo);
173     WIFI_LOGI("Update network result:%{public}d", result);
174 }
175 
UpdateNetLinkInfo(IpInfo & wifiIpInfo,IpV6Info & wifiIpV6Info,WifiProxyConfig & wifiProxyConfig,int instId)176 void WifiNetAgent::UpdateNetLinkInfo(IpInfo &wifiIpInfo, IpV6Info &wifiIpV6Info, WifiProxyConfig &wifiProxyConfig,
177     int instId)
178 {
179     TimeStats timeStats(__func__);
180     WIFI_LOGI("Enter UpdateNetLinkInfo.");
181     std::unique_lock<std::mutex> lock(netAgentMutex_);
182     if (instId >= 0 && instId < STA_INSTANCE_MAX_NUM && !isWifiAvailable_[instId]) {
183         WIFI_LOGE("wifi is not avaliable, no need UpdateNetLinkInfo");
184         return;
185     }
186     sptr<NetManagerStandard::NetLinkInfo> netLinkInfo = (std::make_unique<NetManagerStandard::NetLinkInfo>()).release();
187     if (netLinkInfo == nullptr) {
188         WIFI_LOGE("%{public}s netLinkInfo is null", __func__);
189         return;
190     }
191     CreateNetLinkInfo(netLinkInfo, wifiIpInfo, wifiIpV6Info, wifiProxyConfig, instId);
192     uint32_t& supplierIdNow = (instId == 0) ? supplierId : supplierIdForWlan1;
193     int32_t result = NetConnClient::GetInstance().UpdateNetLinkInfo(supplierIdNow, netLinkInfo);
194     WIFI_LOGI("UpdateNetLinkInfo result:%{public}d", result);
195 }
196 
AddRoute(const std::string interface,const std::string ipAddress,int prefixLength)197 bool WifiNetAgent::AddRoute(const std::string interface, const std::string ipAddress, int prefixLength)
198 {
199     TimeStats timeStats(__func__);
200     LOGI("NetAgent add route");
201     unsigned int ipInt = IpTools::ConvertIpv4Address(ipAddress);
202     std::string mask = IpTools::ConvertIpv4Mask(prefixLength);
203     unsigned int maskInt = IpTools::ConvertIpv4Address(mask);
204     std::string strLocalRoute = IpTools::ConvertIpv4Address(ipInt & maskInt);
205     std::string destAddress = strLocalRoute + "/" + std::to_string(prefixLength);
206 
207     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
208     if (samgr == nullptr) {
209         LOGE("GetSystemAbilityManager failed!");
210         return false;
211     }
212     auto remote = samgr->GetSystemAbility(COMM_NETSYS_NATIVE_SYS_ABILITY_ID);
213     if (remote == nullptr) {
214         LOGE("GetSystemAbility failed!");
215         return false;
216     }
217     OHOS::sptr<OHOS::NetsysNative::INetsysService> netsysService = iface_cast<NetsysNative::INetsysService>(remote);
218     if (netsysService == nullptr) {
219         LOGE("NetdService is nullptr!");
220         return false;
221     }
222     LOGI("Add route, interface: %{public}s, destAddress: %{public}s, ipAddress: %{public}s, prefixLength: %{public}d",
223         interface.c_str(), IpAnonymize(destAddress).c_str(), IpAnonymize(ipAddress).c_str(), prefixLength);
224     netsysService->NetworkAddRoute(OHOS::nmd::LOCAL_NETWORK_NETID, interface, destAddress, ipAddress);
225     LOGI("NetAgent add route finish");
226     return true;
227 }
228 
DelInterfaceAddress(const std::string & interface,const std::string & ipAddress,int prefixLength)229 bool WifiNetAgent::DelInterfaceAddress(const std::string &interface, const std::string &ipAddress, int prefixLength)
230 {
231     int32_t result = NetConnClient::GetInstance().DelInterfaceAddress(interface, ipAddress, prefixLength);
232     if (result == NETMANAGER_SUCCESS) {
233         WIFI_LOGI("DelInterfaceAddress successful");
234         return true;
235     }
236     WIFI_LOGI("DelInterfaceAddress failed");
237     return false;
238 }
239 
OnStaMachineUpdateNetLinkInfo(IpInfo wifiIpInfo,IpV6Info wifiIpV6Info,WifiProxyConfig wifiProxyConfig,int instId)240 void WifiNetAgent::OnStaMachineUpdateNetLinkInfo(IpInfo wifiIpInfo, IpV6Info wifiIpV6Info,
241     WifiProxyConfig wifiProxyConfig, int instId)
242 {
243     if (netAgentEventHandler_) {
244         netAgentEventHandler_->PostSyncTask(
245             [this, wifiIpInfo, wifiIpV6Info, wifiProxyConfig, instId]() mutable {
246                 this->UpdateNetLinkInfo(wifiIpInfo, wifiIpV6Info, wifiProxyConfig, instId);
247             });
248     }
249 }
250 
OnStaMachineUpdateNetSupplierInfo(const sptr<NetManagerStandard::NetSupplierInfo> netSupplierInfo,int instId)251 void WifiNetAgent::OnStaMachineUpdateNetSupplierInfo(const sptr<NetManagerStandard::NetSupplierInfo> netSupplierInfo,
252     int instId)
253 {
254     if (netAgentEventHandler_) {
255         netAgentEventHandler_->PostSyncTask([this, netInfo = netSupplierInfo, m_instId = instId]() {
256            this->UpdateNetSupplierInfo(netInfo, m_instId);
257         });
258     }
259 }
260 
OnStaMachineWifiStart(int instId)261 void WifiNetAgent::OnStaMachineWifiStart(int instId)
262 {
263     if (netAgentEventHandler_) {
264         netAgentEventHandler_->PostSyncTask([this, m_instId = instId]() {
265             this->RegisterNetSupplier(m_instId);
266             this->RegisterNetSupplierCallback(m_instId);
267             this->RegisterNetConnObserver(m_instId);
268         });
269     }
270 }
271 
OnStaMachineNetManagerRestart(const sptr<NetManagerStandard::NetSupplierInfo> netSupplierInfo,int instId)272 void WifiNetAgent::OnStaMachineNetManagerRestart(const sptr<NetManagerStandard::NetSupplierInfo> netSupplierInfo,
273     int instId)
274 {
275     if (!netAgentEventHandler_) {
276         WIFI_LOGE("%{public}s netAgentEventHandler_ is null", __func__);
277         return;
278     }
279     netAgentEventHandler_->PostSyncTask([this, supplierInfo = netSupplierInfo, m_instId = instId]() {
280         this->RegisterNetSupplier(m_instId);
281         this->RegisterNetSupplierCallback(m_instId);
282         this->RegisterNetConnObserver(m_instId);
283         WifiLinkedInfo linkedInfo;
284         WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo, m_instId);
285         if (linkedInfo.connState == ConnState::CONNECTED) {
286 #ifndef OHOS_ARCH_LITE
287             if (supplierInfo != nullptr) {
288                 TimeStats timeStats("Call UpdateNetSupplierInfo");
289                 this->UpdateNetSupplierInfo(supplierInfo, m_instId);
290             }
291 #endif
292             IpInfo wifiIpInfo;
293             WifiConfigCenter::GetInstance().GetIpInfo(wifiIpInfo, m_instId);
294             IpV6Info wifiIpV6Info;
295             WifiConfigCenter::GetInstance().GetIpv6Info(wifiIpV6Info, m_instId);
296             WifiDeviceConfig config;
297             WifiSettings::GetInstance().GetDeviceConfig(linkedInfo.networkId, config);
298             this->UpdateNetLinkInfo(wifiIpInfo, wifiIpV6Info, config.wifiProxyconfig, m_instId);
299         }
300     });
301 }
302 
CreateNetLinkInfo(sptr<NetManagerStandard::NetLinkInfo> & netLinkInfo,IpInfo & wifiIpInfo,IpV6Info & wifiIpV6Info,WifiProxyConfig & wifiProxyConfig,int instId)303 void WifiNetAgent::CreateNetLinkInfo(sptr<NetManagerStandard::NetLinkInfo> &netLinkInfo, IpInfo &wifiIpInfo,
304     IpV6Info &wifiIpV6Info, WifiProxyConfig &wifiProxyConfig, int instId)
305 {
306     netLinkInfo->ifaceName_ = WifiConfigCenter::GetInstance().GetStaIfaceName(instId);
307 
308     SetNetLinkIPInfo(netLinkInfo, wifiIpInfo, wifiIpV6Info);
309     SetNetLinkHostRouteInfo(netLinkInfo, wifiIpInfo);
310     SetNetLinkRouteInfo(netLinkInfo, wifiIpInfo, wifiIpV6Info);
311     SetNetLinkDnsInfo(netLinkInfo, wifiIpInfo, wifiIpV6Info);
312     SetNetLinkLocalRouteInfo(netLinkInfo, wifiIpInfo, wifiIpV6Info);
313     if (wifiProxyConfig.configureMethod == ConfigureProxyMethod::AUTOCONFIGUE) {
314         /* Automatic proxy is not supported */
315     } else if (wifiProxyConfig.configureMethod == ConfigureProxyMethod::MANUALCONFIGUE) {
316         std::vector<std::string> exclusionList;
317         wifiProxyConfig.manualProxyConfig.GetExclusionObjectList(exclusionList);
318         std::list<std::string> tmpExclusionList;
319         std::copy_if(exclusionList.begin(), exclusionList.end(), std::back_inserter(tmpExclusionList),
320             [](const std::string &str) { return !str.empty(); } );
321         netLinkInfo->httpProxy_.SetHost(std::move(wifiProxyConfig.manualProxyConfig.serverHostName));
322         netLinkInfo->httpProxy_.SetPort(wifiProxyConfig.manualProxyConfig.serverPort);
323         netLinkInfo->httpProxy_.SetExclusionList(tmpExclusionList);
324     } else {
325         netLinkInfo->httpProxy_.SetHost("");
326         netLinkInfo->httpProxy_.SetPort(0);
327     }
328 
329     return;
330 }
331 
SetNetLinkIPInfo(sptr<NetManagerStandard::NetLinkInfo> & netLinkInfo,IpInfo & wifiIpInfo,IpV6Info & wifiIpV6Info)332 void WifiNetAgent::SetNetLinkIPInfo(sptr<NetManagerStandard::NetLinkInfo> &netLinkInfo, IpInfo &wifiIpInfo,
333     IpV6Info &wifiIpV6Info)
334 {
335     unsigned int prefixLength =
336         static_cast<unsigned int>(IpTools::GetMaskLength(IpTools::ConvertIpv4Address(wifiIpInfo.netmask)));
337     sptr<NetManagerStandard::INetAddr> netAddr = (std::make_unique<NetManagerStandard::INetAddr>()).release();
338     if (netAddr == nullptr) {
339         WIFI_LOGE("%{public}s netAddr is null", __func__);
340         return;
341     }
342     netAddr->type_ = NetManagerStandard::INetAddr::IPV4;
343     netAddr->family_ = NetManagerStandard::INetAddr::IPV4;
344     netAddr->address_ = IpTools::ConvertIpv4Address(wifiIpInfo.ipAddress);
345     netAddr->netMask_ = IpTools::ConvertIpv4Address(wifiIpInfo.netmask);
346     netAddr->prefixlen_ = prefixLength;
347     netLinkInfo->netAddrList_.push_back(*netAddr);
348 
349     sptr<NetManagerStandard::INetAddr> netIpv6Addr = (std::make_unique<NetManagerStandard::INetAddr>()).release();
350     if (netIpv6Addr == nullptr) {
351         WIFI_LOGE("%{public}s netIpv6Addr is null", __func__);
352         return;
353     }
354     netIpv6Addr->type_ = NetManagerStandard::INetAddr::IPV6;
355     netIpv6Addr->family_ = NetManagerStandard::INetAddr::IPV6;
356     netIpv6Addr->netMask_ = wifiIpV6Info.netmask;
357     netIpv6Addr->prefixlen_ = 0;
358     if (!wifiIpV6Info.globalIpV6Address.empty()) {
359         netIpv6Addr->address_ = wifiIpV6Info.globalIpV6Address;
360         netLinkInfo->netAddrList_.push_back(*netIpv6Addr);
361         LOGI("SetNetLinkIPInfo globalIpv6:%{public}s", MacAnonymize(wifiIpV6Info.globalIpV6Address).c_str());
362     }
363     if (!wifiIpV6Info.randGlobalIpV6Address.empty()) {
364         netIpv6Addr->address_ = wifiIpV6Info.randGlobalIpV6Address;
365         netLinkInfo->netAddrList_.push_back(*netIpv6Addr);
366         LOGI("SetNetLinkIPInfo randGlobalIpv6:%{public}s", MacAnonymize(wifiIpV6Info.randGlobalIpV6Address).c_str());
367     }
368     if (!wifiIpV6Info.uniqueLocalAddress1.empty()) {
369         netIpv6Addr->address_ = wifiIpV6Info.uniqueLocalAddress1;
370         netLinkInfo->netAddrList_.push_back(*netIpv6Addr);
371         LOGI("SetNetLinkIPInfo LocalIpv6:%{public}s", MacAnonymize(wifiIpV6Info.uniqueLocalAddress1).c_str());
372     }
373     if (!wifiIpV6Info.uniqueLocalAddress2.empty()) {
374         netIpv6Addr->address_ = wifiIpV6Info.uniqueLocalAddress2;
375         netLinkInfo->netAddrList_.push_back(*netIpv6Addr);
376         LOGI("SetNetLinkIPInfo randLocalIpv6:%{public}s", MacAnonymize(wifiIpV6Info.uniqueLocalAddress2).c_str());
377     }
378 }
379 
SetNetLinkDnsInfo(sptr<NetManagerStandard::NetLinkInfo> & netLinkInfo,IpInfo & wifiIpInfo,IpV6Info & wifiIpV6Info)380 void WifiNetAgent::SetNetLinkDnsInfo(sptr<NetManagerStandard::NetLinkInfo> &netLinkInfo, IpInfo &wifiIpInfo,
381     IpV6Info &wifiIpV6Info)
382 {
383     sptr<NetManagerStandard::INetAddr> dns = (std::make_unique<NetManagerStandard::INetAddr>()).release();
384     if (dns == nullptr) {
385         WIFI_LOGE("%{public}s dns is null", __func__);
386         return;
387     }
388     dns->type_ = NetManagerStandard::INetAddr::IPV4;
389     dns->family_ = NetManagerStandard::INetAddr::IPV4;
390     for (auto iter = wifiIpInfo.dnsAddr.begin(); iter != wifiIpInfo.dnsAddr.end(); iter++) {
391         dns->address_ = IpTools::ConvertIpv4Address(*iter);
392         netLinkInfo->dnsList_.push_back(*dns);
393         LOGI("SetNetLinkDnsInfo ipv4 address:%{public}s", IpAnonymize(dns->address_).c_str());
394     }
395     sptr<NetManagerStandard::INetAddr> ipv6dns = (std::make_unique<NetManagerStandard::INetAddr>()).release();
396     if (ipv6dns == nullptr) {
397         WIFI_LOGE("%{public}s ipv6dns is null", __func__);
398         return;
399     }
400     ipv6dns->type_ = NetManagerStandard::INetAddr::IPV6;
401     ipv6dns->family_ = NetManagerStandard::INetAddr::IPV6;
402     for (auto iter = wifiIpV6Info.dnsAddr.begin(); iter != wifiIpV6Info.dnsAddr.end(); iter++) {
403         ipv6dns->address_ = *iter;
404         netLinkInfo->dnsList_.push_back(*ipv6dns);
405         LOGI("SetNetLinkDnsInfo ipv6:%{public}s", MacAnonymize(ipv6dns->address_).c_str());
406     }
407 }
408 
SetNetLinkRouteInfo(sptr<NetManagerStandard::NetLinkInfo> & netLinkInfo,IpInfo & wifiIpInfo,IpV6Info & wifiIpV6Info)409 void WifiNetAgent::SetNetLinkRouteInfo(sptr<NetManagerStandard::NetLinkInfo> &netLinkInfo, IpInfo &wifiIpInfo,
410     IpV6Info &wifiIpV6Info)
411 {
412     sptr<NetManagerStandard::Route> route = (std::make_unique<NetManagerStandard::Route>()).release();
413     if (route == nullptr) {
414         WIFI_LOGE("%{public}s route is null", __func__);
415         return;
416     }
417     route->iface_ = netLinkInfo->ifaceName_;
418     route->destination_.type_ = NetManagerStandard::INetAddr::IPV4;
419     route->destination_.address_ = "0.0.0.0";
420     route->destination_.family_ = NetManagerStandard::INetAddr::IPV4;
421     route->gateway_.address_ = IpTools::ConvertIpv4Address(wifiIpInfo.gateway);
422     route->gateway_.family_ = NetManagerStandard::INetAddr::IPV4;
423     netLinkInfo->routeList_.push_back(*route);
424     LOGI("SetNetLinkRouteInfo gateway:%{public}s", IpAnonymize(route->gateway_.address_).c_str());
425     if (!wifiIpV6Info.gateway.empty()) {
426         sptr<NetManagerStandard::Route> ipv6route = (std::make_unique<NetManagerStandard::Route>()).release();
427         if (ipv6route == nullptr) {
428             WIFI_LOGE("%{public}s ipv6route is null", __func__);
429             return;
430         }
431         ipv6route->iface_ = netLinkInfo->ifaceName_;
432         ipv6route->destination_.type_ = NetManagerStandard::INetAddr::IPV6;
433         ipv6route->destination_.family_ = NetManagerStandard::INetAddr::IPV6;
434         ipv6route->destination_.address_ = "::";
435         ipv6route->destination_.prefixlen_ = 0;
436         ipv6route->gateway_.address_ = wifiIpV6Info.gateway;
437         ipv6route->gateway_.family_ = NetManagerStandard::INetAddr::IPV6;
438         netLinkInfo->routeList_.push_back(*ipv6route);
439         LOGI("SetNetLinkRouteInfo gateway:%{public}s", MacAnonymize(wifiIpV6Info.gateway).c_str());
440     }
441 }
442 
SetNetLinkHostRouteInfo(sptr<NetManagerStandard::NetLinkInfo> & netLinkInfo,IpInfo & wifiIpInfo)443 void WifiNetAgent::SetNetLinkHostRouteInfo(sptr<NetManagerStandard::NetLinkInfo> &netLinkInfo, IpInfo &wifiIpInfo)
444 {
445     if ((wifiIpInfo.ipAddress & wifiIpInfo.netmask) != (wifiIpInfo.gateway & wifiIpInfo.netmask)) {
446         sptr<NetManagerStandard::Route> hostRoute = (std::make_unique<NetManagerStandard::Route>()).release();
447         if (hostRoute == nullptr) {
448             WIFI_LOGE("%{public}s hostRoute is null", __func__);
449             return;
450         }
451         hostRoute->iface_ = netLinkInfo->ifaceName_;
452         hostRoute->destination_.type_ = NetManagerStandard::INetAddr::IPV4;
453         hostRoute->destination_.address_ = IpTools::ConvertIpv4Address(wifiIpInfo.gateway);
454         hostRoute->destination_.family_ = NetManagerStandard::INetAddr::IPV4;
455         hostRoute->destination_.prefixlen_ = MAX_PREFIX_LEN;
456         hostRoute->gateway_.address_ = "0.0.0.0";
457         netLinkInfo->routeList_.push_back(*hostRoute);
458         LOGI("SetNetLinkHostRouteInfo gateway:%{public}s", IpAnonymize(hostRoute->gateway_.address_).c_str());
459     }
460 }
461 
SetNetLinkLocalRouteInfo(sptr<NetManagerStandard::NetLinkInfo> & netLinkInfo,IpInfo & wifiIpInfo,IpV6Info & wifiIpV6Info)462 void WifiNetAgent::SetNetLinkLocalRouteInfo(sptr<NetManagerStandard::NetLinkInfo> &netLinkInfo, IpInfo &wifiIpInfo,
463     IpV6Info &wifiIpV6Info)
464 {
465     unsigned int prefixLength =
466         static_cast<unsigned int>(IpTools::GetMaskLength(IpTools::ConvertIpv4Address(wifiIpInfo.netmask)));
467     sptr<NetManagerStandard::Route> localRoute = (std::make_unique<NetManagerStandard::Route>()).release();
468     if (localRoute == nullptr) {
469         WIFI_LOGE("%{public}s localRoute is null", __func__);
470         return;
471     }
472     std::string strLocalRoute = IpTools::ConvertIpv4Address(wifiIpInfo.ipAddress & wifiIpInfo.netmask);
473     localRoute->iface_ = netLinkInfo->ifaceName_;
474     localRoute->destination_.type_ = NetManagerStandard::INetAddr::IPV4;
475     localRoute->destination_.address_ = strLocalRoute;
476     localRoute->destination_.prefixlen_ = prefixLength;
477     localRoute->gateway_.address_ = "0.0.0.0";
478     netLinkInfo->routeList_.push_back(*localRoute);
479     LOGI("SetNetLinkLocalRouteInfo ifaceName_:%{public}s %{public}u %{public}s", netLinkInfo->ifaceName_.c_str(),
480         prefixLength, IpAnonymize(strLocalRoute).c_str());
481     if (!wifiIpV6Info.netmask.empty()) {
482         unsigned int ipv6PrefixLength = IpTools::GetIPV6MaskLength(wifiIpV6Info.netmask);
483         sptr<NetManagerStandard::Route> ipv6route = (std::make_unique<NetManagerStandard::Route>()).release();
484         if (ipv6route == nullptr) {
485             WIFI_LOGE("%{public}s ipv6route is null", __func__);
486             return;
487         }
488         ipv6route->iface_ = netLinkInfo->ifaceName_;
489         ipv6route->destination_.type_ = NetManagerStandard::INetAddr::IPV6;
490         ipv6route->destination_.prefixlen_ = ipv6PrefixLength;
491         ipv6route->gateway_.address_ = "";
492         if (!wifiIpV6Info.globalIpV6Address.empty()) {
493             ipv6route->destination_.address_ =
494                 Ipv6Address::GetPrefixByAddr(wifiIpV6Info.globalIpV6Address, ipv6PrefixLength);
495             netLinkInfo->routeList_.push_back(*ipv6route);
496             LOGI("SetNetLinkLocalRouteInfo ipv6PrefixLength:%{public}u globalIpv6:%{public}s", ipv6PrefixLength,
497                 MacAnonymize(wifiIpV6Info.globalIpV6Address).c_str());
498         }
499         if (!wifiIpV6Info.uniqueLocalAddress1.empty()) {
500             ipv6route->destination_.address_ =
501                 Ipv6Address::GetPrefixByAddr(wifiIpV6Info.uniqueLocalAddress1, ipv6PrefixLength);
502             netLinkInfo->routeList_.push_back(*ipv6route);
503             LOGI("SetNetLinkLocalRouteInfo ipv6PrefixLength:%{public}u uniqueLocalIpv6:%{public}s", ipv6PrefixLength,
504                 MacAnonymize(wifiIpV6Info.uniqueLocalAddress1).c_str());
505         }
506     }
507 }
508 
InitWifiNetAgent(const WifiNetAgentCallbacks & wifiNetAgentCallbacks)509 void WifiNetAgent::InitWifiNetAgent(const WifiNetAgentCallbacks &wifiNetAgentCallbacks)
510 {
511     wifiNetAgentCallbacks_ = wifiNetAgentCallbacks;
512 }
513 
ResetSupplierId()514 void WifiNetAgent::ResetSupplierId()
515 {
516     supplierId = INVALID_SUPPLIER_ID;
517 }
518 
GetSupplierId()519 uint32_t WifiNetAgent::GetSupplierId()
520 {
521     return supplierId;
522 }
523 
RequestNetwork(const int uid,const int networkId)524 bool WifiNetAgent::RequestNetwork(const int uid, const int networkId)
525 {
526     if (!wifiNetAgentCallbacks_.OnRequestNetwork) {
527         WIFI_LOGE("OnRequestNetwork is nullptr.");
528         return false;
529     }
530     if (wifiNetAgentCallbacks_.OnRequestNetwork(uid, networkId)) {
531         return true;
532     }
533     return false;
534 }
535 
NetConnCallback()536 WifiNetAgent::NetConnCallback::NetConnCallback()
537 {
538 }
539 
~NetConnCallback()540 WifiNetAgent::NetConnCallback::~NetConnCallback()
541 {}
542 
RequestNetwork(const std::string & ident,const std::set<NetManagerStandard::NetCap> & netCaps,const NetManagerStandard::NetRequest & netrequest)543 int32_t WifiNetAgent::NetConnCallback::RequestNetwork(
544     const std::string &ident, const std::set<NetManagerStandard::NetCap> &netCaps,
545     const NetManagerStandard::NetRequest &netrequest)
546 {
547     WIFI_LOGD("Enter NetConnCallback::RequestNetwork");
548     LogNetCaps(ident, netCaps);
549 #ifndef OHOS_ARCH_LITE
550     std::string netrequestIdent = netrequest.ident;
551     int networkId = CheckDataLegal(netrequestIdent);
552     if (networkId <= INVALID_NETWORK_ID || std::to_string(networkId) != netrequest.ident) {
553         WIFI_LOGD("networkId is invaild.");
554         return -1;
555     }
556     if (requestIds_.find(netrequest.requestId) != requestIds_.end()) {
557         return -1;
558     }
559     requestIds_.insert(netrequest.requestId);
560 
561     WIFI_LOGI("RequestNetwork uid[%{public}d], networkId[%{public}d].", netrequest.uid, networkId);
562     if (!WifiAppStateAware::GetInstance().IsForegroundApp(netrequest.uid)) {
563         WIFI_LOGE("App is not in foreground.");
564         return -1;
565     }
566 
567     WifiLinkedInfo linkedInfo;
568     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
569     if (linkedInfo.connState == ConnState::CONNECTING || linkedInfo.connState == ConnState::CONNECTED) {
570         if (linkedInfo.networkId == networkId) {
571             WIFI_LOGI("RequestNetwork networkId is connecting or connected.");
572             return 0;
573         }
574     }
575 
576     if (!WifiNetAgent::GetInstance().RequestNetwork(netrequest.uid, networkId)) {
577         WIFI_LOGE("RequestNetwork fail.");
578         return -1;
579     }
580 #endif
581     return 0;
582 }
583 
ReleaseNetwork(const NetManagerStandard::NetRequest & netrequest)584 int32_t WifiNetAgent::NetConnCallback::ReleaseNetwork(const NetManagerStandard::NetRequest &netrequest)
585 {
586     WIFI_LOGD("Enter NetConnCallback::ReleaseNetwork");
587     LogNetCaps(netrequest.ident, netrequest.netCaps);
588     return 0;
589 }
590 
LogNetCaps(const std::string & ident,const std::set<NetManagerStandard::NetCap> & netCaps) const591 void WifiNetAgent::NetConnCallback::LogNetCaps(
592     const std::string &ident, const std::set<NetManagerStandard::NetCap> &netCaps) const
593 {
594     WIFI_LOGD("ident=[%s]", ident.c_str());
595     std::string logStr;
596     const std::string logStrEnd("]");
597     logStr = "netCaps[";
598     for (auto netCap : netCaps) {
599         logStr += std::to_string(static_cast<uint32_t>(netCap));
600         logStr += " ";
601     }
602     logStr += logStrEnd;
603     WIFI_LOGD("%{public}s", logStr.c_str());
604 }
605 
RestoreWifiConnection()606 void WifiNetAgent::RestoreWifiConnection()
607 {
608     using NetManagerStandard::NetBearType;
609     int32_t result = NetConnClient::GetInstance().UpdateSupplierScore(supplierId, ACCEPT_UNVALIDATED);
610     WIFI_LOGI("Restore Wifi Connection, result:%{public}d", result);
611 }
612 }
613 }
614