• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 #include "connection_exec.h"
17 
18 #include <cstddef>
19 #include <cstdint>
20 #include <string>
21 
22 #include "constant.h"
23 #include "errorcode_convertor.h"
24 #include "napi_utils.h"
25 #include "net_conn_callback_observer.h"
26 #include "net_conn_client.h"
27 #include "net_handle_interface.h"
28 #include "net_manager_constants.h"
29 #include "netconnection.h"
30 #include "netmanager_base_common_utils.h"
31 #include "netmanager_base_log.h"
32 #include "securec.h"
33 
34 namespace OHOS::NetManagerStandard {
35 namespace {
36 constexpr int32_t NO_PERMISSION_CODE = 1;
37 constexpr int32_t PERMISSION_DENIED_CODE = 13;
38 constexpr int32_t NET_UNREACHABLE_CODE = 101;
39 } // namespace
40 
CreateNetHandle(napi_env env,NetHandle * handle)41 napi_value ConnectionExec::CreateNetHandle(napi_env env, NetHandle *handle)
42 {
43     napi_value netHandle = NapiUtils::CreateObject(env);
44     if (NapiUtils::GetValueType(env, netHandle) != napi_object) {
45         return NapiUtils::GetUndefined(env);
46     }
47 
48     std::initializer_list<napi_property_descriptor> properties = {
49         DECLARE_NAPI_FUNCTION(NetHandleInterface::FUNCTION_GET_ADDRESSES_BY_NAME,
50                               NetHandleInterface::GetAddressesByName),
51         DECLARE_NAPI_FUNCTION(NetHandleInterface::FUNCTION_GET_ADDRESS_BY_NAME,
52                               NetHandleInterface::GetAddressByName),
53         DECLARE_NAPI_FUNCTION(NetHandleInterface::FUNCTION_BIND_SOCKET,
54                               NetHandleInterface::BindSocket),
55     };
56     NapiUtils::DefineProperties(env, netHandle, properties);
57     NapiUtils::SetUint32Property(env, netHandle, NetHandleInterface::PROPERTY_NET_ID, handle->GetNetId());
58     return netHandle;
59 }
60 
CreateNetCapabilities(napi_env env,NetAllCapabilities * capabilities)61 napi_value ConnectionExec::CreateNetCapabilities(napi_env env, NetAllCapabilities *capabilities)
62 {
63     napi_value netCapabilities = NapiUtils::CreateObject(env);
64     if (NapiUtils::GetValueType(env, netCapabilities) != napi_object) {
65         return NapiUtils::GetUndefined(env);
66     }
67 
68     NapiUtils::SetUint32Property(env, netCapabilities, KEY_LINK_UP_BAND_WIDTH_KPS, capabilities->linkUpBandwidthKbps_);
69     NapiUtils::SetUint32Property(env, netCapabilities, KEY_LINK_DOWN_BAND_WIDTH_KPS,
70                                  capabilities->linkDownBandwidthKbps_);
71     if (!capabilities->netCaps_.empty() && capabilities->netCaps_.size() <= MAX_ARRAY_LENGTH) {
72         napi_value networkCap = NapiUtils::CreateArray(env, std::min(capabilities->netCaps_.size(), MAX_ARRAY_LENGTH));
73         auto it = capabilities->netCaps_.begin();
74         for (uint32_t index = 0; index < MAX_ARRAY_LENGTH && it != capabilities->netCaps_.end(); ++index, ++it) {
75             NapiUtils::SetArrayElement(env, networkCap, index, NapiUtils::CreateUint32(env, *it));
76         }
77         NapiUtils::SetNamedProperty(env, netCapabilities, KEY_NETWORK_CAP, networkCap);
78     }
79     if (!capabilities->bearerTypes_.empty() && capabilities->bearerTypes_.size() <= MAX_ARRAY_LENGTH) {
80         napi_value bearerTypes =
81             NapiUtils::CreateArray(env, std::min(capabilities->bearerTypes_.size(), MAX_ARRAY_LENGTH));
82         auto it = capabilities->bearerTypes_.begin();
83         for (uint32_t index = 0; index < MAX_ARRAY_LENGTH && it != capabilities->bearerTypes_.end(); ++index, ++it) {
84             NapiUtils::SetArrayElement(env, bearerTypes, index, NapiUtils::CreateUint32(env, *it));
85         }
86         NapiUtils::SetNamedProperty(env, netCapabilities, KEY_BEARER_TYPE, bearerTypes);
87     }
88     return netCapabilities;
89 }
90 
CreateConnectionProperties(napi_env env,NetLinkInfo * linkInfo)91 napi_value ConnectionExec::CreateConnectionProperties(napi_env env, NetLinkInfo *linkInfo)
92 {
93     napi_value connectionProperties = NapiUtils::CreateObject(env);
94     if (NapiUtils::GetValueType(env, connectionProperties) != napi_object) {
95         return NapiUtils::GetUndefined(env);
96     }
97     NapiUtils::SetStringPropertyUtf8(env, connectionProperties, KEY_INTERFACE_NAME, linkInfo->ifaceName_);
98     NapiUtils::SetStringPropertyUtf8(env, connectionProperties, KEY_DOMAINS, linkInfo->domain_);
99     NapiUtils::SetUint32Property(env, connectionProperties, KEY_MTU, linkInfo->mtu_);
100     FillLinkAddress(env, connectionProperties, linkInfo);
101     FillRouoteList(env, connectionProperties, linkInfo);
102     FillDns(env, connectionProperties, linkInfo);
103     return connectionProperties;
104 }
105 
ExecGetAddressByName(GetAddressByNameContext * context)106 bool ConnectionExec::ExecGetAddressByName(GetAddressByNameContext *context)
107 {
108     return NetHandleExec::ExecGetAddressesByName(context);
109 }
110 
GetAddressByNameCallback(GetAddressByNameContext * context)111 napi_value ConnectionExec::GetAddressByNameCallback(GetAddressByNameContext *context)
112 {
113     return NetHandleExec::GetAddressesByNameCallback(context);
114 }
115 
ExecGetDefaultNet(GetDefaultNetContext * context)116 bool ConnectionExec::ExecGetDefaultNet(GetDefaultNetContext *context)
117 {
118     auto ret = NetConnClient::GetInstance().GetDefaultNet(context->netHandle_);
119     if (ret != NETMANAGER_SUCCESS) {
120         NETMANAGER_BASE_LOGE("get default net failed %{public}d", ret);
121         context->SetErrorCode(ret);
122     }
123     return ret == NETMANAGER_SUCCESS;
124 }
125 
GetDefaultNetCallback(GetDefaultNetContext * context)126 napi_value ConnectionExec::GetDefaultNetCallback(GetDefaultNetContext *context)
127 {
128     return CreateNetHandle(context->GetEnv(), &context->netHandle_);
129 }
130 
ExecHasDefaultNet(HasDefaultNetContext * context)131 bool ConnectionExec::ExecHasDefaultNet(HasDefaultNetContext *context)
132 {
133     auto ret = NetConnClient::GetInstance().HasDefaultNet(context->hasDefaultNet_);
134     if (ret != NETMANAGER_SUCCESS && ret != NET_CONN_ERR_NO_DEFAULT_NET) {
135         NETMANAGER_BASE_LOGE("ExecHasDefaultNet ret %{public}d", ret);
136         context->SetErrorCode(ret);
137         return false;
138     }
139     return true;
140 }
141 
HasDefaultNetCallback(HasDefaultNetContext * context)142 napi_value ConnectionExec::HasDefaultNetCallback(HasDefaultNetContext *context)
143 {
144     return NapiUtils::GetBoolean(context->GetEnv(), context->hasDefaultNet_);
145 }
146 
ExecIsDefaultNetMetered(IsDefaultNetMeteredContext * context)147 bool ConnectionExec::ExecIsDefaultNetMetered(IsDefaultNetMeteredContext *context)
148 {
149     auto ret = NetConnClient::GetInstance().IsDefaultNetMetered(context->isMetered_);
150     if (ret != NETMANAGER_SUCCESS) {
151         NETMANAGER_BASE_LOGE("get net metered status failed %{public}d", ret);
152         context->SetErrorCode(ret);
153     }
154     return ret == NETMANAGER_SUCCESS;
155 }
156 
IsDefaultNetMeteredCallback(IsDefaultNetMeteredContext * context)157 napi_value ConnectionExec::IsDefaultNetMeteredCallback(IsDefaultNetMeteredContext *context)
158 {
159     return NapiUtils::GetBoolean(context->GetEnv(), context->isMetered_);
160 }
161 
ExecGetNetCapabilities(GetNetCapabilitiesContext * context)162 bool ConnectionExec::ExecGetNetCapabilities(GetNetCapabilitiesContext *context)
163 {
164     if (!context->IsParseOK()) {
165         return false;
166     }
167     auto ret = NetConnClient::GetInstance().GetNetCapabilities(context->netHandle_, context->capabilities_);
168     context->SetErrorCode(ret);
169     return ret == NETMANAGER_SUCCESS;
170 }
171 
GetNetCapabilitiesCallback(GetNetCapabilitiesContext * context)172 napi_value ConnectionExec::GetNetCapabilitiesCallback(GetNetCapabilitiesContext *context)
173 {
174     return CreateNetCapabilities(context->GetEnv(), &context->capabilities_);
175 }
176 
ExecGetConnectionProperties(GetConnectionPropertiesContext * context)177 bool ConnectionExec::ExecGetConnectionProperties(GetConnectionPropertiesContext *context)
178 {
179     if (!context->IsParseOK()) {
180         return false;
181     }
182     auto ret = NetConnClient::GetInstance().GetConnectionProperties(context->netHandle_, context->linkInfo_);
183     context->SetErrorCode(ret);
184     return ret == NETMANAGER_SUCCESS;
185 }
186 
GetConnectionPropertiesCallback(GetConnectionPropertiesContext * context)187 napi_value ConnectionExec::GetConnectionPropertiesCallback(GetConnectionPropertiesContext *context)
188 {
189     return CreateConnectionProperties(context->GetEnv(), &context->linkInfo_);
190 }
191 
ExecGetAllNets(GetAllNetsContext * context)192 bool ConnectionExec::ExecGetAllNets(GetAllNetsContext *context)
193 {
194     int32_t ret = NetConnClient::GetInstance().GetAllNets(context->netHandleList_);
195     context->SetErrorCode(ret);
196     return ret == NETMANAGER_SUCCESS;
197 }
198 
GetAllNetsCallback(GetAllNetsContext * context)199 napi_value ConnectionExec::GetAllNetsCallback(GetAllNetsContext *context)
200 {
201     napi_value array = NapiUtils::CreateArray(context->GetEnv(), context->netHandleList_.size());
202     uint32_t index = 0;
203     std::for_each(context->netHandleList_.begin(), context->netHandleList_.end(),
204                   [array, &index, context](const sptr<NetHandle> &handle) {
205                       NapiUtils::SetArrayElement(context->GetEnv(), array, index,
206                                                  CreateNetHandle(context->GetEnv(), handle.GetRefPtr()));
207                       ++index;
208                   });
209     return array;
210 }
211 
ExecEnableAirplaneMode(EnableAirplaneModeContext * context)212 bool ConnectionExec::ExecEnableAirplaneMode(EnableAirplaneModeContext *context)
213 {
214     int32_t res = NetConnClient::GetInstance().SetAirplaneMode(true);
215     if (res != NETMANAGER_SUCCESS) {
216         NETMANAGER_BASE_LOGE("ExecEnableAirplaneMode failed %{public}d", res);
217         context->SetErrorCode(res);
218     }
219     return res == NETMANAGER_SUCCESS;
220 }
221 
EnableAirplaneModeCallback(EnableAirplaneModeContext * context)222 napi_value ConnectionExec::EnableAirplaneModeCallback(EnableAirplaneModeContext *context)
223 {
224     return NapiUtils::GetUndefined(context->GetEnv());
225 }
226 
ExecDisableAirplaneMode(DisableAirplaneModeContext * context)227 bool ConnectionExec::ExecDisableAirplaneMode(DisableAirplaneModeContext *context)
228 {
229     int32_t res = NetConnClient::GetInstance().SetAirplaneMode(false);
230     if (res != NETMANAGER_SUCCESS) {
231         NETMANAGER_BASE_LOGE("ExecDisableAirplaneMode failed %{public}d", res);
232         context->SetErrorCode(res);
233     }
234     return res == NETMANAGER_SUCCESS;
235 }
236 
DisableAirplaneModeCallback(DisableAirplaneModeContext * context)237 napi_value ConnectionExec::DisableAirplaneModeCallback(DisableAirplaneModeContext *context)
238 {
239     return NapiUtils::GetUndefined(context->GetEnv());
240 }
241 
ExecReportNetConnected(ReportNetConnectedContext * context)242 bool ConnectionExec::ExecReportNetConnected(ReportNetConnectedContext *context)
243 {
244     if (!context->IsParseOK()) {
245         return false;
246     }
247     int32_t res = NetConnClient::GetInstance().NetDetection(context->netHandle_);
248     if (res != NETMANAGER_SUCCESS) {
249         NETMANAGER_BASE_LOGE("ExecReportNetConnected failed %{public}d", res);
250         context->SetErrorCode(res);
251     }
252     return res == NETMANAGER_SUCCESS;
253 }
254 
ReportNetConnectedCallback(ReportNetConnectedContext * context)255 napi_value ConnectionExec::ReportNetConnectedCallback(ReportNetConnectedContext *context)
256 {
257     return NapiUtils::GetUndefined(context->GetEnv());
258 }
259 
ExecReportNetDisconnected(ReportNetConnectedContext * context)260 bool ConnectionExec::ExecReportNetDisconnected(ReportNetConnectedContext *context)
261 {
262     if (!context->IsParseOK()) {
263         return false;
264     }
265     int32_t res = NetConnClient::GetInstance().NetDetection(context->netHandle_);
266     if (res != NETMANAGER_SUCCESS) {
267         NETMANAGER_BASE_LOGE("ExecReportNetDisconnected failed %{public}d", res);
268         context->SetErrorCode(res);
269     }
270     return res == NETMANAGER_SUCCESS;
271 }
272 
ReportNetDisconnectedCallback(ReportNetConnectedContext * context)273 napi_value ConnectionExec::ReportNetDisconnectedCallback(ReportNetConnectedContext *context)
274 {
275     return NapiUtils::GetUndefined(context->GetEnv());
276 }
277 
ExecGetDefaultHttpProxy(GetHttpProxyContext * context)278 bool ConnectionExec::ExecGetDefaultHttpProxy(GetHttpProxyContext *context)
279 {
280     int32_t errorCode = NetConnClient::GetInstance().GetDefaultHttpProxy(context->httpProxy_);
281     if (errorCode != NET_CONN_SUCCESS) {
282         context->SetErrorCode(errorCode);
283         return false;
284     }
285     return true;
286 }
287 
GetDefaultHttpProxyCallback(GetHttpProxyContext * context)288 napi_value ConnectionExec::GetDefaultHttpProxyCallback(GetHttpProxyContext *context)
289 {
290     napi_value host = NapiUtils::CreateStringUtf8(context->GetEnv(), context->httpProxy_.GetHost());
291     napi_value port = NapiUtils::CreateInt32(context->GetEnv(), context->httpProxy_.GetPort());
292     auto lists = context->httpProxy_.GetExclusionList();
293     napi_value exclusionList = NapiUtils::CreateArray(context->GetEnv(), lists.size());
294     size_t index = 0;
295     for (auto list : lists) {
296         napi_value jsList = NapiUtils::CreateStringUtf8(context->GetEnv(), list);
297         NapiUtils::SetArrayElement(context->GetEnv(), exclusionList, index++, jsList);
298     }
299     napi_value httpProxy = NapiUtils::CreateObject(context->GetEnv());
300     NapiUtils::SetNamedProperty(context->GetEnv(), httpProxy, "host", host);
301     NapiUtils::SetNamedProperty(context->GetEnv(), httpProxy, "port", port);
302     NapiUtils::SetNamedProperty(context->GetEnv(), httpProxy, "exclusionList", exclusionList);
303     return httpProxy;
304 }
305 
ExecGetGlobalHttpProxy(GetHttpProxyContext * context)306 bool ConnectionExec::ExecGetGlobalHttpProxy(GetHttpProxyContext *context)
307 {
308     int32_t errorCode = NetConnClient::GetInstance().GetGlobalHttpProxy(context->httpProxy_);
309     if (errorCode != NET_CONN_SUCCESS) {
310         context->SetErrorCode(errorCode);
311         return false;
312     }
313     return true;
314 }
315 
GetGlobalHttpProxyCallback(GetHttpProxyContext * context)316 napi_value ConnectionExec::GetGlobalHttpProxyCallback(GetHttpProxyContext *context)
317 {
318     napi_value host = NapiUtils::CreateStringUtf8(context->GetEnv(), context->httpProxy_.GetHost());
319     napi_value port = NapiUtils::CreateInt32(context->GetEnv(), context->httpProxy_.GetPort());
320     auto lists = context->httpProxy_.GetExclusionList();
321     napi_value exclusionList = NapiUtils::CreateArray(context->GetEnv(), lists.size());
322     size_t index = 0;
323     for (auto list : lists) {
324         napi_value jsList = NapiUtils::CreateStringUtf8(context->GetEnv(), list);
325         NapiUtils::SetArrayElement(context->GetEnv(), exclusionList, index++, jsList);
326     }
327     napi_value httpProxy = NapiUtils::CreateObject(context->GetEnv());
328     NapiUtils::SetNamedProperty(context->GetEnv(), httpProxy, "host", host);
329     NapiUtils::SetNamedProperty(context->GetEnv(), httpProxy, "port", port);
330     NapiUtils::SetNamedProperty(context->GetEnv(), httpProxy, "exclusionList", exclusionList);
331     return httpProxy;
332 }
333 
ExecSetGlobalHttpProxy(SetGlobalHttpProxyContext * context)334 bool ConnectionExec::ExecSetGlobalHttpProxy(SetGlobalHttpProxyContext *context)
335 {
336     int32_t errorCode = NetConnClient::GetInstance().SetGlobalHttpProxy(context->httpProxy_);
337     if (errorCode != NET_CONN_SUCCESS) {
338         context->SetErrorCode(errorCode);
339         return false;
340     }
341     return true;
342 }
343 
SetGlobalHttpProxyCallback(SetGlobalHttpProxyContext * context)344 napi_value ConnectionExec::SetGlobalHttpProxyCallback(SetGlobalHttpProxyContext *context)
345 {
346     return NapiUtils::GetUndefined(context->GetEnv());
347 }
348 
ExecSetAppHttpProxy(SetAppHttpProxyContext * context)349 bool ConnectionExec::ExecSetAppHttpProxy(SetAppHttpProxyContext *context)
350 {
351     int32_t errorCode = NetConnClient::GetInstance().SetAppHttpProxy(context->httpProxy_);
352     if (errorCode != NET_CONN_SUCCESS) {
353         context->SetErrorCode(errorCode);
354         return false;
355     }
356     return true;
357 }
358 
SetAppHttpProxyCallback(SetAppHttpProxyContext * context)359 napi_value ConnectionExec::SetAppHttpProxyCallback(SetAppHttpProxyContext *context)
360 {
361     return NapiUtils::GetUndefined(context->GetEnv());
362 }
363 
ExecGetAppNet(GetAppNetContext * context)364 bool ConnectionExec::ExecGetAppNet(GetAppNetContext *context)
365 {
366     int32_t netId = 0;
367     int32_t errorCode = NetConnClient::GetInstance().GetAppNet(netId);
368     if (errorCode != NET_CONN_SUCCESS) {
369         NETMANAGER_BASE_LOGE("exec getAppNet failed errorCode: %{public}d", errorCode);
370         context->SetErrorCode(errorCode);
371         return false;
372     }
373     context->netHandle_.SetNetId(netId);
374     return true;
375 }
376 
GetAppNetCallback(GetAppNetContext * context)377 napi_value ConnectionExec::GetAppNetCallback(GetAppNetContext *context)
378 {
379     return CreateNetHandle(context->GetEnv(), &context->netHandle_);
380 }
381 
ExecSetAppNet(SetAppNetContext * context)382 bool ConnectionExec::ExecSetAppNet(SetAppNetContext *context)
383 {
384     NETMANAGER_BASE_LOGI("into");
385     int32_t errorCode = NetConnClient::GetInstance().SetAppNet(context->netHandle_.GetNetId());
386     if (errorCode != NET_CONN_SUCCESS) {
387         NETMANAGER_BASE_LOGE("exec setAppNet failed errorCode: %{public}d", errorCode);
388         context->SetErrorCode(errorCode);
389         return false;
390     }
391     return true;
392 }
393 
SetAppNetCallback(SetAppNetContext * context)394 napi_value ConnectionExec::SetAppNetCallback(SetAppNetContext *context)
395 {
396     return NapiUtils::GetUndefined(context->GetEnv());
397 }
398 
ExecGetPacUrl(GetPacUrlContext * context)399 bool ConnectionExec::ExecGetPacUrl(GetPacUrlContext *context)
400 {
401     int32_t errorCode = NetConnClient::GetInstance().GetPacUrl(context->pacUrl_);
402     if (errorCode != NET_CONN_SUCCESS) {
403         NETMANAGER_BASE_LOGE("exec GetPacUrl failed errorCode: %{public}d", errorCode);
404         context->SetErrorCode(errorCode);
405         return false;
406     }
407     return true;
408 }
409 
GetPacUrlCallback(GetPacUrlContext * context)410 napi_value ConnectionExec::GetPacUrlCallback(GetPacUrlContext *context)
411 {
412     return NapiUtils::CreateStringUtf8(context->GetEnv(), context->pacUrl_);
413 }
414 
ExecSetPacUrl(SetPacUrlContext * context)415 bool ConnectionExec::ExecSetPacUrl(SetPacUrlContext *context)
416 {
417     if (context->pacUrl_.empty()) {
418         NETMANAGER_BASE_LOGE("pac Url is empty!");
419         context->SetErrorCode(NETMANAGER_ERR_PARAMETER_ERROR);
420         return false;
421     }
422     int32_t errorCode = NetConnClient::GetInstance().SetPacUrl(context->pacUrl_);
423     if (errorCode != NET_CONN_SUCCESS) {
424         NETMANAGER_BASE_LOGE("exec SetPacUrl failed errorCode: %{public}d", errorCode);
425         context->SetErrorCode(errorCode);
426         return false;
427     }
428     return true;
429 }
430 
SetPacUrlCallback(SetPacUrlContext * context)431 napi_value ConnectionExec::SetPacUrlCallback(SetPacUrlContext *context)
432 {
433     return NapiUtils::GetUndefined(context->GetEnv());
434 }
435 
ExecSetCustomDNSRule(SetCustomDNSRuleContext * context)436 bool ConnectionExec::ExecSetCustomDNSRule(SetCustomDNSRuleContext *context)
437 {
438     if (context == nullptr) {
439         NETMANAGER_BASE_LOGE("context is nullptr");
440         return false;
441     }
442 
443     if (!CommonUtils::HasInternetPermission()) {
444         context->SetErrorCode(NETMANAGER_ERR_PERMISSION_DENIED);
445         return false;
446     }
447 
448     if (context->host_.empty() || context->ip_.empty()) {
449         context->SetErrorCode(NETMANAGER_ERR_PARAMETER_ERROR);
450         return false;
451     }
452 
453     std::vector<std::string> ip = context->ip_;
454     for (size_t i = 0; i < ip.size(); i++) {
455         if (!CommonUtils::IsValidIPV4(ip[i]) && !CommonUtils::IsValidIPV6(ip[i])) {
456             context->SetErrorCode(NETMANAGER_ERR_PARAMETER_ERROR);
457             return false;
458         }
459     }
460 
461     if (!context->IsParseOK()) {
462         context->SetErrorCode(NETMANAGER_ERR_PARAMETER_ERROR);
463         return false;
464     }
465 
466     std::string host_ips = context->host_ + ",";
467     for (size_t i = 0; i < ip.size(); i++) {
468         host_ips.append(ip[i]);
469         if (i < ip.size() - 1) {
470             host_ips.append(",");
471         }
472     }
473 
474     NETMANAGER_BASE_LOGI("set host with ip addr");
475     int res = predefined_host_set_hosts(host_ips.c_str());
476     if (res != NETMANAGER_SUCCESS) {
477         NETMANAGER_BASE_LOGE("ExecSetCustomDNSRule failed %{public}d", res);
478         context->SetErrorCode(res);
479         return false;
480     }
481 
482     return true;
483 }
484 
SetCustomDNSRuleCallback(SetCustomDNSRuleContext * context)485 napi_value ConnectionExec::SetCustomDNSRuleCallback(SetCustomDNSRuleContext *context)
486 {
487     return NapiUtils::GetUndefined(context->GetEnv());
488 }
489 
ExecDeleteCustomDNSRule(DeleteCustomDNSRuleContext * context)490 bool ConnectionExec::ExecDeleteCustomDNSRule(DeleteCustomDNSRuleContext *context)
491 {
492     if (context == nullptr) {
493         NETMANAGER_BASE_LOGE("context is nullptr");
494         return false;
495     }
496     if (!CommonUtils::HasInternetPermission()) {
497         context->SetErrorCode(NETMANAGER_ERR_PERMISSION_DENIED);
498         return false;
499     }
500 
501     if (context->host_.empty()) {
502         context->SetErrorCode(NETMANAGER_ERR_PARAMETER_ERROR);
503         return false;
504     }
505 
506     if (!context->IsParseOK()) {
507         context->SetErrorCode(NETMANAGER_ERR_PARAMETER_ERROR);
508         return false;
509     }
510 
511     NETMANAGER_BASE_LOGI("delete host with ip addr");
512     int res = predefined_host_remove_host(context->host_.c_str());
513     if (res != NETMANAGER_SUCCESS) {
514         NETMANAGER_BASE_LOGE("ExecDeleteCustomDNSRule failed %{public}d", res);
515         context->SetErrorCode(res);
516         return false;
517     }
518     return true;
519 }
520 
DeleteCustomDNSRuleCallback(DeleteCustomDNSRuleContext * context)521 napi_value ConnectionExec::DeleteCustomDNSRuleCallback(DeleteCustomDNSRuleContext *context)
522 {
523     return NapiUtils::GetUndefined(context->GetEnv());
524 }
525 
ExecDeleteCustomDNSRules(DeleteCustomDNSRulesContext * context)526 bool ConnectionExec::ExecDeleteCustomDNSRules(DeleteCustomDNSRulesContext *context)
527 {
528     if (context == nullptr) {
529         NETMANAGER_BASE_LOGE("context is nullptr");
530         return false;
531     }
532     if (!CommonUtils::HasInternetPermission()) {
533         context->SetErrorCode(NETMANAGER_ERR_PERMISSION_DENIED);
534         return false;
535     }
536 
537     if (!context->IsParseOK()) {
538         context->SetErrorCode(NETMANAGER_ERR_PARAMETER_ERROR);
539         return false;
540     }
541 
542     int res = predefined_host_clear_all_hosts();
543     if (res != NETMANAGER_SUCCESS) {
544         NETMANAGER_BASE_LOGE("ExecDeleteCustomDNSRules failed %{public}d", res);
545         context->SetErrorCode(res);
546         return false;
547     }
548 
549     return true;
550 }
551 
DeleteCustomDNSRulesCallback(DeleteCustomDNSRulesContext * context)552 napi_value ConnectionExec::DeleteCustomDNSRulesCallback(DeleteCustomDNSRulesContext *context)
553 {
554     return NapiUtils::GetUndefined(context->GetEnv());
555 }
556 
ExecFactoryResetNetwork(FactoryResetNetworkContext * context)557 bool ConnectionExec::ExecFactoryResetNetwork(FactoryResetNetworkContext *context)
558 {
559     NETMANAGER_BASE_LOGI("ExecFactoryResetNetwork into");
560     int32_t errorCode = NetConnClient::GetInstance().FactoryResetNetwork();
561     if (errorCode != NET_CONN_SUCCESS) {
562         NETMANAGER_BASE_LOGE("exec ResetNetwork failed errorCode: %{public}d", errorCode);
563         context->SetErrorCode(errorCode);
564         return false;
565     }
566     return true;
567 }
568 
FactoryResetNetworkCallback(FactoryResetNetworkContext * context)569 napi_value ConnectionExec::FactoryResetNetworkCallback(FactoryResetNetworkContext *context)
570 {
571     return NapiUtils::GetUndefined(context->GetEnv());
572 }
573 
TransErrorCode(int32_t error)574 int32_t TransErrorCode(int32_t error)
575 {
576     switch (error) {
577         case NO_PERMISSION_CODE:
578             return NETMANAGER_ERR_PERMISSION_DENIED;
579         case PERMISSION_DENIED_CODE:
580             return NETMANAGER_ERR_PERMISSION_DENIED;
581         case NET_UNREACHABLE_CODE:
582             return NETMANAGER_ERR_INTERNAL;
583         default:
584             return NETMANAGER_ERR_OPERATION_FAILED;
585     }
586 }
587 
ExecGetAddressesByName(GetAddressByNameContext * context)588 bool ConnectionExec::NetHandleExec::ExecGetAddressesByName(GetAddressByNameContext *context)
589 {
590     if (!context->IsParseOK()) {
591         return false;
592     }
593     uint32_t netid = static_cast<uint32_t>(context->netId_);
594     addrinfo *res = nullptr;
595     queryparam param;
596     param.qp_type = QEURY_TYPE_NORMAL;
597     param.qp_netid = netid;
598     NETMANAGER_BASE_LOGD("getaddrinfo_ext %{public}d %{public}d", netid, param.qp_netid);
599     if (context->host_.empty()) {
600         NETMANAGER_BASE_LOGE("host is empty!");
601         context->SetErrorCode(NETMANAGER_ERR_INVALID_PARAMETER);
602         return false;
603     }
604 
605     int status = getaddrinfo_ext(context->host_.c_str(), nullptr, nullptr, &res, &param);
606     if (status < 0) {
607         NETMANAGER_BASE_LOGE("getaddrinfo errno %{public}d %{public}s,  status: %{public}d", errno, strerror(errno),
608                              status);
609         int32_t temp = TransErrorCode(errno);
610         context->SetErrorCode(temp);
611         return false;
612     }
613 
614     for (addrinfo *tmp = res; tmp != nullptr; tmp = tmp->ai_next) {
615         std::string host;
616         if (tmp->ai_family == AF_INET) {
617             auto addr = reinterpret_cast<sockaddr_in *>(tmp->ai_addr);
618             char ip[MAX_IPV4_STR_LEN] = {0};
619             inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));
620             host = ip;
621         } else if (tmp->ai_family == AF_INET6) {
622             auto addr = reinterpret_cast<sockaddr_in6 *>(tmp->ai_addr);
623             char ip[MAX_IPV6_STR_LEN] = {0};
624             inet_ntop(AF_INET6, &addr->sin6_addr, ip, sizeof(ip));
625             host = ip;
626         }
627 
628         NetAddress address;
629         SetAddressInfo(host.c_str(), tmp, address);
630 
631         context->addresses_.emplace_back(address);
632     }
633     freeaddrinfo(res);
634     return true;
635 }
636 
GetAddressesByNameCallback(GetAddressByNameContext * context)637 napi_value ConnectionExec::NetHandleExec::GetAddressesByNameCallback(GetAddressByNameContext *context)
638 {
639     napi_value addresses = NapiUtils::CreateArray(context->GetEnv(), context->addresses_.size());
640     for (uint32_t index = 0; index < context->addresses_.size(); ++index) {
641         napi_value obj = MakeNetAddressJsValue(context->GetEnv(), context->addresses_[index]);
642         NapiUtils::SetArrayElement(context->GetEnv(), addresses, index, obj);
643     }
644     return addresses;
645 }
646 
ExecGetAddressByName(GetAddressByNameContext * context)647 bool ConnectionExec::NetHandleExec::ExecGetAddressByName(GetAddressByNameContext *context)
648 {
649     if (!context->IsParseOK()) {
650         return false;
651     }
652     uint32_t netid = static_cast<uint32_t>(context->netId_);
653     addrinfo *res = nullptr;
654     queryparam param;
655     param.qp_type = QEURY_TYPE_NORMAL;
656     param.qp_netid = netid;
657     NETMANAGER_BASE_LOGD("getaddrinfo_ext %{public}d %{public}d", netid, param.qp_netid);
658     if (context->host_.empty()) {
659         NETMANAGER_BASE_LOGE("host is empty!");
660         context->SetErrorCode(NETMANAGER_ERR_INVALID_PARAMETER);
661         return false;
662     }
663 
664     int status = getaddrinfo_ext(context->host_.c_str(), nullptr, nullptr, &res, &param);
665     if (status < 0) {
666         NETMANAGER_BASE_LOGE("getaddrinfo errno %{public}d %{public}s,  status: %{public}d", errno, strerror(errno),
667                              status);
668         int32_t temp = TransErrorCode(errno);
669         context->SetErrorCode(temp);
670         return false;
671     }
672 
673     if (res != nullptr) {
674         std::string host;
675         if (res->ai_family == AF_INET) {
676             auto addr = reinterpret_cast<sockaddr_in *>(res->ai_addr);
677             char ip[MAX_IPV4_STR_LEN] = {0};
678             inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));
679             host = ip;
680         } else if (res->ai_family == AF_INET6) {
681             auto addr = reinterpret_cast<sockaddr_in6 *>(res->ai_addr);
682             char ip[MAX_IPV6_STR_LEN] = {0};
683             inet_ntop(AF_INET6, &addr->sin6_addr, ip, sizeof(ip));
684             host = ip;
685         }
686 
687         NetAddress address;
688         SetAddressInfo(host.c_str(), res, address);
689 
690         context->addresses_.emplace_back(address);
691     }
692     freeaddrinfo(res);
693     return true;
694 }
695 
GetAddressByNameCallback(GetAddressByNameContext * context)696 napi_value ConnectionExec::NetHandleExec::GetAddressByNameCallback(GetAddressByNameContext *context)
697 {
698     if (context->addresses_.empty()) {
699         return NapiUtils::GetUndefined(context->GetEnv());
700     }
701     return MakeNetAddressJsValue(context->GetEnv(), context->addresses_[0]);
702 }
703 
MakeNetAddressJsValue(napi_env env,const NetAddress & address)704 napi_value ConnectionExec::NetHandleExec::MakeNetAddressJsValue(napi_env env, const NetAddress &address)
705 {
706     napi_value obj = NapiUtils::CreateObject(env);
707     if (NapiUtils::GetValueType(env, obj) != napi_object) {
708         return NapiUtils::GetUndefined(env);
709     }
710 
711     NapiUtils::SetStringPropertyUtf8(env, obj, KEY_ADDRESS, address.GetAddress());
712     NapiUtils::SetUint32Property(env, obj, KEY_FAMILY, address.GetJsValueFamily());
713     NapiUtils::SetUint32Property(env, obj, KEY_PORT, address.GetPort());
714     return obj;
715 }
716 
ExecBindSocket(BindSocketContext * context)717 bool ConnectionExec::NetHandleExec::ExecBindSocket(BindSocketContext *context)
718 {
719     if (!context->IsParseOK()) {
720         return false;
721     }
722     NetHandle handle(context->netId_);
723     int32_t res = handle.BindSocket(context->socketFd_);
724     if (res != NETMANAGER_SUCCESS) {
725         NETMANAGER_BASE_LOGE("ExecBindSocket failed %{public}d", res);
726         context->SetErrorCode(res);
727     }
728     return res == NETMANAGER_SUCCESS;
729 }
730 
BindSocketCallback(BindSocketContext * context)731 napi_value ConnectionExec::NetHandleExec::BindSocketCallback(BindSocketContext *context)
732 {
733     return NapiUtils::GetUndefined(context->GetEnv());
734 }
735 
SetAddressInfo(const char * host,addrinfo * info,NetAddress & address)736 void ConnectionExec::NetHandleExec::SetAddressInfo(const char *host, addrinfo *info, NetAddress &address)
737 {
738     address.SetAddress(host);
739     address.SetFamilyBySaFamily(info->ai_addr->sa_family);
740     if (info->ai_addr->sa_family == AF_INET) {
741         auto addr4 = reinterpret_cast<sockaddr_in *>(info->ai_addr);
742         address.SetPort(addr4->sin_port);
743     } else if (info->ai_addr->sa_family == AF_INET6) {
744         auto addr6 = reinterpret_cast<sockaddr_in6 *>(info->ai_addr);
745         address.SetPort(addr6->sin6_port);
746     }
747 }
748 
ExecRegister(RegisterContext * context)749 bool ConnectionExec::NetConnectionExec::ExecRegister(RegisterContext *context)
750 {
751     auto wCallback = context->GetNetConnCallback();
752     sptr<INetConnCallback> callback = wCallback.promote();
753     if (callback == nullptr) {
754         NETMANAGER_BASE_LOGE("ExecRegister getNetConnCallback nullptr");
755         return false;
756     }
757 
758     auto conn = context->GetConn();
759     if (conn.hasNetSpecifier_ && conn.hasTimeout_) {
760         sptr<NetSpecifier> specifier = new NetSpecifier(conn.netSpecifier_);
761         int32_t ret = NetConnClient::GetInstance().RegisterNetConnCallback(specifier, callback, conn.timeout_);
762         NETMANAGER_BASE_LOGI("Register result hasNetSpecifier_ and hasTimeout_ %{public}d", ret);
763         context->SetErrorCode(ret);
764         return ret == NETMANAGER_SUCCESS;
765     }
766 
767     if (conn.hasNetSpecifier_) {
768         sptr<NetSpecifier> specifier = new NetSpecifier(conn.netSpecifier_);
769         int32_t ret = NetConnClient::GetInstance().RegisterNetConnCallback(specifier, callback, 0);
770         NETMANAGER_BASE_LOGI("Register result hasNetSpecifier_ %{public}d", ret);
771         context->SetErrorCode(ret);
772         return ret == NETMANAGER_SUCCESS;
773     }
774 
775     int32_t ret = NetConnClient::GetInstance().RegisterNetConnCallback(callback);
776     NETMANAGER_BASE_LOGI("Register result %{public}d", ret);
777     context->SetErrorCode(ret);
778     return ret == NETMANAGER_SUCCESS;
779 }
780 
RegisterCallback(RegisterContext * context)781 napi_value ConnectionExec::NetConnectionExec::RegisterCallback(RegisterContext *context)
782 {
783     return NapiUtils::GetUndefined(context->GetEnv());
784 }
785 
ExecUnregister(UnregisterContext * context)786 bool ConnectionExec::NetConnectionExec::ExecUnregister(UnregisterContext *context)
787 {
788     auto wCallback = context->GetNetConnCallback();
789     auto callback = wCallback.promote();
790     if (callback == nullptr) {
791         NETMANAGER_BASE_LOGE("ExecUnregister getNetConnCallback nullptr");
792         return false;
793     }
794 
795     int32_t ret = NetConnClient::GetInstance().UnregisterNetConnCallback(callback);
796     if (ret != NETMANAGER_SUCCESS) {
797         NETMANAGER_BASE_LOGE("Unregister result %{public}d", ret);
798         context->SetErrorCode(ret);
799     }
800     return ret == NETMANAGER_SUCCESS;
801 }
802 
UnregisterCallback(RegisterContext * context)803 napi_value ConnectionExec::NetConnectionExec::UnregisterCallback(RegisterContext *context)
804 {
805     return NapiUtils::GetUndefined(context->GetEnv());
806 }
807 
FillLinkAddress(napi_env env,napi_value connectionProperties,NetLinkInfo * linkInfo)808 void ConnectionExec::FillLinkAddress(napi_env env, napi_value connectionProperties, NetLinkInfo *linkInfo)
809 {
810     if (!linkInfo->netAddrList_.empty() && linkInfo->netAddrList_.size() <= MAX_ARRAY_LENGTH) {
811         napi_value linkAddresses =
812             NapiUtils::CreateArray(env, std::min(linkInfo->netAddrList_.size(), MAX_ARRAY_LENGTH));
813         auto it = linkInfo->netAddrList_.begin();
814         for (uint32_t index = 0; index < MAX_ARRAY_LENGTH && it != linkInfo->netAddrList_.end(); ++index, ++it) {
815             napi_value netAddr = NapiUtils::CreateObject(env);
816             NapiUtils::SetStringPropertyUtf8(env, netAddr, KEY_ADDRESS, it->address_);
817             NapiUtils::SetUint32Property(env, netAddr, KEY_FAMILY, it->family_);
818             NapiUtils::SetUint32Property(env, netAddr, KEY_PORT, it->port_);
819 
820             napi_value linkAddr = NapiUtils::CreateObject(env);
821             NapiUtils::SetNamedProperty(env, linkAddr, KEY_ADDRESS, netAddr);
822             NapiUtils::SetUint32Property(env, linkAddr, KEY_PREFIX_LENGTH, it->prefixlen_);
823             NapiUtils::SetArrayElement(env, linkAddresses, index, linkAddr);
824         }
825         NapiUtils::SetNamedProperty(env, connectionProperties, KEY_LINK_ADDRESSES, linkAddresses);
826     }
827 }
828 
FillRouoteList(napi_env env,napi_value connectionProperties,NetLinkInfo * linkInfo)829 void ConnectionExec::FillRouoteList(napi_env env, napi_value connectionProperties, NetLinkInfo *linkInfo)
830 {
831     if (!linkInfo->routeList_.empty() && linkInfo->routeList_.size() <= MAX_ARRAY_LENGTH) {
832         napi_value routes = NapiUtils::CreateArray(env, std::min(linkInfo->routeList_.size(), MAX_ARRAY_LENGTH));
833         auto it = linkInfo->routeList_.begin();
834         for (uint32_t index = 0; index < MAX_ARRAY_LENGTH && it != linkInfo->routeList_.end(); ++index, ++it) {
835             napi_value route = NapiUtils::CreateObject(env);
836             NapiUtils::SetStringPropertyUtf8(env, route, KEY_INTERFACE, it->iface_);
837 
838             napi_value dest = NapiUtils::CreateObject(env);
839             napi_value netAddr = NapiUtils::CreateObject(env);
840             NapiUtils::SetStringPropertyUtf8(env, netAddr, KEY_ADDRESS, it->destination_.address_);
841             NapiUtils::SetUint32Property(env, netAddr, KEY_FAMILY, it->destination_.family_);
842             NapiUtils::SetUint32Property(env, netAddr, KEY_PORT, it->destination_.port_);
843             NapiUtils::SetNamedProperty(env, dest, KEY_ADDRESS, netAddr);
844             NapiUtils::SetUint32Property(env, dest, KEY_PREFIX_LENGTH, it->destination_.prefixlen_);
845             NapiUtils::SetNamedProperty(env, route, KEY_DESTINATION, dest);
846 
847             napi_value gateway = NapiUtils::CreateObject(env);
848             NapiUtils::SetStringPropertyUtf8(env, gateway, KEY_ADDRESS, it->gateway_.address_);
849             NapiUtils::SetUint32Property(env, gateway, KEY_PREFIX_LENGTH, it->gateway_.prefixlen_);
850             NapiUtils::SetNamedProperty(env, route, KEY_GATE_WAY, gateway);
851 
852             NapiUtils::SetBooleanProperty(env, route, KEY_HAS_GET_WAY, it->hasGateway_);
853             NapiUtils::SetBooleanProperty(env, route, KEY_IS_DEFAULT_ROUE, it->isDefaultRoute_);
854 
855             NapiUtils::SetArrayElement(env, routes, index, route);
856         }
857         NapiUtils::SetNamedProperty(env, connectionProperties, KEY_ROUTES, routes);
858     }
859 }
860 
FillDns(napi_env env,napi_value connectionProperties,NetLinkInfo * linkInfo)861 void ConnectionExec::FillDns(napi_env env, napi_value connectionProperties, NetLinkInfo *linkInfo)
862 {
863     if (!linkInfo->dnsList_.empty() && linkInfo->dnsList_.size() <= MAX_ARRAY_LENGTH) {
864         napi_value dnsList = NapiUtils::CreateArray(env, std::min(linkInfo->dnsList_.size(), MAX_ARRAY_LENGTH));
865         auto it = linkInfo->dnsList_.begin();
866         for (uint32_t index = 0; index < MAX_ARRAY_LENGTH && it != linkInfo->dnsList_.end(); ++index, ++it) {
867             napi_value netAddr = NapiUtils::CreateObject(env);
868             NapiUtils::SetStringPropertyUtf8(env, netAddr, KEY_ADDRESS, it->address_);
869             NapiUtils::SetUint32Property(env, netAddr, KEY_FAMILY, it->family_);
870             NapiUtils::SetUint32Property(env, netAddr, KEY_PORT, it->port_);
871             NapiUtils::SetArrayElement(env, dnsList, index, netAddr);
872         }
873         NapiUtils::SetNamedProperty(env, connectionProperties, KEY_DNSES, dnsList);
874     }
875 }
876 } // namespace OHOS::NetManagerStandard
877