diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000..4947287 --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.en.md b/README.en.md old mode 100644 new mode 100755 index 0471c0c..efe9ea6 --- a/README.en.md +++ b/README.en.md @@ -1,4 +1,4 @@ -# communication_netmanager_standard +# communication_netmanager_base #### Description {**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 1165ef4..6a43c1c --- a/README.md +++ b/README.md @@ -1,39 +1,95 @@ -# communication_netmanager_standard +# Net Manager -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} - -#### 软件架构 -软件架构说明 +- [简介](#section112mcpsimp) +- [目录](#section125mcpsimp) +- [约束](#section133mcpsimp) +- [相关仓](#section155mcpsimp) -#### 安装教程 -1. xxxx -2. xxxx -3. xxxx +## 简介 -#### 使用说明 +网络管理介绍: -1. xxxx -2. xxxx -3. xxxx +​ 网络管理模块作为电话子系统可裁剪部件,依赖于蜂窝数据管理,主要分为连接管理、策略管理、流量管理、网络共享、VPN管理五大模块;如图1:网络管理架构图; -#### 参与贡献 +**图 1** 网络管理架构图 -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request +![](figures/net_manager_arch_zh.png) +连接管理介绍: -#### 特技 +​ 负责与蜂窝数据交互,请求到IP后,再与Netd交互并将路由参数设置到内核,使得蜂窝数据连接且可用,最终实现上网,如图2:网络连接架构图; + +**图 2** 网络连接架构图 + +![](figures/net_conn_manager_arch_zh.png) + +**图 3** 网络策略架构图 + +![](figures\net_policy_manager_arch_zh.png) + +## 目录 + +``` +/foundation/communication/netmanager_standard/netmanager_standard/ +├── frameworks # 框架代码 +│   ├── innerkitsimpl # 内部接口实现 +│   │   └── netconnmanager +│   │   │ └── src +│   │   └── netpolicymanager +│   │   └── src +│   └── js # JS接口实现 +│   └── napi +│   ├── http +│   ├── socket +│   └── websocket +├── interfaces # 接口代码 +│   ├── innerkits # 内部接口 +│   │   └── native +│   │   └── netconnmanager +│   │   │ └── include +│   │   └── netpolicymanager +│   │   └── include +│   └── kits # 外部接口 +│   └── js +├── sa_profile # 服务配置文件 +├── services # 核心服务代码目录 +│   ├── common # 网络管理公共组件 +│   ├── etc # 网络管理进程配置脚本 +│   │   └── init +│   ├── netconnmanager # 网络连接管理代码 +│   │   ├── include # 头文件 +│   │   │   ├── ipc # IPC通信头文件 +│   │   │   ├── net_controller # 网络控制 +│   │   ├── src # 源文件目录 +│   │   │   ├── ipc # IPC通信源文件 +│   │   │   ├── net_controller # 网络控制实现 +│   │   └── test # 单元测试代码 +│   ├── netpolicymanager # 网络策略管理代码 +│   │   ├── include # 头文件 +│   │   │   └── ipc # IPC通信头文件 +│   │   ├── src # 源文件目录 +│   │   │   └── ipc # IPC通信源文件 +│   │   └── test # 单元测试代码 +│   ├── netmanagernative # Netd代码 +│   └── prebuild # 预编译库文件 +└── utils # 公共功能实现 +| └── log # 日志实现 +└── ohos.build # 编译文件 +``` + +## 约束 + +- 开发语言:C++ +- 软件层,需要以下子系统和服务配合使用:蜂窝数据、安全子系统、软总线子系统、USB子系统、电源管理子系统等; +- 硬件层,需要搭载的设备支持以下硬件:可以进行独立蜂窝通信的Modem以及SIM卡; + +## 相关仓 + +[netmanager_standard](https://gitee.com/openharmony/communication_netmanager_standard/blob/master/README.md) + +[电话服务子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E7%94%B5%E8%AF%9D%E6%9C%8D%E5%8A%A1%E5%AD%90%E7%B3%BB%E7%BB%9F.md) + +[ telephony_cellular_data](https://gitee.com/openharmony/telephony_cellular_data/blob/master/README.md) -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/figures/net_conn_manager_arch_zh.png b/figures/net_conn_manager_arch_zh.png new file mode 100755 index 0000000..bef52c5 Binary files /dev/null and b/figures/net_conn_manager_arch_zh.png differ diff --git a/figures/net_manager_arch_zh.png b/figures/net_manager_arch_zh.png new file mode 100755 index 0000000..5c247ab Binary files /dev/null and b/figures/net_manager_arch_zh.png differ diff --git a/figures/net_policy_manager_arch_zh.png b/figures/net_policy_manager_arch_zh.png new file mode 100755 index 0000000..bc88209 Binary files /dev/null and b/figures/net_policy_manager_arch_zh.png differ diff --git a/figures/net_stats_manager_arch_zh.png b/figures/net_stats_manager_arch_zh.png new file mode 100755 index 0000000..b1ed2be Binary files /dev/null and b/figures/net_stats_manager_arch_zh.png differ diff --git a/frameworks/innerkitsimpl/dnsresolvermanager/src/dns_addr_info.cpp b/frameworks/innerkitsimpl/dnsresolvermanager/src/dns_addr_info.cpp new file mode 100755 index 0000000..70fadb2 --- /dev/null +++ b/frameworks/innerkitsimpl/dnsresolvermanager/src/dns_addr_info.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dns_addr_info.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool DnsAddrInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(flags_)) { + return false; + } + if (!parcel.WriteInt32(family_)) { + return false; + } + if (!parcel.WriteInt32(sockType_)) { + return false; + } + if (!parcel.WriteInt32(protocol_)) { + return false; + } + if (!parcel.WriteString(addr_)) { + return false; + } + return true; +} + +sptr DnsAddrInfo::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + NETMGR_LOGE("create DnsAddrInfo failed"); + return nullptr; + } + if (!parcel.ReadInt32(ptr->flags_)) { + return nullptr; + } + if (!parcel.ReadInt32(ptr->family_)) { + return nullptr; + } + if (!parcel.ReadInt32(ptr->sockType_)) { + return nullptr; + } + if (!parcel.ReadInt32(ptr->protocol_)) { + return nullptr; + } + if (!parcel.ReadString(ptr->addr_)) { + return nullptr; + } + return ptr; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/dnsresolvermanager/src/dns_resolver_client.cpp b/frameworks/innerkitsimpl/dnsresolvermanager/src/dns_resolver_client.cpp new file mode 100755 index 0000000..ab9edfd --- /dev/null +++ b/frameworks/innerkitsimpl/dnsresolvermanager/src/dns_resolver_client.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dns_resolver_client.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +DnsResolverClient::DnsResolverClient() : dnsResolverService_(nullptr), deathRecipient_(nullptr) {} + +DnsResolverClient::~DnsResolverClient() {} + +int32_t DnsResolverClient::GetAddressesByName(const std::string &hostName, std::vector &addrInfo) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->GetAddressesByName(hostName, addrInfo); +} + +int32_t DnsResolverClient::GetAddrInfo(const std::string &hostName, const std::string &server, + const sptr &hints, std::vector> &dnsAddrInfo) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->GetAddrInfo(hostName, server, hints, dnsAddrInfo); +} + +int32_t DnsResolverClient::CreateNetworkCache(uint16_t netId) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->CreateNetworkCache(netId); +} + +int32_t DnsResolverClient::DestoryNetworkCache(uint16_t netId) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->DestoryNetworkCache(netId); +} + +int32_t DnsResolverClient::FlushNetworkCache(uint16_t netId) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->FlushNetworkCache(netId); +} + +int32_t DnsResolverClient::SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->SetResolverConfig(netId, baseTimeoutMsec, retryCount, servers, domains); +} + +int32_t DnsResolverClient::GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->GetResolverInfo(netId, servers, domains, baseTimeoutMsec, retryCount); +} + +sptr DnsResolverClient::GetProxy() +{ + std::lock_guard lock(mutex_); + if (dnsResolverService_) { + NETMGR_LOGI("get proxy is ok"); + return dnsResolverService_; + } + NETMGR_LOGI("execute GetSystemAbilityManager"); + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + NETMGR_LOGE("GetProxy, get SystemAbilityManager failed"); + return nullptr; + } + sptr remote = sam->CheckSystemAbility(COMM_DNS_MANAGER_SYS_ABILITY_ID); + if (remote == nullptr) { + NETMGR_LOGE("get Remote service failed"); + return nullptr; + } + deathRecipient_ = (std::make_unique(*this)).release(); + if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) { + NETMGR_LOGE("add death recipient failed"); + return nullptr; + } + dnsResolverService_ = iface_cast(remote); + if (dnsResolverService_ == nullptr) { + NETMGR_LOGE("get Remote service proxy failed"); + return nullptr; + } + return dnsResolverService_; +} + +void DnsResolverClient::OnRemoteDied(const wptr &remote) +{ + NETMGR_LOGI("on remote died"); + if (remote == nullptr) { + NETMGR_LOGE("remote object is nullptr"); + return; + } + std::lock_guard lock(mutex_); + if (dnsResolverService_ == nullptr) { + NETMGR_LOGE("dnsResolverService_ is nullptr"); + return; + } + sptr local = dnsResolverService_->AsObject(); + if (local != remote.promote()) { + NETMGR_LOGE("proxy and stub is not same remote object"); + return; + } + local->RemoveDeathRecipient(deathRecipient_); + dnsResolverService_ = nullptr; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/ethernetmanager/src/ethernet_client.cpp b/frameworks/innerkitsimpl/ethernetmanager/src/ethernet_client.cpp new file mode 100755 index 0000000..0395477 --- /dev/null +++ b/frameworks/innerkitsimpl/ethernetmanager/src/ethernet_client.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ethernet_client.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +EthernetClient::EthernetClient() : ethernetService_(nullptr), deathRecipient_(nullptr) {} + +EthernetClient::~EthernetClient() {} + +int32_t EthernetClient::SetIfaceConfig(const std::string &iface, sptr &ic) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->SetIfaceConfig(iface, ic); +} + +sptr EthernetClient::GetIfaceConfig(const std::string &iface) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return nullptr; + } + return proxy->GetIfaceConfig(iface); +} +int32_t EthernetClient::IsActivate(const std::string &iface) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->IsActivate(iface); +} + +std::vector EthernetClient::GetActivateInterfaces() +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return {}; + } + return proxy->GetActivateInterfaces(); +} + +sptr EthernetClient::GetProxy() +{ + std::lock_guard lock(mutex_); + if (ethernetService_) { + NETMGR_LOGI("get proxy is ok"); + return ethernetService_; + } + NETMGR_LOGI("execute GetSystemAbilityManager"); + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + NETMGR_LOGE("GetProxy, get SystemAbilityManager failed"); + return nullptr; + } + sptr remote = sam->CheckSystemAbility(COMM_ETHERNET_MANAGER_SYS_ABILITY_ID); + if (remote == nullptr) { + NETMGR_LOGE("get Remote service failed"); + return nullptr; + } + deathRecipient_ = (std::make_unique(*this)).release(); + if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) { + NETMGR_LOGE("add death recipient failed"); + return nullptr; + } + ethernetService_ = iface_cast(remote); + if (ethernetService_ == nullptr) { + NETMGR_LOGE("get Remote service proxy failed"); + return nullptr; + } + return ethernetService_; +} + +void EthernetClient::OnRemoteDied(const wptr &remote) +{ + NETMGR_LOGI("on remote died"); + if (remote == nullptr) { + NETMGR_LOGE("remote object is nullptr"); + return; + } + std::lock_guard lock(mutex_); + if (ethernetService_ == nullptr) { + NETMGR_LOGE("ethernetService_ is nullptr"); + return; + } + sptr local = ethernetService_->AsObject(); + if (local != remote.promote()) { + NETMGR_LOGE("proxy and stub is not same remote object"); + return; + } + local->RemoveDeathRecipient(deathRecipient_); + ethernetService_ = nullptr; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/ethernetmanager/src/interface_configuration.cpp b/frameworks/innerkitsimpl/ethernetmanager/src/interface_configuration.cpp new file mode 100755 index 0000000..b744bc9 --- /dev/null +++ b/frameworks/innerkitsimpl/ethernetmanager/src/interface_configuration.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "interface_configuration.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool InterfaceConfiguration::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(static_cast(mode_))) { + return false; + } + if (!ipStatic_.Marshalling(parcel)) { + NETMGR_LOGE("write ipStatic_ to parcel failed"); + return false; + } + return true; +} + +sptr InterfaceConfiguration::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + return nullptr; + } + int32_t mode = 0; + if (!parcel.ReadInt32(mode)) { + return nullptr; + } + ptr->mode_ = static_cast(mode); + sptr sc = StaticConfiguration::Unmarshalling(parcel); + if (sc == nullptr) { + NETMGR_LOGE("sc is null"); + return nullptr; + } + ptr->ipStatic_ = *sc; + return ptr; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/ethernetmanager/src/static_configuration.cpp b/frameworks/innerkitsimpl/ethernetmanager/src/static_configuration.cpp new file mode 100755 index 0000000..cce72d0 --- /dev/null +++ b/frameworks/innerkitsimpl/ethernetmanager/src/static_configuration.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "static_configuration.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool StaticConfiguration::Marshalling(Parcel &parcel) const +{ + if (!ipAddr_.Marshalling(parcel)) { + NETMGR_LOGE("write ipAddr_ to parcel failed"); + return false; + } + if (!route_.Marshalling(parcel)) { + NETMGR_LOGE("write route_ to parcel failed"); + return false; + } + if (!gate_.Marshalling(parcel)) { + NETMGR_LOGE("write gate_ to parcel failed"); + return false; + } + if (!netMask_.Marshalling(parcel)) { + NETMGR_LOGE("write netMask_ to parcel failed"); + return false; + } + if (!parcel.WriteUint32(dnsServers_.size())) { + NETMGR_LOGE("write dnsServers_ size to parcel failed"); + return false; + } + for (auto it = dnsServers_.begin(); it != dnsServers_.end(); ++it) { + if (!it->Marshalling(parcel)) { + NETMGR_LOGE("write dnsServers_ to parcel failed"); + return false; + } + } + if (!parcel.WriteString(domain_)) { + NETMGR_LOGE("write domain_ to parcel failed"); + return false; + } + return true; +} + +sptr StaticConfiguration::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + return nullptr; + } + sptr ipAddr = INetAddr::Unmarshalling(parcel); + if (ipAddr == nullptr) { + NETMGR_LOGE("ipAddr_ is null"); + return nullptr; + } + ptr->ipAddr_ = *ipAddr; + sptr route = INetAddr::Unmarshalling(parcel); + if (route == nullptr) { + NETMGR_LOGE("route_ is null"); + return nullptr; + } + ptr->route_ = *route; + sptr gate = INetAddr::Unmarshalling(parcel); + if (gate == nullptr) { + NETMGR_LOGE("gate_ is null"); + return nullptr; + } + ptr->gate_ = *gate; + sptr netMask = INetAddr::Unmarshalling(parcel); + if (netMask == nullptr) { + NETMGR_LOGE("netMask_ is null"); + return nullptr; + } + ptr->netMask_ = *netMask; + uint32_t size = 0; + if (!parcel.ReadUint32(size)) { + return nullptr; + } + for (uint32_t i = 0; i < size; i++) { + sptr netAddr = INetAddr::Unmarshalling(parcel); + if (netAddr == nullptr) { + NETMGR_LOGE("netAddr is null"); + return nullptr; + } + ptr->dnsServers_.push_back(*netAddr); + } + if (!parcel.ReadString(ptr->domain_)) { + return nullptr; + } + return ptr; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/netconnmanager/src/inet_addr.cpp b/frameworks/innerkitsimpl/netconnmanager/src/inet_addr.cpp new file mode 100755 index 0000000..ea08d61 --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/inet_addr.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "inet_addr.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool INetAddr::operator==(const INetAddr &obj) const +{ + bool out = true; + out = out && (type_ == obj.type_); + out = out && (family_ == obj.family_); + out = out && (prefixlen_ == obj.prefixlen_); + out = out && (address_ == obj.address_); + out = out && (netMask_ == obj.netMask_); + out = out && (hostName_ == obj.hostName_); + return out; +} + +bool INetAddr::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteUint8(type_)) { + return false; + } + if (!parcel.WriteUint8(family_)) { + return false; + } + if (!parcel.WriteUint8(prefixlen_)) { + return false; + } + if (!parcel.WriteString(address_)) { + return false; + } + if (!parcel.WriteString(netMask_)) { + return false; + } + if (!parcel.WriteString(hostName_)) { + return false; + } + return true; +} + +sptr INetAddr::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + NETMGR_LOGE("create INetAddr failed"); + return nullptr; + } + if (!parcel.ReadUint8(ptr->type_)) { + return nullptr; + } + if (!parcel.ReadUint8(ptr->family_)) { + return nullptr; + } + if (!parcel.ReadUint8(ptr->prefixlen_)) { + return nullptr; + } + if (!parcel.ReadString(ptr->address_)) { + return nullptr; + } + if (!parcel.ReadString(ptr->netMask_)) { + return nullptr; + } + if (!parcel.ReadString(ptr->hostName_)) { + return nullptr; + } + return ptr; +} + +bool INetAddr::Marshalling(Parcel &parcel, const sptr &object) +{ + if (object == nullptr) { + NETMGR_LOGE("INetAddr object ptr is nullptr"); + return false; + } + if (!parcel.WriteUint8(object->type_)) { + return false; + } + if (!parcel.WriteUint8(object->family_)) { + return false; + } + if (!parcel.WriteUint8(object->prefixlen_)) { + return false; + } + if (!parcel.WriteString(object->address_)) { + return false; + } + if (!parcel.WriteString(object->netMask_)) { + return false; + } + if (!parcel.WriteString(object->hostName_)) { + return false; + } + return true; +} + +std::string INetAddr::ToString(const std::string tab) const +{ + std::string familyStr = std::to_string(family_); + std::string prefixlenStr = std::to_string(prefixlen_); + std::string jsonStr = "{"; + jsonStr += "\"family_\""; + jsonStr += ":"; + jsonStr += "\"" + familyStr + "\","; + + jsonStr += "\"prefixlen_\""; + jsonStr += ":"; + jsonStr += "\"" + prefixlenStr + "\","; + + jsonStr += "\"address_\""; + jsonStr += ":"; + jsonStr += "\"" + address_ + "\","; + + jsonStr += "\"netMask_\""; + jsonStr += ":"; + jsonStr += "\"" + netMask_ + "\""; + jsonStr += "}"; + return jsonStr; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/innerkitsimpl/netconnmanager/src/ipc/net_conn_callback_stub.cpp b/frameworks/innerkitsimpl/netconnmanager/src/ipc/net_conn_callback_stub.cpp new file mode 100755 index 0000000..644ee7c --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/ipc/net_conn_callback_stub.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_conn_callback_stub.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetConnCallbackStub::NetConnCallbackStub() +{ + memberFuncMap_[NET_CONN_STATE_CHANGED] = &NetConnCallbackStub::OnNetConnStateChanged; +} + +NetConnCallbackStub::~NetConnCallbackStub() {} + +int32_t NetConnCallbackStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + NETMGR_LOGI("Stub call start, code:[%{public}d]", code); + std::u16string myDescripter = NetConnCallbackStub::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (myDescripter != remoteDescripter) { + NETMGR_LOGE("Descriptor checked failed"); + return ERR_FLATTEN_OBJECT; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + + NETMGR_LOGI("Stub default case, need check"); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t NetConnCallbackStub::OnNetConnStateChanged(MessageParcel &data, MessageParcel &reply) +{ + if (!data.ContainFileDescriptors()) { + NETMGR_LOGE("Execute ContainFileDescriptors failed"); + } + + sptr info = NetConnCallbackInfo::Unmarshalling(data); + int32_t result = NetConnStateChanged(info); + if (!reply.WriteInt32(result)) { + NETMGR_LOGE("Write parcel failed"); + return result; + } + + return ERR_NONE; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/innerkitsimpl/netconnmanager/src/net_conn_callback_info.cpp b/frameworks/innerkitsimpl/netconnmanager/src/net_conn_callback_info.cpp new file mode 100755 index 0000000..d50771a --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/net_conn_callback_info.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_conn_callback_info.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool NetConnCallbackInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(netState_)) { + return false; + } + if (!parcel.WriteUint32(netType_)) { + return false; + } + + return true; +} + +sptr NetConnCallbackInfo::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + NETMGR_LOGE("The parameter of ptr is nullptr"); + return nullptr; + } + + if (!parcel.ReadInt32(ptr->netState_)) { + return nullptr; + } + if (!parcel.ReadUint32(ptr->netType_)) { + return nullptr; + } + + return ptr; +} + +bool NetConnCallbackInfo::Marshalling(Parcel &parcel, const sptr &object) +{ + if (object == nullptr) { + NETMGR_LOGE("NetConnCallbackInfo object is nullptr"); + return false; + } + + if (!parcel.WriteInt32(object->netState_)) { + NETMGR_LOGE("Write netState_ failed"); + return false; + } + if (!parcel.WriteUint32(object->netType_)) { + NETMGR_LOGE("Write netType_ failed"); + return false; + } + + return true; +} + +std::string NetConnCallbackInfo::ToString(const std::string &tab) const +{ + std::string str; + str.append("\n"); + str.append(tab); + str.append("[NetConnCallbackInfo]"); + + str.append("\n"); + str.append(tab); + str.append("netState_ = "); + str.append(std::to_string(netState_)); + + str.append("\n"); + str.append(tab); + str.append("netType_ = "); + str.append(std::to_string(netType_)); + + return str; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/netconnmanager/src/net_conn_client.cpp b/frameworks/innerkitsimpl/netconnmanager/src/net_conn_client.cpp new file mode 100755 index 0000000..5d7f67e --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/net_conn_client.cpp @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_conn_client.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetConnClient::NetConnClient() : NetConnService_(nullptr), deathRecipient_(nullptr) {} + +NetConnClient::~NetConnClient() {} + +int32_t NetConnClient::SystemReady() +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->SystemReady(); +} + +int32_t NetConnClient::RegisterNetSupplier(uint32_t netType, const std::string &ident, uint64_t netCapabilities) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->RegisterNetSupplier(netType, ident, netCapabilities); +} + +int32_t NetConnClient::UnregisterNetSupplier(uint32_t supplierId) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->UnregisterNetSupplier(supplierId); +} + +int32_t NetConnClient::RegisterNetConnCallback(const sptr &callback) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("The parameter of proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->RegisterNetConnCallback(callback); +} + +int32_t NetConnClient::RegisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("The parameter of proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->RegisterNetConnCallback(netSpecifier, callback); +} + +int32_t NetConnClient::UnregisterNetConnCallback(const sptr &callback) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->UnregisterNetConnCallback(callback); +} + +int32_t NetConnClient::UnregisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->UnregisterNetConnCallback(netSpecifier, callback); +} + +int32_t NetConnClient::UpdateNetSupplierInfo(uint32_t supplierId, const sptr &netSupplierInfo) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->UpdateNetSupplierInfo(supplierId, netSupplierInfo); +} + +int32_t NetConnClient::UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->UpdateNetCapabilities(supplierId, netCapabilities); +} + +int32_t NetConnClient::UpdateNetLinkInfo(uint32_t supplierId, const sptr &netLinkInfo) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return IPC_PROXY_ERR; + } + return proxy->UpdateNetLinkInfo(supplierId, netLinkInfo); +} + +sptr NetConnClient::GetProxy() +{ + std::lock_guard lock(mutex_); + if (NetConnService_) { + NETMGR_LOGI("get proxy is ok"); + return NetConnService_; + } + NETMGR_LOGI("execute GetSystemAbilityManager"); + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + NETMGR_LOGE("GetProxy, get SystemAbilityManager failed"); + return nullptr; + } + sptr remote = sam->CheckSystemAbility(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID); + if (remote == nullptr) { + NETMGR_LOGE("get Remote service failed"); + return nullptr; + } + deathRecipient_ = (std::make_unique(*this)).release(); + if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) { + NETMGR_LOGE("add death recipient failed"); + return nullptr; + } + NetConnService_ = iface_cast(remote); + if (NetConnService_ == nullptr) { + NETMGR_LOGE("get Remote service proxy failed"); + return nullptr; + } + return NetConnService_; +} + +void NetConnClient::OnRemoteDied(const wptr &remote) +{ + NETMGR_LOGI("on remote died"); + if (remote == nullptr) { + NETMGR_LOGE("remote object is nullptr"); + return; + } + std::lock_guard lock(mutex_); + if (NetConnService_ == nullptr) { + NETMGR_LOGE("OnRemoteDied NetConnService_ is nullptr"); + return; + } + sptr local = NetConnService_->AsObject(); + if (local != remote.promote()) { + NETMGR_LOGE("OnRemoteDied proxy and stub is not same remote object"); + return; + } + local->RemoveDeathRecipient(deathRecipient_); + NetConnService_ = nullptr; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/innerkitsimpl/netconnmanager/src/net_link_info.cpp b/frameworks/innerkitsimpl/netconnmanager/src/net_link_info.cpp new file mode 100755 index 0000000..c3f874a --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/net_link_info.cpp @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_link_info.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool NetLinkInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(ifaceName_)) { + return false; + } + if (!parcel.WriteString(domain_)) { + return false; + } + if (!parcel.WriteUint32(netAddrList_.size())) { + return false; + } + for (auto it = netAddrList_.begin(); it != netAddrList_.end(); it++) { + if (!it->Marshalling(parcel)) { + NETMGR_LOGE("write net address to parcel failed"); + return false; + } + } + if (!parcel.WriteUint32(dnsList_.size())) { + return false; + } + for (auto it = dnsList_.begin(); it != dnsList_.end(); it++) { + if (!it->Marshalling(parcel)) { + NETMGR_LOGE("write dns to parcel failed"); + return false; + } + } + if (!parcel.WriteUint32(routeList_.size())) { + return false; + } + for (auto it = routeList_.begin(); it != routeList_.end(); it++) { + if (!it->Marshalling(parcel)) { + NETMGR_LOGE("write route to parcel failed"); + return false; + } + } + if (!parcel.WriteUint16(mtu_)) { + return false; + } + return true; +} + +sptr NetLinkInfo::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + return nullptr; + } + if (!parcel.ReadString(ptr->ifaceName_)) { + return nullptr; + } + if (!parcel.ReadString(ptr->domain_)) { + return nullptr; + } + uint32_t size = 0; + if (!parcel.ReadUint32(size)) { + return nullptr; + } + sptr netAddr; + for (uint32_t i = 0; i < size; i++) { + netAddr = INetAddr::Unmarshalling(parcel); + if (netAddr == nullptr) { + NETMGR_LOGE("INetAddr::Unmarshalling(parcel) is null"); + return nullptr; + } + ptr->netAddrList_.push_back(*netAddr); + } + if (!parcel.ReadUint32(size)) { + return nullptr; + } + for (uint32_t i = 0; i < size; i++) { + netAddr = INetAddr::Unmarshalling(parcel); + if (netAddr == nullptr) { + NETMGR_LOGE("INetAddr::Unmarshalling(parcel) is null"); + return nullptr; + } + ptr->dnsList_.push_back(*netAddr); + } + if (!parcel.ReadUint32(size)) { + return nullptr; + } + sptr route; + for (uint32_t i = 0; i < size; i++) { + route = Route::Unmarshalling(parcel); + if (route == nullptr) { + NETMGR_LOGE("Route::Unmarshalling(parcel) is null"); + return nullptr; + } + ptr->routeList_.push_back(*route); + } + if (!parcel.ReadUint16(ptr->mtu_)) { + return nullptr; + } + return ptr; +} + +bool NetLinkInfo::Marshalling(Parcel &parcel, const sptr &object) +{ + if (object == nullptr) { + NETMGR_LOGE("NetLinkInfo object ptr is nullptr"); + return false; + } + if (!parcel.WriteString(object->ifaceName_)) { + return false; + } + if (!parcel.WriteString(object->domain_)) { + return false; + } + if (!parcel.WriteUint32(object->netAddrList_.size())) { + return false; + } + for (auto it = object->netAddrList_.begin(); it != object->netAddrList_.end(); it++) { + if (!it->Marshalling(parcel)) { + NETMGR_LOGE("write objects net address to parcel failed"); + return false; + } + } + if (!parcel.WriteUint32(object->dnsList_.size())) { + return false; + } + for (auto it = object->dnsList_.begin(); it != object->dnsList_.end(); it++) { + if (!it->Marshalling(parcel)) { + NETMGR_LOGE("write objects dns to parcel failed"); + return false; + } + } + if (!parcel.WriteUint32(object->routeList_.size())) { + return false; + } + for (auto it = object->routeList_.begin(); it != object->routeList_.end(); it++) { + if (!it->Marshalling(parcel)) { + NETMGR_LOGE("write objects route to parcel failed"); + return false; + } + } + if (!parcel.WriteUint16(object->mtu_)) { + return false; + } + return true; +} + +std::string NetLinkInfo::ToString(const std::string &tab) const +{ + std::string str; + str.append("\n"); + str.append(tab); + str.append("[NetLinkInfo]"); + + str.append("\n"); + str.append(tab); + str.append("ifaceName_ = "); + str.append(ifaceName_); + + str.append("\n"); + str.append(tab); + str.append("domain_ = "); + str.append(domain_); + + str.append("\n"); + str.append(tab); + str.append("netAddrList_ = "); + for (auto it = netAddrList_.begin(); it != netAddrList_.end(); it++) { + str.append(it->ToString(tab + " ")); + } + + str.append("\n"); + str.append(tab); + str.append("dnsList_ = "); + for (auto it = dnsList_.begin(); it != dnsList_.end(); it++) { + str.append(it->ToString(tab + " ")); + } + + str.append("\n"); + str.append(tab); + str.append("routeList_ = "); + for (auto it = routeList_.begin(); it != routeList_.end(); it++) { + str.append(it->ToString(tab + " ")); + } + + str.append("\n"); + str.append(tab); + str.append("mtu_ = "); + str.append(std::to_string(mtu_)); + return str; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/innerkitsimpl/netconnmanager/src/net_specifier.cpp b/frameworks/innerkitsimpl/netconnmanager/src/net_specifier.cpp new file mode 100755 index 0000000..ae3f326 --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/net_specifier.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_specifier.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool NetSpecifier::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(ident_)) { + return false; + } + if (!parcel.WriteUint32(netType_)) { + return false; + } + if (!parcel.WriteUint64(netCapabilities_)) { + return false; + } + return true; +} + +sptr NetSpecifier::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + NETMGR_LOGE("make_unique() failed"); + return nullptr; + } + if (!parcel.ReadString(ptr->ident_)) { + return nullptr; + } + if (!parcel.ReadUint32(ptr->netType_)) { + return nullptr; + } + if (!parcel.ReadUint64(ptr->netCapabilities_)) { + return nullptr; + } + return ptr; +} + +bool NetSpecifier::Marshalling(Parcel &parcel, const sptr &object) +{ + if (object == nullptr) { + NETMGR_LOGE("NetSpecifier object ptr is nullptr"); + return false; + } + if (!parcel.WriteString(object->ident_)) { + return false; + } + if (!parcel.WriteUint32(object->netType_)) { + return false; + } + if (!parcel.WriteUint64(object->netCapabilities_)) { + return false; + } + return true; +} + +std::string NetSpecifier::ToString(const std::string &tab) const +{ + std::string str; + str.append("\n"); + str.append(tab); + str.append("[NetSpecifier]"); + + str.append("\n"); + str.append(tab); + str.append("ident_ = "); + str.append(ident_); + + str.append("\n"); + str.append(tab); + str.append("netType_ = "); + str.append(std::to_string(netType_)); + + str.append("\n"); + str.append(tab); + str.append("netCapabilities_ = "); + str.append(std::to_string(netCapabilities_)); + + return str; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/netconnmanager/src/net_supplier_info.cpp b/frameworks/innerkitsimpl/netconnmanager/src/net_supplier_info.cpp new file mode 100755 index 0000000..0bfa3f1 --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/net_supplier_info.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_supplier_info.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool NetSupplierInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteBool(isAvailable_)) { + return false; + } + if (!parcel.WriteBool(isRoaming_)) { + return false; + } + if (!parcel.WriteUint8(strength_)) { + return false; + } + if (!parcel.WriteUint32(frequency_)) { + return false; + } + return true; +} + +sptr NetSupplierInfo::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + NETMGR_LOGE("make_unique() failed"); + return nullptr; + } + if (!parcel.ReadBool(ptr->isAvailable_)) { + return nullptr; + } + if (!parcel.ReadBool(ptr->isRoaming_)) { + return nullptr; + } + if (!parcel.ReadUint8(ptr->strength_)) { + NETMGR_LOGE("read strength_ from parcel failed"); + return nullptr; + } + if (!parcel.ReadUint32(ptr->frequency_)) { + return nullptr; + } + return ptr; +} + +bool NetSupplierInfo::Marshalling(Parcel &parcel, const sptr &object) +{ + if (object == nullptr) { + NETMGR_LOGE("NetSupplierInfo object ptr is nullptr"); + return false; + } + if (!parcel.WriteBool(object->isAvailable_)) { + return false; + } + if (!parcel.WriteBool(object->isRoaming_)) { + return false; + } + if (!parcel.WriteUint8(object->strength_)) { + return false; + } + if (!parcel.WriteUint32(object->frequency_)) { + return false; + } + return true; +} + +std::string NetSupplierInfo::ToString(const std::string &tab) const +{ + std::string str; + str.append("\n"); + str.append(tab); + str.append("[NetSupplierInfo]"); + + str.append("\n"); + str.append(tab); + str.append("isAvailable_ = "); + str.append(std::to_string(isAvailable_)); + + str.append("\n"); + str.append(tab); + str.append("isRoaming_ = "); + str.append(std::to_string(isRoaming_)); + + str.append("\n"); + str.append(tab); + str.append("strength_ = "); + str.append(std::to_string(strength_)); + + str.append("\n"); + str.append(tab); + str.append("frequency_ = "); + str.append(std::to_string(frequency_)); + + return str; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/netconnmanager/src/route.cpp b/frameworks/innerkitsimpl/netconnmanager/src/route.cpp new file mode 100755 index 0000000..9287b95 --- /dev/null +++ b/frameworks/innerkitsimpl/netconnmanager/src/route.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "route.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool Route::operator==(const Route &obj) const +{ + bool out = true; + out = out && (iface_ == obj.iface_); + out = out && (destination_ == obj.destination_); + out = out && (gateway_ == obj.gateway_); + return out; +} + +bool Route::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(iface_)) { + return false; + } + if (!destination_.Marshalling(parcel)) { + NETMGR_LOGE("write destination_ to parcel failed"); + return false; + } + if (!gateway_.Marshalling(parcel)) { + NETMGR_LOGE("write gateway_ to parcel failed"); + return false; + } + return true; +} + +sptr Route::Unmarshalling(Parcel &parcel) +{ + sptr ptr = (std::make_unique()).release(); + if (ptr == nullptr) { + NETMGR_LOGE("make_unique() failed"); + return nullptr; + } + if (!parcel.ReadString(ptr->iface_)) { + return nullptr; + } + sptr destination = INetAddr::Unmarshalling(parcel); + if (destination == nullptr) { + NETMGR_LOGE("read destination from parcel failed"); + return nullptr; + } + ptr->destination_ = *destination; + sptr gateway = INetAddr::Unmarshalling(parcel); + if (gateway == nullptr) { + NETMGR_LOGE("read gateway from parcel failed"); + return nullptr; + } + ptr->gateway_ = *gateway; + return ptr; +} + +bool Route::Marshalling(Parcel &parcel, const sptr &object) +{ + if (object == nullptr) { + NETMGR_LOGE("Route object ptr is nullptr"); + return false; + } + if (!parcel.WriteString(object->iface_)) { + return false; + } + if (!object->destination_.Marshalling(parcel)) { + NETMGR_LOGE("write object->destination_ to parcel failed"); + return false; + } + if (!object->gateway_.Marshalling(parcel)) { + NETMGR_LOGE("write object->gateway_ to parcel failed"); + return false; + } + return true; +} + +std::string Route::ToString(const std::string &tab) const +{ + std::string str; + str.append("\n"); + str.append(tab); + str.append("[Route]"); + + str.append("\n"); + str.append(tab); + str.append("iface_ = "); + str.append(iface_); + + str.append("\n"); + str.append(tab); + str.append("destination_ = "); + str.append(destination_.ToString(tab + " ")); + + str.append("\n"); + str.append(tab); + str.append("gateway_ = "); + str.append(gateway_.ToString(tab + " ")); + + return str; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/netpolicymanager/src/net_policy_client.cpp b/frameworks/innerkitsimpl/netpolicymanager/src/net_policy_client.cpp new file mode 100755 index 0000000..834e4ce --- /dev/null +++ b/frameworks/innerkitsimpl/netpolicymanager/src/net_policy_client.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_policy_client.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetPolicyClient::NetPolicyClient() : netPolicyService_(nullptr), deathRecipient_(nullptr) {} + +NetPolicyClient::~NetPolicyClient() {} + +NetPolicyResultCode NetPolicyClient::SetUidPolicy(uint32_t uid, NetUidPolicy policy) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + return proxy->SetUidPolicy(uid, policy); +} + +NetUidPolicy NetPolicyClient::GetUidPolicy(uint32_t uid) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return NetUidPolicy::NET_POLICY_NONE; + } + return proxy->GetUidPolicy(uid); +} + +std::vector NetPolicyClient::GetUids(NetUidPolicy policy) +{ + std::vector uids; + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return uids; + } + uids = proxy->GetUids(policy); + return uids; +} + +bool NetPolicyClient::IsUidNetAccess(uint32_t uid, bool metered) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return false; + } + return proxy->IsUidNetAccess(uid, metered); +} + +bool NetPolicyClient::IsUidNetAccess(uint32_t uid, const std::string &ifaceName) +{ + sptr proxy = GetProxy(); + if (proxy == nullptr) { + NETMGR_LOGE("proxy is nullptr"); + return false; + } + return proxy->IsUidNetAccess(uid, ifaceName); +} + +sptr NetPolicyClient::GetProxy() +{ + std::lock_guard lock(mutex_); + if (netPolicyService_ != nullptr) { + return netPolicyService_; + } + + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + NETMGR_LOGE("GetProxy, get SystemAbilityManager failed"); + return nullptr; + } + + sptr remote = sam->CheckSystemAbility(COMM_NET_POLICY_MANAGER_SYS_ABILITY_ID); + if (remote == nullptr) { + NETMGR_LOGE("get Remote service failed"); + return nullptr; + } + + deathRecipient_ = (std::make_unique(*this)).release(); + if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) { + NETMGR_LOGE("add death recipient failed"); + return nullptr; + } + + netPolicyService_ = iface_cast(remote); + if (netPolicyService_ == nullptr) { + NETMGR_LOGE("get Remote service proxy failed"); + return nullptr; + } + return netPolicyService_; +} + +void NetPolicyClient::OnRemoteDied(const wptr &remote) +{ + NETMGR_LOGI("on remote died"); + if (remote == nullptr) { + NETMGR_LOGE("remote object is nullptr"); + return; + } + + std::lock_guard lock(mutex_); + if (netPolicyService_ == nullptr) { + NETMGR_LOGE("netPolicyService_ is nullptr"); + return; + } + + sptr local = netPolicyService_->AsObject(); + if (local != remote.promote()) { + NETMGR_LOGE("proxy and stub is not same remote object"); + return; + } + local->RemoveDeathRecipient(deathRecipient_); + netPolicyService_ = nullptr; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/js/common/napi_common.cpp b/frameworks/js/common/napi_common.cpp new file mode 100755 index 0000000..b2aecb2 --- /dev/null +++ b/frameworks/js/common/napi_common.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_common.h" + +namespace OHOS { +namespace NetManagerStandard { +napi_value NpiCommon::CreateCodeMessage(napi_env env, const std::string &msg, int32_t code) +{ + napi_value messageCodeInfo = nullptr; + napi_value messageInfo = nullptr; + napi_value codeInfo = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, msg.c_str(), msg.length(), &messageInfo)); + NAPI_CALL(env, napi_create_string_utf8( + env, std::to_string(code).c_str(), std::to_string(code).length(), &codeInfo)); + NAPI_CALL(env, napi_create_error(env, codeInfo, messageInfo, &messageCodeInfo)); + return messageCodeInfo; +} + +void NpiCommon::SetPropertyInt32(napi_env env, napi_value object, const std::string &propertyName, int32_t property) +{ + napi_value propertyDest = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, property, &propertyDest)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, object, propertyName.c_str(), propertyDest)); +} + +void NpiCommon::SetPropertyString( + napi_env env, napi_value object, const std::string &propertyName, const std::string &property) +{ + napi_value propertyDest = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, property.c_str(), property.length(), &propertyDest)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, object, propertyName.c_str(), propertyDest)); +} + +void NpiCommon::GetPropertyString( + napi_env env, napi_value object, const std::string &propertyName, std::string &property) +{ + napi_value value = nullptr; + char propertyBuffer[PROPERTY_MAX_BYTE] = {0}; + size_t realByte= 0; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, object, propertyName.c_str(), &value)); + NAPI_CALL_RETURN_VOID(env, napi_get_value_string_utf8(env, value, propertyBuffer, PROPERTY_MAX_BYTE, &realByte)); + property = propertyBuffer; +} + +void NpiCommon::GetPropertyInt32(napi_env env, napi_value object, const std::string &propertyName, int32_t &property) +{ + napi_value value = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, object, propertyName.c_str(), &value)); + NAPI_CALL_RETURN_VOID(env, napi_get_value_int32(env, value, &property)); +} + +napi_value NpiCommon::NapiValueByInt32(napi_env env, int32_t property) +{ + napi_value value = nullptr; + NAPI_CALL(env, napi_create_int32(env, property, &value)); + return value; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/js/common/napi_common.h b/frameworks/js/common/napi_common.h new file mode 100755 index 0000000..bce9aea --- /dev/null +++ b/frameworks/js/common/napi_common.h @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_COMMON_H +#define NAPI_COMMON_H + +#include +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace NetManagerStandard { +// define callback ref count +constexpr uint32_t CALLBACK_REF_CNT = 1; +// define property max bytes +constexpr uint32_t PROPERTY_MAX_BYTE = 128; +// define constant of 64 bytes +constexpr uint32_t BUFFER_BYTE = 64; + +enum JS_CALLBACK_ARGV { + CALLBACK_ARGV_INDEX_0 = 0, + CALLBACK_ARGV_INDEX_1, + CALLBACK_ARGV_CNT, +}; + +enum JS_ARGV_NUM { + ARGV_NUM_0 = 0, + ARGV_NUM_1, + ARGV_NUM_2, + ARGV_NUM_3, + ARGV_NUM_4, + ARGV_NUM_5, +}; + +enum JS_ARGV_INDEX { + ARGV_INDEX_0 = 0, + ARGV_INDEX_1, + ARGV_INDEX_2, + ARGV_INDEX_3, + ARGV_INDEX_4, +}; + +class NpiCommon { +public: + static napi_value CreateCodeMessage(napi_env env, const std::string &msg, int32_t code); + static napi_value NapiValueByInt32(napi_env env, int32_t property); + static void SetPropertyInt32(napi_env env, napi_value object, const std::string &propertyName, int32_t property); + static void SetPropertyString(napi_env env, napi_value object, const std::string &propertyName, + const std::string &property); + static void GetPropertyString(napi_env env, napi_value object, const std::string &propertyName, + std::string &property); + static void GetPropertyInt32(napi_env env, napi_value object, const std::string &propertyName, int32_t &property); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NAPI_COMMON_H + diff --git a/frameworks/js/dnsresolver/BUILD.gn b/frameworks/js/dnsresolver/BUILD.gn new file mode 100755 index 0000000..5cd5ca5 --- /dev/null +++ b/frameworks/js/dnsresolver/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +SUBSYSTEM_DIR = "//foundation/communication" +NETMANAGER_NAPI_ROOT = "$SUBSYSTEM_DIR/netmanager_standard/frameworks/js/" + +ohos_shared_library("dnsresolver") { + include_dirs = [ + "//third_party/node/src", + "$NETMANAGER_NAPI_ROOT/dnsresolver/include", + "$NETMANAGER_NAPI_ROOT/common", + "$NETMANAGER_BASE_ROOT/utils/log/include", + "$DNSRESOLVERMANAGER_SOURCE_DIR/include", + "$DNSRESOLVERMANAGER_SOURCE_DIR/include/ipc", + "$INNERKITS_ROOT/native/netconnmanager/include", + ] + + sources = [ + "$NETMANAGER_NAPI_ROOT/common/napi_common.cpp", + "$NETMANAGER_NAPI_ROOT/dnsresolver/src/napi_dns_resolver.cpp", + ] + + defines = [ "NETMGR_DEBUG" ] + + deps = [ + "$INNERKITS_ROOT/native/dnsresolvermanager:dns_resolver_manager_if", + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/ace/napi/:ace_napi", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + relative_install_dir = "module" + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/frameworks/js/dnsresolver/include/napi_dns_resolver.h b/frameworks/js/dnsresolver/include/napi_dns_resolver.h new file mode 100755 index 0000000..0f3a2d4 --- /dev/null +++ b/frameworks/js/dnsresolver/include/napi_dns_resolver.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_DNS_RESOLVER_H +#define NAPI_DNS_RESOLVER_H + +#include +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int32_t HOST_MAX_BYTES = 256; + +// dns resolver async context +struct DnsResolverAsyncContext { + napi_async_work work = nullptr; + napi_deferred deferred = nullptr; + napi_ref callbackRef = nullptr; + // Data context + char host[HOST_MAX_BYTES] = {0}; + size_t hostRealBytes = 0; + std::vector hostAddress; +}; + +class NapiDnsResolver { +public: + NapiDnsResolver(); + ~NapiDnsResolver() = default; + static napi_value DeclareNapiDnsResolverInterface(napi_env env, napi_value exports); + static napi_value RegisterDnsResolverInterface(napi_env env, napi_value exports); + static void ExecDnsResolverCallback(napi_env env, void *data); + static void CompleteDnsResolverCallback(napi_env env, napi_status status, void *data); + // declare napi interface for JS + static napi_value GetAddressesByName(napi_env env, napi_callback_info info); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NAPI_DNS_RESOLVER_H diff --git a/frameworks/js/dnsresolver/src/napi_dns_resolver.cpp b/frameworks/js/dnsresolver/src/napi_dns_resolver.cpp new file mode 100755 index 0000000..8b4271d --- /dev/null +++ b/frameworks/js/dnsresolver/src/napi_dns_resolver.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_dns_resolver.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "net_mgr_log_wrapper.h" +#include "i_dns_resolver_service.h" +#include "dns_resolver_client.h" +#include "napi_common.h" + +namespace OHOS { +namespace NetManagerStandard { +NapiDnsResolver::NapiDnsResolver() {} + +void NapiDnsResolver::ExecDnsResolverCallback(napi_env env, void *data) +{ + DnsResolverAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + std::string hostName = context->host; + std::vector addrInfo; + NETMGR_LOGI("ExecDnsResolverCallback [%{public}s]", hostName.c_str()); + DelayedSingleton::GetInstance()->GetAddressesByName(hostName, addrInfo); + NETMGR_LOGI("ExecDnsResolverCallback, addrInfo.size = [%{public}d]", static_cast(addrInfo.size())); + std::string tap; + for (auto it = addrInfo.begin(); it != addrInfo.end(); ++it) { + context->hostAddress.push_back(it->ToString(tap)); + } +} + +void NapiDnsResolver::CompleteDnsResolverCallback(napi_env env, napi_status status, void *data) +{ + NETMGR_LOGI("CompleteDnsResolverCallback"); + DnsResolverAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + // creat function return + napi_value infoAttay = nullptr; + napi_value info = nullptr; + napi_create_string_utf8(env, "fail", NAPI_AUTO_LENGTH, &info); + napi_create_array_with_length(env, context->hostAddress.size(), &infoAttay); + for (size_t index = 0; index < context->hostAddress.size(); index++) { + napi_create_string_utf8(env, context->hostAddress[index].c_str(), NAPI_AUTO_LENGTH, &info); + napi_set_element(env, infoAttay, index, info); + } + if (context->callbackRef == nullptr) { + // promiss return + if (context->hostAddress.size() > 0) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, infoAttay)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + } + } else { + // call back return + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + if (context->hostAddress.size() > 0) { + callbackValues[CALLBACK_ARGV_INDEX_1] = infoAttay; + } else { + callbackValues[CALLBACK_ARGV_INDEX_0] = info; + } + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +napi_value NapiDnsResolver::GetAddressesByName(napi_env env, napi_callback_info info) +{ + NETMGR_LOGI("NapiDnsResolver GetAddressesByName"); + size_t argc = ARGV_NUM_2; + napi_value argv[] = {nullptr, nullptr} ; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + DnsResolverAsyncContext* context = std::make_unique().release(); + NAPI_CALL(env, napi_get_value_string_utf8( + env, argv[ARGV_INDEX_0], context->host, HOST_MAX_BYTES, &(context->hostRealBytes))); + NETMGR_LOGI("GetAddressesByName = [%{public}s]", context->host); + NETMGR_LOGI("GetAddressesByName argc = [%{public}d]", static_cast(argc)); + napi_value result = nullptr; + if (argc == ARGV_NUM_1) { + if (context->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_NUM_2) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("GetAddressesByName exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "GetAddressesByName", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecDnsResolverCallback, + CompleteDnsResolverCallback, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiDnsResolver::DeclareNapiDnsResolverInterface(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getAddressesByName", GetAddressesByName), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value NapiDnsResolver::RegisterDnsResolverInterface(napi_env env, napi_value exports) +{ + DeclareNapiDnsResolverInterface(env, exports); + return nullptr; +} + +static napi_module _dnsResolverModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = NapiDnsResolver::RegisterDnsResolverInterface, + .nm_modname = "netmanager.dnsresolver", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +extern "C" __attribute__((constructor)) void RegisterDnsResolverModule(void) +{ + napi_module_register(&_dnsResolverModule); +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/js/ethernet/BUILD.gn b/frameworks/js/ethernet/BUILD.gn new file mode 100755 index 0000000..e0f098b --- /dev/null +++ b/frameworks/js/ethernet/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +SUBSYSTEM_DIR = "//foundation/communication" +NETMANAGER_NAPI_ROOT = "$SUBSYSTEM_DIR/netmanager_standard/frameworks/js/" + +ohos_shared_library("ethernet") { + include_dirs = [ + "//third_party/node/src", + "$NETMANAGER_NAPI_ROOT/ethernet/include", + "$NETMANAGER_NAPI_ROOT/common", + "$NETMANAGER_BASE_ROOT/utils/log/include", + "$ETHERNETMANAGER_SOURCE_DIR/include", + "$ETHERNETMANAGER_SOURCE_DIR/include/ipc", + "$INNERKITS_ROOT/native/ethernetmanager/include", + "//foundation/communication/netmanager_standard/interfaces/innerkits/native/ethernetmanager/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + ] + + sources = [ + "$NETMANAGER_NAPI_ROOT/common/napi_common.cpp", + "$NETMANAGER_NAPI_ROOT/ethernet/src/napi_ethernet.cpp", + ] + + defines = [ "NETMGR_DEBUG" ] + + deps = [ + "$INNERKITS_ROOT/native/ethernetmanager:ethernet_manager_if", + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$NETMANAGER_PREBUILTS_DIR/librarys/netd:libnet_manager_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/ace/napi/:ace_napi", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + relative_install_dir = "module" + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/frameworks/js/ethernet/include/napi_ethernet.h b/frameworks/js/ethernet/include/napi_ethernet.h new file mode 100755 index 0000000..19f35c8 --- /dev/null +++ b/frameworks/js/ethernet/include/napi_ethernet.h @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_ETHERNET_H +#define NAPI_ETHERNET_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include +#include + +namespace OHOS { +namespace NetManagerStandard { +// ethernet name max bytes +constexpr int32_t ETHERNET_NAME_MAX_BYTE = 32; +// ip address max bytes +constexpr int32_t IP_ADDR_MAX_BYTE = 128; +// ip address type [static] +const std::string STATIC_IP = "static"; +// ip address type [dynamic] +const std::string DYNAMIC_IP = "dynamic"; + +struct EthernetAsyncContext { + napi_async_work work = nullptr; + napi_deferred deferred = nullptr; + napi_ref callbackRef = nullptr; + // Data context + char ethernetName[ETHERNET_NAME_MAX_BYTE] = {0}; + size_t ethernetNameRealBytes = 0; + int32_t ifActivate = 0; + // get all ethernetName + std::vector ethernetNameList; + // [0] static, [1] dhcp + int32_t ipMode = 0; + // ip address info + std::string ipAddrInfo; + // route address info + std::string routeAddrInfo; + // gate address info + std::string gateAddrInfo; + // mask address info + std::string maskAddrInfo; + // dns0 address info + std::string dns0AddrInfo; + // dns1 address info + std::string dns1AddrInfo; + int32_t result = 0; +}; + +class NapiEthernet { +public: + NapiEthernet(); + ~NapiEthernet() = default; + static napi_value RegisterEthernetInterface(napi_env env, napi_value exports); + static napi_value DeclareEthernetInterface(napi_env env, napi_value exports); + static napi_value DeclareEthernetData(napi_env env, napi_value exports); + + static void ExecSetIfaceConfig(napi_env env, void *data); + static void CompleteSetIfaceConfig(napi_env env, napi_status status, void *data); + static void ExecGetIfaceConfig(napi_env env, void *data); + static void CompleteGetIfaceConfig(napi_env env, napi_status status, void *data); + static void ExecIsActivate(napi_env env, void *data); + static void CompleteIsActivate(napi_env env, napi_status status, void *data); + static void ExecGetActivateInterfaces(napi_env env, void *data); + static void CompleteGetActivateInterfaces(napi_env env, napi_status status, void *data); + // define napi interface for JS + static napi_value SetIfaceConfig(napi_env env, napi_callback_info info); + static napi_value GetIfaceConfig(napi_env env, napi_callback_info info); + static napi_value IsActivate(napi_env env, napi_callback_info info); + static napi_value GetActivateInterfaces(napi_env env, napi_callback_info info); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NAPI_ETHERNET_H diff --git a/frameworks/js/ethernet/src/napi_ethernet.cpp b/frameworks/js/ethernet/src/napi_ethernet.cpp new file mode 100755 index 0000000..847ea02 --- /dev/null +++ b/frameworks/js/ethernet/src/napi_ethernet.cpp @@ -0,0 +1,470 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_ethernet.h" +#include +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "net_mgr_log_wrapper.h" +#include "i_ethernet_service.h" +#include "ethernet_client.h" +#include "napi_common.h" + +namespace OHOS { +namespace NetManagerStandard { +NapiEthernet::NapiEthernet() {} + +void NapiEthernet::ExecSetIfaceConfig(napi_env env, void *data) +{ + NETMGR_LOGI("ExecSetIfaceConfig"); + EthernetAsyncContext *context = (EthernetAsyncContext *)data; + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + INetAddr addr0, addr1; + sptr config = std::make_unique().release(); + if (config == nullptr) { + NETMGR_LOGE("config == nullptr"); + return; + } + addr0.address_ = context->dns0AddrInfo; + addr1.address_ = context->dns1AddrInfo; + config->mode_ = static_cast(context->ipMode); + config->ipStatic_.ipAddr_.address_ = context->ipAddrInfo; + config->ipStatic_.route_.address_ = context->routeAddrInfo; + config->ipStatic_.gate_.address_ = context->gateAddrInfo; + config->ipStatic_.netMask_.address_ = context->maskAddrInfo; + config->ipStatic_.dnsServers_.push_back(addr0); + config->ipStatic_.dnsServers_.push_back(addr1); + context->result = DelayedSingleton::GetInstance()->SetIfaceConfig( + context->ethernetName, config); + NETMGR_LOGI("ExecSetIfaceConfig result =[%{public}d]", context->result); +} + +void NapiEthernet::CompleteSetIfaceConfig(napi_env env, napi_status status, void *data) +{ + NETMGR_LOGI("CompleteSetIfaceConfig"); + EthernetAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + napi_value info = nullptr; + napi_create_int32(env, context->result, &info); + if (context->callbackRef == nullptr) { + // promiss return + if (context->result != ERR_NONE) { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } + } else { + // call back return + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + if (context->result != ERR_NONE) { + callbackValues[CALLBACK_ARGV_INDEX_0] = info; + } else { + callbackValues[CALLBACK_ARGV_INDEX_1] = info; + } + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +void NapiEthernet::ExecGetIfaceConfig(napi_env env, void *data) +{ + NETMGR_LOGI("ExecGetIfaceConfig"); + EthernetAsyncContext *context = (EthernetAsyncContext *)data; + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + sptr config = + DelayedSingleton::GetInstance()->GetIfaceConfig(context->ethernetName); + if (config != nullptr) { + context->ifActivate = 1; + std::string tap; + context->ipMode = config->mode_; + NETMGR_LOGI("config->mode_ = [%{public}d]", config->mode_); + context->ipAddrInfo = config->ipStatic_.ipAddr_.ToString(tap); + NETMGR_LOGI("config->ipAddr_ = [%{public}s]", config->ipStatic_.ipAddr_.ToString(tap).c_str()); + context->routeAddrInfo = config->ipStatic_.route_.ToString(tap); + NETMGR_LOGI("config->route_ = [%{public}s]", config->ipStatic_.route_.ToString(tap).c_str()); + context->gateAddrInfo = config->ipStatic_.gate_.ToString(tap); + NETMGR_LOGI("config->gate_ = [%{public}s]", config->ipStatic_.gate_.ToString(tap).c_str()); + context->maskAddrInfo = config->ipStatic_.netMask_.ToString(tap); + NETMGR_LOGI("config->netMask_ = [%{public}s]", config->ipStatic_.netMask_.ToString(tap).c_str()); + for (auto it = config->ipStatic_.dnsServers_.begin(); it != config->ipStatic_.dnsServers_.end(); ++it) { + context->dns0AddrInfo = it->ToString(tap); + context->dns1AddrInfo = it->ToString(tap); + NETMGR_LOGI("config->dnsServers_ = [%{public}s]", it->ToString(tap).c_str()); + } + } else { + context->ifActivate = -1; + } +} + +void NapiEthernet::CompleteGetIfaceConfig(napi_env env, napi_status status, void *data) +{ + NETMGR_LOGI("CompleteGetIfaceConfig"); + EthernetAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + napi_value info = nullptr; + napi_value infoFail = nullptr; + napi_create_object(env, &info); + napi_create_string_utf8(env, "fail", NAPI_AUTO_LENGTH, &infoFail); + NpiCommon::SetPropertyInt32(env, info, "mode", context->ipMode); + NpiCommon::SetPropertyString(env, info, "ipAddr", context->ipAddrInfo); + NpiCommon::SetPropertyString(env, info, "routeAddr", context->routeAddrInfo); + NpiCommon::SetPropertyString(env, info, "gateAddr", context->gateAddrInfo); + NpiCommon::SetPropertyString(env, info, "maskAddr", context->maskAddrInfo); + NpiCommon::SetPropertyString(env, info, "dns0Addr", context->dns0AddrInfo); + NpiCommon::SetPropertyString(env, info, "dns1Addr", context->dns1AddrInfo); + if (context->callbackRef == nullptr) { + if (context->ifActivate == -1) { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, infoFail)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } + } else { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + if (context->ifActivate == 0) { + callbackValues[ARGV_INDEX_0] = infoFail; + } else { + callbackValues[ARGV_INDEX_1] = info; + } + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +void NapiEthernet::ExecIsActivate(napi_env env, void *data) +{ + NETMGR_LOGI("ExecIsActivate"); + EthernetAsyncContext *context = (EthernetAsyncContext *)data; + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + context->ifActivate = DelayedSingleton::GetInstance()->IsActivate(context->ethernetName); + NETMGR_LOGI("ifActivate == [%{public}d]", context->ifActivate); +} + +void NapiEthernet::CompleteIsActivate(napi_env env, napi_status status, void *data) +{ + NETMGR_LOGI("CompleteIsActivate"); + EthernetAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + napi_value info = nullptr; + napi_create_int32(env, context->ifActivate, &info); + if (context->callbackRef == nullptr) { + if (context->ifActivate == -1) { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } + } else { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + if (context->ifActivate == -1) { + callbackValues[ARGV_INDEX_0] = info; + } else { + callbackValues[ARGV_INDEX_1] = info; + } + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +void NapiEthernet::ExecGetActivateInterfaces(napi_env env, void *data) +{ + NETMGR_LOGI("ExecGetActivateInterfaces"); + EthernetAsyncContext *context = (EthernetAsyncContext *)data; + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + context->ethernetNameList = DelayedSingleton::GetInstance()->GetActivateInterfaces(); +} + +void NapiEthernet::CompleteGetActivateInterfaces(napi_env env, napi_status status, void *data) +{ + NETMGR_LOGI("CompleteGetActivateInterfaces"); + EthernetAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + // creat function return + napi_value infoAttay = nullptr; + napi_value info = nullptr; + napi_create_array_with_length(env, context->ethernetNameList.size(), &infoAttay); + for (size_t index = 0; index < context->ethernetNameList.size(); index++) { + napi_create_string_utf8(env, context->ethernetNameList[index].c_str(), NAPI_AUTO_LENGTH, &info); + napi_set_element(env, infoAttay, index, info); + } + if (context->callbackRef == nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, infoAttay)); + } else { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + callbackValues[CALLBACK_ARGV_INDEX_1] = infoAttay; + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +napi_value NapiEthernet::SetIfaceConfig(napi_env env, napi_callback_info info) +{ + NETMGR_LOGI("SetIfaceConfig"); + size_t argc = ARGV_NUM_4; + napi_value argv[] = {nullptr, nullptr, nullptr, nullptr} ; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NETMGR_LOGI("SetIfaceConfig agvc = [%{public}d]", static_cast(argc)); + EthernetAsyncContext* context = std::make_unique().release(); + // Parse Js argv + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[ARGV_INDEX_0], + context->ethernetName, ETHERNET_NAME_MAX_BYTE, &(context->ethernetNameRealBytes))); + NETMGR_LOGI("SetIfaceConfig ethernetName = [%{public}s]", context->ethernetName); + // Parse Js object [ip] + NAPI_CALL(env, napi_get_value_int32(env, argv[ARGV_INDEX_1], &context->ipMode)); + NETMGR_LOGI("SetIfaceConfig mode = [%{public}d]", context->ipMode); + if (context->ipMode == IPSetMode::STATIC) { + NpiCommon::GetPropertyString(env, argv[ARGV_INDEX_2], "ipAddr", context->ipAddrInfo); + NpiCommon::GetPropertyString(env, argv[ARGV_INDEX_2], "routeAddr", context->routeAddrInfo); + NpiCommon::GetPropertyString(env, argv[ARGV_INDEX_2], "gateAddr", context->gateAddrInfo); + NpiCommon::GetPropertyString(env, argv[ARGV_INDEX_2], "maskAddr", context->maskAddrInfo); + NpiCommon::GetPropertyString(env, argv[ARGV_INDEX_2], "dnsAddr0", context->dns0AddrInfo); + NpiCommon::GetPropertyString(env, argv[ARGV_INDEX_2], "dnsAddr1", context->dns1AddrInfo); + } + napi_value result = nullptr; + if ((argc == ARGV_NUM_2) || (argc == ARGV_NUM_3 && context->ipMode == IPSetMode::STATIC)) { + if (context->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if ((argc == ARGV_NUM_4) || (argc == ARGV_NUM_3 && context->ipMode == IPSetMode::DHCP)) { + NAPI_CALL(env, napi_create_reference(env, argv[argc - 1], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("SetIfaceConfig exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "SetIfaceConfig", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecSetIfaceConfig, + CompleteSetIfaceConfig, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiEthernet::GetIfaceConfig(napi_env env, napi_callback_info info) +{ + NETMGR_LOGI("GetIfaceConfig"); + size_t argc = ARGV_NUM_2; + napi_value argv[] = {nullptr, nullptr} ; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NETMGR_LOGI("GetIfaceConfig agvc = [%{public}d]", static_cast(argc)); + EthernetAsyncContext* context = std::make_unique().release(); + // Parse Js argv + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[ARGV_INDEX_0], + context->ethernetName, ETHERNET_NAME_MAX_BYTE, &(context->ethernetNameRealBytes))); + NETMGR_LOGI("GetIfaceConfig [%{public}s]", context->ethernetName); + napi_value result = nullptr; + if (argc == ARGV_NUM_1) { + if (context->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_NUM_2) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("GetIfaceConfig exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "GetIfaceConfig", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecGetIfaceConfig, + CompleteGetIfaceConfig, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiEthernet::IsActivate(napi_env env, napi_callback_info info) +{ + NETMGR_LOGI("IsActivate"); + size_t argc = ARGV_NUM_2; + napi_value argv[] = {nullptr, nullptr} ; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NETMGR_LOGI("IsActivate agvc = [%{public}d]", static_cast(argc)); + EthernetAsyncContext* context = std::make_unique().release(); + // Parse Js argv + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[ARGV_INDEX_0], + context->ethernetName, ETHERNET_NAME_MAX_BYTE, &(context->ethernetNameRealBytes))); + NETMGR_LOGI("IsActivate [%{public}s]", context->ethernetName); + napi_value result = nullptr; + if (argc == ARGV_NUM_1) { + if (context->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_NUM_2) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("IsActivate exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "IsActivate", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecIsActivate, + CompleteIsActivate, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiEthernet::GetActivateInterfaces(napi_env env, napi_callback_info info) +{ + size_t argc = ARGV_NUM_1; + napi_value argv[] = {nullptr} ; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NETMGR_LOGI("GetActivateInterfaces agvc = [%{public}d]", static_cast(argc)); + EthernetAsyncContext* context = std::make_unique().release(); + napi_value result = nullptr; + if (argc == ARGV_NUM_0) { + if (context->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_NUM_1) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_0], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("GetActivateInterfaces exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "GetActivateInterfaces", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecGetActivateInterfaces, + CompleteGetActivateInterfaces, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiEthernet::DeclareEthernetData(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("STATIC", + NpiCommon::NapiValueByInt32(env, static_cast(IPSetMode::STATIC))), + DECLARE_NAPI_STATIC_PROPERTY("DHCP", + NpiCommon::NapiValueByInt32(env, static_cast(IPSetMode::DHCP))), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value NapiEthernet::DeclareEthernetInterface(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("setIfaceConfig", SetIfaceConfig), + DECLARE_NAPI_FUNCTION("getIfaceConfig", GetIfaceConfig), + DECLARE_NAPI_FUNCTION("isActivate", IsActivate), + DECLARE_NAPI_FUNCTION("getActivateInterfaces", GetActivateInterfaces), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value NapiEthernet::RegisterEthernetInterface(napi_env env, napi_value exports) +{ + DeclareEthernetInterface(env, exports); + DeclareEthernetData(env, exports); + return nullptr; +} + +static napi_module _ethernetModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = NapiEthernet::RegisterEthernetInterface, + .nm_modname = "netmanager.ethernet", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +extern "C" __attribute__((constructor)) void RegisterEthernetModule(void) +{ + napi_module_register(&_ethernetModule); +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/frameworks/js/netpolicy/BUILD.gn b/frameworks/js/netpolicy/BUILD.gn new file mode 100755 index 0000000..d504eed --- /dev/null +++ b/frameworks/js/netpolicy/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +NETMANAGER_NAPI_ROOT = "$SUBSYSTEM_DIR/netmanager_standard/frameworks/js/" + +ohos_shared_library("netpolicy") { + include_dirs = [ + "//third_party/node/src", + "$NETMANAGER_NAPI_ROOT/netpolicy/include", + "$NETMANAGER_NAPI_ROOT/common", + "$NETMANAGER_BASE_ROOT/utils/log/include", + "$NETPOLICYMANAGER_SOURCE_DIR/include", + "$NETPOLICYMANAGER_SOURCE_DIR/include/ipc", + ] + + sources = [ + "$NETMANAGER_NAPI_ROOT/common/napi_common.cpp", + "$NETMANAGER_NAPI_ROOT/netpolicy/src/napi_net_policy.cpp", + ] + + defines = [ "NETMGR_DEBUG" ] + + deps = [ + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$INNERKITS_ROOT/native/netpolicymanager:net_policy_manager_if", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/ace/napi/:ace_napi", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + relative_install_dir = "module" + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/frameworks/js/netpolicy/include/napi_net_policy.h b/frameworks/js/netpolicy/include/napi_net_policy.h new file mode 100755 index 0000000..fc33b51 --- /dev/null +++ b/frameworks/js/netpolicy/include/napi_net_policy.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_NET_POLICY_H +#define NAPI_NET_POLICY_H + +#include +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "net_policy_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +// net policy async context +struct NetPolicyAsyncContext { + napi_async_work work = nullptr; + napi_deferred deferred = nullptr; + napi_ref callbackRef = nullptr; + // uid + uint32_t uid = 0; + // policy + uint32_t policy = 0; + // result of policy napi + int32_t policyResult = 0; + // vector of uid + std::vector uidTogether; + // result of bool type + bool result = false; + // metered + bool metered = false; + // interface name + std::string interfaceName; +}; + +class NapiNetPolicy { +public: + NapiNetPolicy(); + ~NapiNetPolicy() = default; + static napi_value RegisterNetPolicyInterface(napi_env env, napi_value exports); + static napi_value DeclareNapiNetPolicyInterface(napi_env env, napi_value exports); + static napi_value DeclareNapiNetPolicyData(napi_env env, napi_value exports); + static napi_value DeclareNapiNetPolicyResultData(napi_env env, napi_value exports); + + static void ExecSetUidPolicy(napi_env env, void *data); + static void ExecGetUids(napi_env env, void *data); + static void ExecGetUidPolicy(napi_env env, void *data); + static void ExecIsUidNetAccess(napi_env env, void *data); + static void CompleteSetUidPolicy(napi_env env, napi_status status, void *data); + static void CompleteGetUids(napi_env env, napi_status status, void *data); + static void CompleteGetUidPolicy(napi_env env, napi_status status, void *data); + static void CompleteIsUidNetAccess(napi_env env, napi_status status, void *data); + // Declare napi interfaces for JS + static napi_value SetUidPolicy(napi_env env, napi_callback_info info); + static napi_value GetUidPolicy(napi_env env, napi_callback_info info); + static napi_value GetUids(napi_env env, napi_callback_info info); + static napi_value IsUidNetAccess(napi_env env, napi_callback_info info); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NAPI_NET_POLICY_H diff --git a/frameworks/js/netpolicy/src/napi_net_policy.cpp b/frameworks/js/netpolicy/src/napi_net_policy.cpp new file mode 100755 index 0000000..e7831cb --- /dev/null +++ b/frameworks/js/netpolicy/src/napi_net_policy.cpp @@ -0,0 +1,442 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_net_policy.h" +#include +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "net_mgr_log_wrapper.h" +#include "i_net_policy_service.h" +#include "net_conn_constants.h" +#include "net_policy_client.h" +#include "napi_common.h" + +namespace OHOS { +namespace NetManagerStandard { +void NapiNetPolicy::ExecSetUidPolicy(napi_env env, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + NetUidPolicy policy = static_cast(context->policy); + context->policyResult = + static_cast(DelayedSingleton::GetInstance()->SetUidPolicy(context->uid, policy)); + NETMGR_LOGI("ExecSetUidPolicy, policy = [%{public}d], policyResult = [%{public}d]", + context->policy, context->policyResult); +} + +void NapiNetPolicy::ExecGetUids(napi_env env, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + NetUidPolicy policy = static_cast(context->policy); + context->uidTogether = DelayedSingleton::GetInstance()->GetUids(policy); + NETMGR_LOGI("ExecGetUids, policy = [%{public}d], res.length = [%{public}d]", + context->policy, static_cast(context->uidTogether.size())); +} + +void NapiNetPolicy::ExecGetUidPolicy(napi_env env, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + context->policyResult = + static_cast(DelayedSingleton::GetInstance()->GetUidPolicy(context->uid)); + NETMGR_LOGI("ExecGetUidPolicy, uid = [%{public}d], policyResult = [%{public}d]", + context->uid, context->policyResult); +} + +void NapiNetPolicy::ExecIsUidNetAccess(napi_env env, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + if (context->interfaceName.length() > 0) { + context->result = + DelayedSingleton::GetInstance()->IsUidNetAccess(context->uid, context->interfaceName); + } else { + context->result = + DelayedSingleton::GetInstance()->IsUidNetAccess(context->uid, context->metered); + } +} +void NapiNetPolicy::CompleteSetUidPolicy(napi_env env, napi_status status, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + napi_value info = nullptr; + napi_create_int32(env, context->policyResult, &info); + if (context->callbackRef == nullptr) { + // promiss return + if (context->policyResult != static_cast(NetPolicyResultCode::ERR_NONE)) { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } + } else { + // call back + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + if (context->policyResult != static_cast(NetPolicyResultCode::ERR_NONE)) { + callbackValues[CALLBACK_ARGV_INDEX_0] = info; + } else { + callbackValues[CALLBACK_ARGV_INDEX_1] = info; + } + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +void NapiNetPolicy::CompleteGetUids(napi_env env, napi_status status, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + napi_value info = nullptr; + std::vector& res = context->uidTogether; + napi_create_array(env, &info); + for (unsigned int i = 0; i < res.size(); i++) { + napi_value num; + napi_create_uint32(env, res[i], &num); + napi_set_element(env, info, i, num); + } + if (!context->callbackRef) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } else { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + callbackValues[CALLBACK_ARGV_INDEX_1] = info; + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +void NapiNetPolicy::CompleteGetUidPolicy(napi_env env, napi_status status, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + napi_value info = nullptr; + napi_create_int32(env, context->policyResult, &info); + if (!context->callbackRef) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } else { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + callbackValues[CALLBACK_ARGV_INDEX_1] = info; + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +void NapiNetPolicy::CompleteIsUidNetAccess(napi_env env, napi_status status, void *data) +{ + NetPolicyAsyncContext* context = static_cast(data); + if (context == nullptr) { + NETMGR_LOGE("context == nullptr"); + return; + } + napi_value info = nullptr; + napi_create_int32(env, context->result, &info); + if (!context->callbackRef) { + if (context->result == 0) { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, context->deferred, info)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, context->deferred, info)); + } + } else { + napi_value callbackValues[CALLBACK_ARGV_CNT] = {nullptr, nullptr}; + napi_value recv = nullptr; + napi_value result = nullptr; + napi_value callbackFunc = nullptr; + napi_get_undefined(env, &recv); + napi_get_reference_value(env, context->callbackRef, &callbackFunc); + if (context->result == 0) { + callbackValues[CALLBACK_ARGV_INDEX_0] = info; + } else { + callbackValues[CALLBACK_ARGV_INDEX_1] = info; + } + napi_call_function(env, recv, callbackFunc, std::size(callbackValues), callbackValues, &result); + napi_delete_reference(env, context->callbackRef); + } + napi_delete_async_work(env, context->work); + delete context; + context = nullptr; +} + +napi_value NapiNetPolicy::DeclareNapiNetPolicyData(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_NONE", + NpiCommon::NapiValueByInt32(env, static_cast(NetUidPolicy::NET_POLICY_NONE))), + DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_ALLOW_METERED_BACKGROUND", + NpiCommon::NapiValueByInt32(env, static_cast(NetUidPolicy::NET_POLICY_ALLOW_METERED_BACKGROUND))), + DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_TEMPORARY_ALLOW_METERED", + NpiCommon::NapiValueByInt32(env, static_cast(NetUidPolicy::NET_POLICY_TEMPORARY_ALLOW_METERED))), + DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_REJECT_METERED_BACKGROUND", + NpiCommon::NapiValueByInt32(env, static_cast(NetUidPolicy::NET_POLICY_REJECT_METERED_BACKGROUND))), + DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_ALLOW_ALL", + NpiCommon::NapiValueByInt32(env, static_cast(NetUidPolicy::NET_POLICY_ALLOW_ALL))), + DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_REJECT_ALL", + NpiCommon::NapiValueByInt32(env, static_cast(NetUidPolicy::NET_POLICY_REJECT_ALL))), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value NapiNetPolicy::DeclareNapiNetPolicyResultData(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("ERR_NONE", + NpiCommon::NapiValueByInt32(env, static_cast(NetPolicyResultCode::ERR_NONE))), + DECLARE_NAPI_STATIC_PROPERTY("ERR_INTERNAL_ERROR", + NpiCommon::NapiValueByInt32(env, static_cast(NetPolicyResultCode::ERR_INTERNAL_ERROR))), + DECLARE_NAPI_STATIC_PROPERTY("ERR_INVALID_UID", + NpiCommon::NapiValueByInt32(env, static_cast(NetPolicyResultCode::ERR_INVALID_UID))), + DECLARE_NAPI_STATIC_PROPERTY("ERR_INVALID_POLICY", + NpiCommon::NapiValueByInt32(env, static_cast(NetPolicyResultCode::ERR_INVALID_POLICY))), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value NapiNetPolicy::DeclareNapiNetPolicyInterface(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("setUidPolicy", SetUidPolicy), + DECLARE_NAPI_FUNCTION("getUidPolicy", GetUidPolicy), + DECLARE_NAPI_FUNCTION("getUids", GetUids), + DECLARE_NAPI_FUNCTION("isUidNetAccess", IsUidNetAccess), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value NapiNetPolicy::SetUidPolicy(napi_env env, napi_callback_info info) +{ + size_t argc = ARGV_NUM_3; + napi_value argv[] = {nullptr, nullptr, nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NetPolicyAsyncContext* context = std::make_unique().release(); + NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_INDEX_0], &context->uid)); + NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_INDEX_1], &context->policy)); + NETMGR_LOGI("JS agvc count = [%{public}d], argv[ARGV_INDEX_0] = [%{public}d], argv[ARGV_INDEX_1] = [%{public}d]", + static_cast(argc), context->uid, context->policy); + napi_value result = nullptr; + if (argc == ARGV_INDEX_2) { + if (context->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_INDEX_3) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_2], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("SetUidPolicy exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "SetUidPolicy", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecSetUidPolicy, + CompleteSetUidPolicy, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiNetPolicy::GetUidPolicy(napi_env env, napi_callback_info info) +{ + size_t argc = ARGV_INDEX_2; + napi_value argv[] = {nullptr, nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NetPolicyAsyncContext* context = std::make_unique().release(); + NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_INDEX_0], &context->uid)); + NETMGR_LOGE("JS agvc count = [%{public}d], argv[0] = [%{public}d]", + static_cast(argc), context->uid); + // Get and verify parameter[js] + napi_value result = nullptr; + if (argc == ARGV_INDEX_1) { + if (!context->callbackRef) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_INDEX_2) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("GetUidPolicy exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "getUids", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecGetUidPolicy, + CompleteGetUidPolicy, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiNetPolicy::GetUids(napi_env env, napi_callback_info info) +{ + size_t argc = ARGV_INDEX_2; + napi_value argv[] = {nullptr, nullptr} ; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NetPolicyAsyncContext* context = std::make_unique().release(); + NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_INDEX_0], &context->policy)); + NETMGR_LOGE("JS agvc count = [%{public}d], argv[0] = [%{public}d]", + static_cast(argc), context->policy); + // Get and verify parameter[js] + napi_value result = nullptr; + if (argc == ARGV_INDEX_1) { + if (!context->callbackRef) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_INDEX_2) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_INDEX_1], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("GetUids exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "getUids", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecGetUids, + CompleteGetUids, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiNetPolicy::IsUidNetAccess(napi_env env, napi_callback_info info) +{ + napi_valuetype valueType = napi_undefined; + size_t argc = ARGV_NUM_3; + napi_value argv[] = {nullptr, nullptr, nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NetPolicyAsyncContext* context = std::make_unique().release(); + NAPI_CALL(env, napi_get_value_uint32(env, argv[ARGV_NUM_0], &context->uid)); + napi_typeof(env, argv[ARGV_NUM_1], &valueType); + if (napi_valuetype::napi_boolean == valueType) { + NAPI_CALL(env, napi_get_value_bool(env, argv[ARGV_NUM_1], &context->metered)); + } + if (napi_valuetype::napi_string == valueType) { + char buf[BUFFER_BYTE] = {0}; + size_t typeLen = 0; + napi_get_value_string_utf8(env, argv[ARGV_NUM_1], buf, sizeof(buf), &typeLen); + context->interfaceName = buf; + NETMGR_LOGE("interfaceName = [%{public}s].\n", context->interfaceName.c_str()); + } + NETMGR_LOGI("JS agvc count = [%{public}d], argv[0] = [%{public}d], argv[1] = [%{public}d]", + static_cast(argc), context->uid, context->metered); + napi_value result = nullptr; + if (argc == ARGV_NUM_2) { + if (!context->callbackRef) { + NAPI_CALL(env, napi_create_promise(env, &context->deferred, &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + } else if (argc == ARGV_NUM_3) { + NAPI_CALL(env, napi_create_reference(env, argv[ARGV_NUM_2], CALLBACK_REF_CNT, &context->callbackRef)); + } else { + NETMGR_LOGE("IsUidNetAccess exception"); + } + // creat async work + napi_value resource = nullptr; + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &resource)); + NAPI_CALL(env, napi_create_string_utf8(env, "IsUidNetAccess", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, resource, resourceName, + ExecIsUidNetAccess, + CompleteIsUidNetAccess, + (void *)context, + &context->work)); + NAPI_CALL(env, napi_queue_async_work(env, context->work)); + return result; +} + +napi_value NapiNetPolicy::RegisterNetPolicyInterface(napi_env env, napi_value exports) +{ + NETMGR_LOGI("RegisterNetPolicyInterface"); + DeclareNapiNetPolicyInterface(env, exports); + DeclareNapiNetPolicyData(env, exports); + DeclareNapiNetPolicyResultData(env, exports); + return nullptr; +} + +static napi_module _netPolicyModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = NapiNetPolicy::RegisterNetPolicyInterface, + .nm_modname = "netmanager.netpolicy", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +extern "C" __attribute__((constructor)) void RegisterNetPolicyModule(void) +{ + napi_module_register(&_netPolicyModule); +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/interfaces/innerkits/native/dnsresolvermanager/BUILD.gn b/interfaces/innerkits/native/dnsresolvermanager/BUILD.gn new file mode 100755 index 0000000..874b156 --- /dev/null +++ b/interfaces/innerkits/native/dnsresolvermanager/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +config("net_conn_manager_if_config") { + # header file path + include_dirs = [ + "$DNSRESOLVERMANAGER_SOURCE_DIR/include/ipc/", + "$INNERKITS_ROOT/native/dnsresolvermanager/include", + "$INNERKITS_ROOT/native/netconnmanager/include", + "$INNERKITS_ROOT/native/include", + ] + + cflags = [] + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + if (is_standard_system) { + cflags += [ "-DCONFIG_STANDARD_SYSTEM" ] + } + if (defined(build_public_version) && build_public_version) { + cflags += [ "-DBUILD_PUBLIC_VERSION" ] + } +} + +ohos_shared_library("dns_resolver_manager_if") { + sources = [ + "$DNSRESOLVERMANAGER_INNERKITS_SOURCE_DIR/src/dns_addr_info.cpp", + "$DNSRESOLVERMANAGER_INNERKITS_SOURCE_DIR/src/dns_resolver_client.cpp", + "$DNSRESOLVERMANAGER_SOURCE_DIR/src/ipc/dns_resolver_service_proxy.cpp", + ] + + include_dirs = [ "$DNSRESOLVERMANAGER_SOURCE_DIR/include/" ] + + public_configs = [ ":net_conn_manager_if_config" ] + + deps = [ + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + ] + + external_deps = [ + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "NETMGR_LOG_TAG = \"DnsResolverManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/interfaces/innerkits/native/dnsresolvermanager/include/dns_addr_info.h b/interfaces/innerkits/native/dnsresolvermanager/include/dns_addr_info.h new file mode 100755 index 0000000..b955b00 --- /dev/null +++ b/interfaces/innerkits/native/dnsresolvermanager/include/dns_addr_info.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DNS_ADDR_INFO_H +#define DNS_ADDR_INFO_H + +#include +#include + +#include "parcel.h" + +namespace OHOS { +namespace NetManagerStandard { +struct DnsAddrInfo : public Parcelable { + int32_t flags_ = 0; + int32_t family_ = 0; + int32_t sockType_ = 0; + int32_t protocol_ = 0; + std::string addr_; + std::string canonName_; + + bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native/dnsresolvermanager/include/dns_resolver_client.h b/interfaces/innerkits/native/dnsresolvermanager/include/dns_resolver_client.h new file mode 100755 index 0000000..e461d60 --- /dev/null +++ b/interfaces/innerkits/native/dnsresolvermanager/include/dns_resolver_client.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DNS_RESOLVER_MANAGER_H +#define DNS_RESOLVER_MANAGER_H + +#include + +#include "parcel.h" +#include "singleton.h" + +#include "i_dns_resolver_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class DnsResolverClient { + DECLARE_DELAYED_SINGLETON(DnsResolverClient) + +public: + /** + * @brief Get Addresses By domain Name + * + * @param The domain name + * @param The address information is parsed successfully + * @return Returns 0 as success, other values as failure + */ + int32_t GetAddressesByName(const std::string &hostName, std::vector &addrInfo); + /** + * @brief Get Addresses By domain Name + * + * @param DNS server address + * @param DNS server address + * @param Address information structure + * @param The address information is parsed successfully + * @return Returns 0 as success, other values as failure + */ + int32_t GetAddrInfo(const std::string &hostName, const std::string &server, + const sptr &hints, std::vector> &dnsAddrInfo); + /** + * @brief Create a network cache and netId mapping + * + * @param netId + * @return Returns 0 as success, other values as failure + */ + int32_t CreateNetworkCache(uint16_t netId); + /** + * @brief Delete the network cache and remove the mapping with netId + * + * @param netId + * @return Returns 0 as success, other values as failure + */ + int32_t DestoryNetworkCache(uint16_t netId); + /** + * @brief Clear the network cache information + * + * @param netId + * @return Returns 0 as success, other values as failure + */ + int32_t FlushNetworkCache(uint16_t netId); + /** + * @brief Bind the DNS server address to netId + * + * @param netId + * @param Timeout of domain name request + * @param Number of Domain name Requests + * @param DNS server address information + * @param The domain name + * @return Returns 0 as success, other values as failure + */ + int32_t SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains); + /** + * @brief Obtain domain name resolution configuration information + * + * @param netId + * @param DNS server address information + * @param The domain name + * @param Timeout of domain name request + * @param Number of Domain name Requests + * @return Returns 0 as success, other values as failure + */ + int32_t GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount); + +private: + class DnsResolverDeathRecipient : public IRemoteObject::DeathRecipient { + public: + explicit DnsResolverDeathRecipient(DnsResolverClient &client) : client_(client) {} + ~DnsResolverDeathRecipient() override = default; + void OnRemoteDied(const wptr &remote) override + { + client_.OnRemoteDied(remote); + } + + private: + DnsResolverClient &client_; + }; + +private: + sptr GetProxy(); + void OnRemoteDied(const wptr &remote); + +private: + std::mutex mutex_; + sptr dnsResolverService_; + sptr deathRecipient_; +}; +} // namespace NetManagerStandard +} // namespace OHOS + +#endif // DNS_RESOLVER_MANAGER_H \ No newline at end of file diff --git a/interfaces/innerkits/native/dnsresolvermanager/include/dns_resolver_constants.h b/interfaces/innerkits/native/dnsresolvermanager/include/dns_resolver_constants.h new file mode 100755 index 0000000..31fed08 --- /dev/null +++ b/interfaces/innerkits/native/dnsresolvermanager/include/dns_resolver_constants.h @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DNS_RESOLVER_CONSTANTS_H +#define DNS_RESOLVER_CONSTANTS_H + +#include "netmanager_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int DNS_ERROR = -1; +constexpr int DNS_SUCCESS = 0; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // DNS_RESOLVER_CONSTANTS_H \ No newline at end of file diff --git a/interfaces/innerkits/native/ethernetmanager/BUILD.gn b/interfaces/innerkits/native/ethernetmanager/BUILD.gn new file mode 100755 index 0000000..5265e86 --- /dev/null +++ b/interfaces/innerkits/native/ethernetmanager/BUILD.gn @@ -0,0 +1,80 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") +config("net_conn_manager_if_config") { + # header file path + include_dirs = [ + "$ETHERNETMANAGER_SOURCE_DIR/include/ipc/", + "$INNERKITS_ROOT/native/ethernetmanager/include", + "$INNERKITS_ROOT/native/netconnmanager/include", + "$INNERKITS_ROOT/native/include", + ] + + cflags = [] + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + if (is_standard_system) { + cflags += [ "-DCONFIG_STANDARD_SYSTEM" ] + } + if (defined(build_public_version) && build_public_version) { + cflags += [ "-DBUILD_PUBLIC_VERSION" ] + } +} + +ohos_shared_library("ethernet_manager_if") { + sources = [ + "$ETHERNETMANAGER_INNERKITS_SOURCE_DIR/src/ethernet_client.cpp", + "$ETHERNETMANAGER_INNERKITS_SOURCE_DIR/src/interface_configuration.cpp", + "$ETHERNETMANAGER_INNERKITS_SOURCE_DIR/src/static_configuration.cpp", + "$ETHERNETMANAGER_SOURCE_DIR/src/ipc/ethernet_service_proxy.cpp", + ] + + include_dirs = [ "$ETHERNETMANAGER_SOURCE_DIR/include/" ] + + public_configs = [ ":net_conn_manager_if_config" ] + + deps = [ + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + ] + + external_deps = [ + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "NETMGR_LOG_TAG = \"EthernetManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/interfaces/innerkits/native/ethernetmanager/include/ethernet_client.h b/interfaces/innerkits/native/ethernetmanager/include/ethernet_client.h new file mode 100755 index 0000000..db6729c --- /dev/null +++ b/interfaces/innerkits/native/ethernetmanager/include/ethernet_client.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ETHERNET_MANAGER_H +#define ETHERNET_MANAGER_H + +#include + +#include "parcel.h" +#include "singleton.h" + +#include "i_ethernet_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class EthernetClient { + DECLARE_DELAYED_SINGLETON(EthernetClient) + +public: + /** + * @brief Set the network interface configuration + * + * @param Network interface name + * @param Network interface parameters + * @return Returns 0 as success, other values as failure + */ + int32_t SetIfaceConfig(const std::string &iface, sptr &ic); + /** + * @brief Gets the network interface configuration parameters + * + * @param Network interface name + * @return Parameter is returned on success, null on failure + */ + sptr GetIfaceConfig(const std::string &iface); + /** + * @brief Gets the network interface configuration parameters + * + * @param Network interface name + * @return Returns 1 for device open (active), 0 for device closed (inactive), and -1 for failure + */ + int32_t IsActivate(const std::string &iface); + /** + * @brief Gets the list of active devices + * + * @return Return to device List + */ + std::vector GetActivateInterfaces(); + +private: + class EthernetDeathRecipient : public IRemoteObject::DeathRecipient { + public: + explicit EthernetDeathRecipient(EthernetClient &client) : client_(client) {} + ~EthernetDeathRecipient() override = default; + void OnRemoteDied(const wptr &remote) override + { + client_.OnRemoteDied(remote); + } + + private: + EthernetClient &client_; + }; + +private: + sptr GetProxy(); + void OnRemoteDied(const wptr &remote); + +private: + std::mutex mutex_; + sptr ethernetService_; + sptr deathRecipient_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // ETHERNET_MANAGER_H \ No newline at end of file diff --git a/interfaces/innerkits/native/ethernetmanager/include/ethernet_constants.h b/interfaces/innerkits/native/ethernetmanager/include/ethernet_constants.h new file mode 100755 index 0000000..3c42533 --- /dev/null +++ b/interfaces/innerkits/native/ethernetmanager/include/ethernet_constants.h @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ETHERNET_CONSTANTS_H +#define ETHERNET_CONSTANTS_H + +#include "netmanager_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int ETHERNET_ERROR = -1; +constexpr int ETHERNET_SUCCESS = 0; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // ETHERNET_ERRORS_H \ No newline at end of file diff --git a/interfaces/innerkits/native/ethernetmanager/include/interface_configuration.h b/interfaces/innerkits/native/ethernetmanager/include/interface_configuration.h new file mode 100755 index 0000000..7445f41 --- /dev/null +++ b/interfaces/innerkits/native/ethernetmanager/include/interface_configuration.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACE_CONFIGURATION_H +#define INTERFACE_CONFIGURATION_H + +#include "static_configuration.h" + +namespace OHOS { +namespace NetManagerStandard { +typedef enum { + STATIC, + DHCP, +} IPSetMode; +struct InterfaceConfiguration : public Parcelable { + IPSetMode mode_; + StaticConfiguration ipStatic_; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native/ethernetmanager/include/static_configuration.h b/interfaces/innerkits/native/ethernetmanager/include/static_configuration.h new file mode 100755 index 0000000..b269f65 --- /dev/null +++ b/interfaces/innerkits/native/ethernetmanager/include/static_configuration.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STATIC_CONFIGURATION_H +#define STATIC_CONFIGURATION_H + +#include +#include + +#include "parcel.h" +#include "inet_addr.h" + +namespace OHOS { +namespace NetManagerStandard { +struct StaticConfiguration : public Parcelable { + INetAddr ipAddr_; + INetAddr route_; + INetAddr gate_; + INetAddr netMask_; + std::vector dnsServers_; + std::string domain_; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native/include/netmanager_constants.h b/interfaces/innerkits/native/include/netmanager_constants.h new file mode 100755 index 0000000..5dfc674 --- /dev/null +++ b/interfaces/innerkits/native/include/netmanager_constants.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETMANAGER_CONSTANTS_H +#define NETMANAGER_CONSTANTS_H + +#include + +namespace OHOS { +namespace NetManagerStandard { +constexpr int NETMANAGER_ERROR = -1; +constexpr int NETMANAGER_SUCCESS = 0; + +enum { + NETMANAGER_COMMON = 0x00, + NETMANAGER_DNS_RESOLVER_MANAGER = 0x01, + NETMANAGER_ETHERNET_MANAGER = 0x02, + NETMANAGER_NET_CONN_MANAGER = 0x03, + NETMANAGER_NET_POLICY_MANAGER = 0x04, +}; + +// Error code for common +constexpr ErrCode COMMON_ERR_OFFSET = ErrCodeOffset(SUBSYS_COMMUNICATION, NETMANAGER_COMMON); + +enum { + NETMANAGER_ERR_FAIL = COMMON_ERR_OFFSET, + NETMANAGER_ERR_MEMCPY_FAIL, + NETMANAGER_ERR_MEMSET_FAIL, + NETMANAGER_ERR_STRCPY_FAIL, + NETMANAGER_ERR_STRING_EMPTY, + NETMANAGER_ERR_LOCAL_PTR_NULL, + NETMANAGER_ERR_PERMISSION_ERR, + NETMANAGER_ERR_DESCRIPTOR_MISMATCH, + NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL, + NETMANAGER_ERR_WRITE_DATA_FAIL, + NETMANAGER_ERR_WRITE_REPLY_FAIL, + NETMANAGER_ERR_READ_DATA_FAIL, + NETMANAGER_ERR_READ_REPLY_FAIL, + NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL, + NETMANAGER_ERR_ADD_DEATH_RECIPIENT_FAIL, + NETMANAGER_ERR_REGISTER_CALLBACK_FAIL, + NETMANAGER_ERR_UNINIT, +}; + +// Error code for netmanager dns resolver +constexpr ErrCode DNS_ERR_OFFSET = ErrCodeOffset(SUBSYS_COMMUNICATION, NETMANAGER_DNS_RESOLVER_MANAGER); +// Error code for netmanager ethernet +constexpr ErrCode ETHERNET_ERR_OFFSET = ErrCodeOffset(SUBSYS_COMMUNICATION, NETMANAGER_ETHERNET_MANAGER); +// Error code for netmanager conn manager +constexpr ErrCode CONN_MANAGER_ERR_OFFSET = ErrCodeOffset(SUBSYS_COMMUNICATION, NETMANAGER_NET_CONN_MANAGER); +// Error code for netmanager policy manager +constexpr ErrCode POLICY_MANAGER_ERR_OFFSET = ErrCodeOffset(SUBSYS_COMMUNICATION, NETMANAGER_NET_POLICY_MANAGER); +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NETMANAGER_CONSTANTS_H \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/BUILD.gn b/interfaces/innerkits/native/netconnmanager/BUILD.gn new file mode 100755 index 0000000..6ed54b2 --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/BUILD.gn @@ -0,0 +1,83 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +config("net_conn_manager_if_config") { + # header file path + include_dirs = [ + "$NETCONNMANAGER_SOURCE_DIR/include/ipc", + "$INNERKITS_ROOT/native/netconnmanager/include", + "$INNERKITS_ROOT/native/netconnmanager/include/ipc", + ] + + cflags = [] + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + if (is_standard_system) { + cflags += [ "-DCONFIG_STANDARD_SYSTEM" ] + } + if (defined(build_public_version) && build_public_version) { + cflags += [ "-DBUILD_PUBLIC_VERSION" ] + } +} + +ohos_shared_library("net_conn_manager_if") { + sources = [ + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/inet_addr.cpp", + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/ipc/net_conn_callback_stub.cpp", + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/net_conn_callback_info.cpp", + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/net_conn_client.cpp", + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/net_link_info.cpp", + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/net_specifier.cpp", + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/net_supplier_info.cpp", + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/route.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/ipc/net_conn_service_proxy.cpp", + ] + + include_dirs = [ "$NETCONNMANAGER_SOURCE_DIR/include/" ] + + public_configs = [ ":net_conn_manager_if_config" ] + + deps = [ "$NETMANAGER_BASE_ROOT/utils:net_manager_common" ] + + external_deps = [ + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "NETMGR_LOG_TAG = \"NetConnManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/interfaces/innerkits/native/netconnmanager/include/inet_addr.h b/interfaces/innerkits/native/netconnmanager/include/inet_addr.h new file mode 100755 index 0000000..65615d5 --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/inet_addr.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INET_ADDR_H +#define INET_ADDR_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace NetManagerStandard { +struct INetAddr : public Parcelable { + typedef enum { + UNKNOWN = 0x00, + IPV4 = 0x01, + IPV6 = 0x02, + } IpType; + + uint8_t type_ = UNKNOWN; + uint8_t family_ = 0x00; + uint8_t prefixlen_ = 0; + std::string address_; + std::string netMask_; + std::string hostName_; + + bool operator==(const INetAddr& obj) const; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); + static bool Marshalling(Parcel &parcel, const sptr &object); + std::string ToString(const std::string tab = "") const; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/include/ipc/i_net_conn_callback.h b/interfaces/innerkits/native/netconnmanager/include/ipc/i_net_conn_callback.h new file mode 100755 index 0000000..c7fd30a --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/ipc/i_net_conn_callback.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_NET_CONN_CALLBACK_H +#define I_NET_CONN_CALLBACK_H + +#include + +#include "iremote_broker.h" + +#include "net_conn_callback_info.h" + +namespace OHOS { +namespace NetManagerStandard { +class INetConnCallback : public IRemoteBroker { +public: + virtual ~INetConnCallback() = default; +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.NetManagerStandard.INetConnCallback"); + enum { + NET_CONN_STATE_CHANGED = 0, + }; + +public: + virtual int32_t NetConnStateChanged(const sptr &info) = 0; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // I_NET_CONN_CALLBACK_H diff --git a/interfaces/innerkits/native/netconnmanager/include/ipc/net_conn_callback_stub.h b/interfaces/innerkits/native/netconnmanager/include/ipc/net_conn_callback_stub.h new file mode 100755 index 0000000..5eefd7e --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/ipc/net_conn_callback_stub.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_CALLBACK_STUB_H +#define NET_CONN_CALLBACK_STUB_H + +#include + +#include "iremote_stub.h" + +#include "i_net_conn_callback.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetConnCallbackStub : public IRemoteStub { +public: + NetConnCallbackStub(); + virtual ~NetConnCallbackStub(); + + int32_t OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + using NetConnCallbackFunc = int32_t (NetConnCallbackStub::*)(MessageParcel &, MessageParcel &); + +private: + int32_t OnNetConnStateChanged(MessageParcel &data, MessageParcel &reply); + +private: + std::map memberFuncMap_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_CALLBACK_STUB_H diff --git a/interfaces/innerkits/native/netconnmanager/include/net_conn_callback_info.h b/interfaces/innerkits/native/netconnmanager/include/net_conn_callback_info.h new file mode 100755 index 0000000..9b11e49 --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/net_conn_callback_info.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CALLBACK_INFO_H +#define NET_CALLBACK_INFO_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace NetManagerStandard { +struct NetConnCallbackInfo : public Parcelable { + int32_t netState_ = 0; + uint32_t netType_ = 0; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); + static bool Marshalling(Parcel &parcel, const sptr &object); + std::string ToString(const std::string &tab) const; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CALLBACK_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/include/net_conn_client.h b/interfaces/innerkits/native/netconnmanager/include/net_conn_client.h new file mode 100755 index 0000000..218286e --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/net_conn_client.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_MANAGER_H +#define NET_CONN_MANAGER_H + +#include + +#include "parcel.h" +#include "singleton.h" + +#include "i_net_conn_service.h" +#include "net_link_info.h" +#include "net_specifier.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetConnClient { + DECLARE_DELAYED_SINGLETON(NetConnClient) + +public: + int32_t SystemReady(); + int32_t RegisterNetSupplier(uint32_t netType, const std::string &ident, uint64_t netCapabilities); + int32_t UnregisterNetSupplier(uint32_t supplierId); + int32_t RegisterNetConnCallback(const sptr &callback); + int32_t RegisterNetConnCallback(const sptr &netSpecifier, const sptr &callback); + int32_t UnregisterNetConnCallback(const sptr &callback); + int32_t UnregisterNetConnCallback(const sptr &netSpecifier, const sptr &callback); + int32_t UpdateNetSupplierInfo(uint32_t supplierId, const sptr &netSupplierInfo); + int32_t UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities); + int32_t UpdateNetLinkInfo(uint32_t supplierId, const sptr &netLinkInfo); + +private: + class NetConnDeathRecipient : public IRemoteObject::DeathRecipient { + public: + explicit NetConnDeathRecipient(NetConnClient &client) : client_(client) {} + ~NetConnDeathRecipient() override = default; + void OnRemoteDied(const wptr &remote) override + { + client_.OnRemoteDied(remote); + } + + private: + NetConnClient &client_; + }; + +private: + sptr GetProxy(); + void OnRemoteDied(const wptr &remote); + +private: + std::mutex mutex_; + sptr NetConnService_; + sptr deathRecipient_; +}; +} // namespace NetManagerStandard +} // namespace OHOS + +#endif // NET_CONN_MANAGER_H \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/include/net_conn_constants.h b/interfaces/innerkits/native/netconnmanager/include/net_conn_constants.h new file mode 100755 index 0000000..8037422 --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/net_conn_constants.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_CONSTANTS_H +#define NET_CONN_CONSTANTS_H + +namespace OHOS { +namespace NetManagerStandard { +enum NetConnResultCode { + NET_CONN_SUCCESS = 0, + NET_CONN_ERR_GET_REMOTE_OBJECT_FAILED = (-1), + NET_CONN_ERR_INPUT_NULL_PTR = (-2), + NET_CONN_ERR_INVALID_SUPPLIER_ID = (-3), + NET_CONN_ERR_INVALID_PARAMETER = (-4), + NET_CONN_ERR_NET_TYPE_NOT_FOUND = (-5), + NET_CONN_ERR_NO_ANY_NET_TYPE = (-6), + NET_CONN_ERR_NO_REGISTERED = (-7), + NET_CONN_ERR_INTERNAL_ERROR = (-1000) +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_CONSTANTS_H \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/include/net_link_info.h b/interfaces/innerkits/native/netconnmanager/include/net_link_info.h new file mode 100755 index 0000000..7f907eb --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/net_link_info.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_LINK_INFO_H +#define NET_LINK_INFO_H + +#include + +#include "inet_addr.h" +#include "net_specifier.h" +#include "route.h" + +namespace OHOS { +namespace NetManagerStandard { +struct NetLinkInfo : public Parcelable { + std::string ifaceName_; + std::string domain_; + std::list netAddrList_; + std::list dnsList_; + std::list routeList_; + uint16_t mtu_ = 0; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); + static bool Marshalling(Parcel &parcel, const sptr &object); + std::string ToString(const std::string &tab) const; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_LINK_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/include/net_specifier.h b/interfaces/innerkits/native/netconnmanager/include/net_specifier.h new file mode 100755 index 0000000..d9ad85e --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/net_specifier.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_SPECIFIER_H +#define NET_SPECIFIER_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace NetManagerStandard { +typedef enum { + NET_CAPABILITIES_NONE, + NET_CAPABILITIES_INTERNET = 1 << 0, + NET_CAPABILITIES_MMS = 1 << 1, + NET_CAPABILITIES_MAX +} NetCapabilities; + +typedef enum { + NET_TYPE_UNKNOWN, + NET_TYPE_CELLULAR, + NET_TYPE_ETHERNET, + NET_TYPE_MAX +} NetworkType; + +struct NetSpecifier : public Parcelable { + std::string ident_; + uint32_t netType_ = NET_TYPE_UNKNOWN; + uint64_t netCapabilities_ = NET_CAPABILITIES_NONE; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); + static bool Marshalling(Parcel &parcel, const sptr &object); + std::string ToString(const std::string &tab) const; + + bool operator< (const NetSpecifier &spec) const + { + return (netType_ < spec.netType_) || (netType_ == spec.netType_ && netCapabilities_ < spec.netCapabilities_); + } +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/include/net_supplier_info.h b/interfaces/innerkits/native/netconnmanager/include/net_supplier_info.h new file mode 100755 index 0000000..f112575 --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/net_supplier_info.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_SUPPLIER_INFO_H +#define NET_SUPPLIER_INFO_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace NetManagerStandard { +struct NetSupplierInfo : public Parcelable { + bool isAvailable_ = false; + bool isRoaming_ = false; + uint8_t strength_ = 0x00; + uint32_t frequency_ = 0x00; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); + static bool Marshalling(Parcel &parcel, const sptr &object); + std::string ToString(const std::string &tab) const; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_SUPPLIER_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/native/netconnmanager/include/route.h b/interfaces/innerkits/native/netconnmanager/include/route.h new file mode 100755 index 0000000..c76de70 --- /dev/null +++ b/interfaces/innerkits/native/netconnmanager/include/route.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ROUTE_H +#define ROUTE_H + +#include + +#include "inet_addr.h" + +namespace OHOS { +namespace NetManagerStandard { +struct Route : public Parcelable { + std::string iface_; + INetAddr destination_; + INetAddr gateway_; + + bool operator==(const Route& obj) const; + + virtual bool Marshalling(Parcel &parcel) const override; + static sptr Unmarshalling(Parcel &parcel); + static bool Marshalling(Parcel &parcel, const sptr &object); + std::string ToString(const std::string &tab) const; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native/netpolicymanager/BUILD.gn b/interfaces/innerkits/native/netpolicymanager/BUILD.gn new file mode 100755 index 0000000..204acef --- /dev/null +++ b/interfaces/innerkits/native/netpolicymanager/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +config("net_policy_manager_if_config") { + # header file path + include_dirs = [ + "$NETPOLICYMANAGER_SOURCE_DIR/include/ipc", + "$INNERKITS_ROOT/native/netpolicymanager/include", + ] + + cflags = [] + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + if (is_standard_system) { + cflags += [ "-DCONFIG_STANDARD_SYSTEM" ] + } + if (defined(build_public_version) && build_public_version) { + cflags += [ "-DBUILD_PUBLIC_VERSION" ] + } +} + +ohos_shared_library("net_policy_manager_if") { + sources = [ + "$NETPOLICYMANAGER_INNERKITS_SOURCE_DIR/src/net_policy_client.cpp", + "$NETPOLICYMANAGER_SOURCE_DIR/src/ipc/net_policy_service_proxy.cpp", + ] + + include_dirs = [ "$NETPOLICYMANAGER_SOURCE_DIR/include/" ] + + public_configs = [ ":net_policy_manager_if_config" ] + + deps = [ "$NETMANAGER_BASE_ROOT/utils:net_manager_common" ] + + external_deps = [ + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "NETMGR_LOG_TAG = \"NetPolicyManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/interfaces/innerkits/native/netpolicymanager/include/net_policy_client.h b/interfaces/innerkits/native/netpolicymanager/include/net_policy_client.h new file mode 100755 index 0000000..13fbee5 --- /dev/null +++ b/interfaces/innerkits/native/netpolicymanager/include/net_policy_client.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_MANAGER_H +#define NET_POLICY_MANAGER_H + +#include "singleton.h" + +#include "i_net_policy_service.h" +#include "net_policy_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetPolicyClient { + DECLARE_DELAYED_SINGLETON(NetPolicyClient) + +public: + NetPolicyResultCode SetUidPolicy(uint32_t uid, NetUidPolicy policy); + NetUidPolicy GetUidPolicy(uint32_t uid); + std::vector GetUids(NetUidPolicy policy); + bool IsUidNetAccess(uint32_t uid, bool metered); + bool IsUidNetAccess(uint32_t uid, const std::string &ifaceName); + +private: + class NetPolicyDeathRecipient : public IRemoteObject::DeathRecipient { + public: + explicit NetPolicyDeathRecipient(NetPolicyClient &client) : client_(client) {} + ~NetPolicyDeathRecipient() override = default; + void OnRemoteDied(const wptr &remote) override + { + client_.OnRemoteDied(remote); + } + + private: + NetPolicyClient &client_; + }; + +private: + sptr GetProxy(); + void OnRemoteDied(const wptr &remote); + +private: + std::mutex mutex_; + sptr netPolicyService_; + sptr deathRecipient_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_MANAGER_H diff --git a/interfaces/innerkits/native/netpolicymanager/include/net_policy_constants.h b/interfaces/innerkits/native/netpolicymanager/include/net_policy_constants.h new file mode 100755 index 0000000..18b00b1 --- /dev/null +++ b/interfaces/innerkits/native/netpolicymanager/include/net_policy_constants.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_CONSTANTS_H +#define NET_POLICY_CONSTANTS_H + +namespace OHOS { +namespace NetManagerStandard { +enum class NetPolicyResultCode { + ERR_NONE = 0, + ERR_INTERNAL_ERROR = (-1), + ERR_INVALID_UID = (-10001), + ERR_INVALID_POLICY = (-10002), +}; + +enum class NetUidPolicy { + NET_POLICY_NONE = 0, + NET_POLICY_ALLOW_METERED_BACKGROUND = 1 << 0, + NET_POLICY_TEMPORARY_ALLOW_METERED = 1 << 1, + NET_POLICY_REJECT_METERED_BACKGROUND = 1 << 2, + NET_POLICY_ALLOW_ALL = 1 << 5, + NET_POLICY_REJECT_ALL = 1 << 6, +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_CONSTANTS_H diff --git a/netmanager_base_config.gni b/netmanager_base_config.gni new file mode 100755 index 0000000..9541928 --- /dev/null +++ b/netmanager_base_config.gni @@ -0,0 +1,32 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +SUBSYSTEM_DIR = "//foundation/communication" +NETMANAGER_BASE_ROOT = "$SUBSYSTEM_DIR/netmanager_standard" +NETMANAGERNATIVE_ROOT = "$NETMANAGER_BASE_ROOT/services/netmanagernative" +INNERKITS_ROOT = "$NETMANAGER_BASE_ROOT/interfaces/innerkits" +NETCONNMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT//frameworks/innerkitsimpl/netconnmanager" +NETPOLICYMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT//frameworks/innerkitsimpl/netpolicymanager" +DNSRESOLVERMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT//frameworks/innerkitsimpl/dnsresolvermanager" +ETHERNETMANAGER_INNERKITS_SOURCE_DIR = "$NETMANAGER_BASE_ROOT//frameworks/innerkitsimpl/ethernetmanager" +NETCONNMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/netconnmanager" +NETPOLICYMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/netpolicymanager" +NETCONNMANAGER_COMMON_DIR = "$NETMANAGER_BASE_ROOT/services/common" +DNSRESOLVERMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/dnsresolvermanager" +ETHERNETMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/ethernetmanager" +NETMANAGER_PREBUILTS_DIR = "$NETMANAGER_BASE_ROOT/prebuilts" + +use_js_debug = false +declare_args() { + enable_netmgr_debug = false +} diff --git a/ohos.build b/ohos.build new file mode 100755 index 0000000..79e447c --- /dev/null +++ b/ohos.build @@ -0,0 +1,62 @@ +{ + "subsystem": "communication", + "parts": { + "netmanager_standard": { + "variants": [ + "phone", + "wearable", + "ivi" + ], + "module_list": [ + "//foundation/communication/netmanager_standard/prebuilts/librarys/netd:libnet_manager_native", + "//foundation/communication/netmanager_standard/services/netconnmanager:net_conn_manager", + "//foundation/communication/netmanager_standard/services/dnsresolvermanager:dns_resolver_manager", + "//foundation/communication/netmanager_standard/services/netpolicymanager:net_policy_manager", + "//foundation/communication/netmanager_standard/services/ethernetmanager:ethernet_manager", + "//foundation/communication/netmanager_standard/interfaces/innerkits/native/netconnmanager:net_conn_manager_if", + "//foundation/communication/netmanager_standard/interfaces/innerkits/native/dnsresolvermanager:dns_resolver_manager_if", + "//foundation/communication/netmanager_standard/interfaces/innerkits/native/netpolicymanager:net_policy_manager_if", + "//foundation/communication/netmanager_standard/interfaces/innerkits/native/ethernetmanager:ethernet_manager_if", + "//foundation/communication/netmanager_standard/utils:net_manager_common", + "//foundation/communication/netmanager_standard/services/etc/init:netmanager_base.rc", + "//foundation/communication/netmanager_standard/services/etc/init:netd.rc", + "//foundation/communication/netmanager_standard/sa_profile:net_manager_profile", + "//foundation/communication/netmanager_standard/frameworks/js/netpolicy:netpolicy", + "//foundation/communication/netmanager_standard/frameworks/js/ethernet:ethernet", + "//foundation/communication/netmanager_standard/frameworks/js/dnsresolver:dnsresolver" + ], + "inner_kits": [ + { + "type": "so", + "name": "//foundation/communication/netmanager_standard/interfaces/innerkits/native/netconnmanager:net_conn_manager_if", + "header": { + "header_files": [ + "inet_addr.h", + "net_conn_client.h", + "net_link_info.h", + "net_supplier_info.h", + "net_conn_callback_info.h", + "net_specifier.h", + "route.h" + ], + "header_base": "//foundation/communication/netmanager_standard/interfaces/innerkits/native/netconnmanager/include" + } + }, + { + "type": "so", + "name": "//foundation/communication/netmanager_standard/interfaces/innerkits/native/netpolicymanager:net_policy_manager_if", + "header": { + "header_files": [ + "net_policy_client.h" + ], + "header_base": "//foundation/communication/netmanager_standard/interfaces/innerkits/native/netpolicymanager/include" + } + } + ], + "test_list": [ + "//foundation/communication/netmanager_standard/services/netconnmanager/test:unittest", + "//foundation/communication/netmanager_standard/services/netpolicymanager/test:unittest" + ] + } + } +} diff --git a/prebuilts/librarys/netd/BUILD.gn b/prebuilts/librarys/netd/BUILD.gn new file mode 100755 index 0000000..e994a13 --- /dev/null +++ b/prebuilts/librarys/netd/BUILD.gn @@ -0,0 +1,36 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +config("netd_public_config") { + include_dirs = [ + "$NETMANAGER_PREBUILTS_DIR/librarys/netd/include/common/include", + "$NETMANAGER_PREBUILTS_DIR/librarys/netd/include/net_mgr_native/include", + ] + + libs = [ "$NETMANAGER_PREBUILTS_DIR/librarys/netd/${target_cpu}/libnet_manager_native.z.so" ] +} + +ohos_prebuilt_shared_library("libnet_manager_native") { + source = "$NETMANAGER_PREBUILTS_DIR/librarys/netd/${target_cpu}/libnet_manager_native.z.so" + + public_configs = [ ":netd_public_config" ] + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/prebuilts/librarys/netd/arm/libnet_manager_native.z.so b/prebuilts/librarys/netd/arm/libnet_manager_native.z.so new file mode 100755 index 0000000..33a0bc7 Binary files /dev/null and b/prebuilts/librarys/netd/arm/libnet_manager_native.z.so differ diff --git a/prebuilts/librarys/netd/arm64/libnet_manager_native.z.so b/prebuilts/librarys/netd/arm64/libnet_manager_native.z.so new file mode 100755 index 0000000..c251c53 Binary files /dev/null and b/prebuilts/librarys/netd/arm64/libnet_manager_native.z.so differ diff --git a/prebuilts/librarys/netd/include/common/include/blocking_queue.h b/prebuilts/librarys/netd/include/common/include/blocking_queue.h new file mode 100755 index 0000000..8f8d6b1 --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/blocking_queue.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_BLOCKING_QUEUE_H__ +#define INCLUDE_BLOCKING_QUEUE_H__ + +#include +#include +#include +namespace OHOS { +namespace nmd { +template +class blocking_queue { +public: + explicit blocking_queue(unsigned int capacity) : start_(0), end_(0), capacity_(capacity), vt_(capacity + 1) {}; + ~blocking_queue() {}; + + bool isEmpty() + { + return this->end_ == this->start_; + } + + bool isFull() + { + return (this->start_ + this->capacity_ - this->end_) % (this->capacity_ + 1) == 0; + } + + void push(const T &e) + { + std::unique_lock lock(this->mutex_); + while (this->isFull()) { + this->notFull_.wait(lock); + } + + this->vt_[this->end_++] = e; + this->end_ %= (this->capacity_ + 1); + this->notEmpty_.notify_one(); + } + + T pop() + { + std::unique_lock lock(this->mutex_); + while (this->isEmpty()) { + this->notEmpty_.wait(lock); + } + + auto res = this->vt_[this->start_++]; + this->start_ %= (this->capacity_ + 1); + this->notFull_.notify_one(); + return res; + } + +private: + std::mutex mutex_; + std::condition_variable notFull_; + std::condition_variable notEmpty_; + unsigned int start_; + unsigned int end_; + unsigned int capacity_; + std::vector vt_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_BLOCKING_QUEUE_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/job.h b/prebuilts/librarys/netd/include/common/include/job.h new file mode 100755 index 0000000..e7123d5 --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/job.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_JOB_H__ +#define INCLUDE_JOB_H__ + +#include +#include "server_socket.h" +namespace OHOS { +namespace nmd { +class job { +public: + job(const int fd, const uint8_t *msg, const size_t msgLen, + const std::shared_ptr serverSocket) + : fd_(fd), msg_(msg, msg + msgLen), serverSocket_(serverSocket) + {} + virtual ~job() = default; + virtual void run() = 0; + +protected: + int fd_; + std::vector msg_; + std::shared_ptr serverSocket_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_JOB_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/net_utils.h b/prebuilts/librarys/netd/include/common/include/net_utils.h new file mode 100755 index 0000000..4de8fa8 --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/net_utils.h @@ -0,0 +1,539 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NET_UTILS_H__ +#define INCLUDE_NET_UTILS_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "warning_disable.h" +namespace OHOS { +namespace nmd { +namespace common { +namespace net_utils { +enum protocol : uint8_t { + PROTO_UNKNOWN = 0, + PROTO_TCP = 6, + PROTO_UDP = 17, +}; +// See also NetworkConstants.java in frameworks/base. +constexpr int IPV4_ADDR_LEN = 4; +constexpr int IPV4_ADDR_BITS = 32; +constexpr int IPV6_ADDR_LEN = 16; +constexpr int IPV6_ADDR_BITS = 128; + +// Referred from SHA256_DIGEST_LENGTH in boringssl +constexpr size_t SHA256_SIZE = 32; + +struct compact_ipdata { + uint8_t family {AF_UNSPEC}; + uint8_t cidrlen {0U}; // written and read in host-byte order + in_port_t port {0U}; // written and read in host-byte order + uint32_t scope_id {0U}; + + DISABLE_WARNING_PUSH + DISABLE_WARNING_C99_EXTENSIONS + union { + in_addr v4; + in6_addr v6; + } ip {.v6 = IN6ADDR_ANY_INIT}; // written and read in network-byte order + + DISABLE_WARNING_POP + // Classes that use compact_ipdata and this method should be sure to clear + // (i.e. zero or make uniform) any fields not relevant to the class. + friend bool operator==(const compact_ipdata &a, const compact_ipdata &b) + { + if ((a.family != b.family) || (a.cidrlen != b.cidrlen) || (a.port != b.port) || (a.scope_id != b.scope_id)) { + return false; + } + switch (a.family) { + case AF_UNSPEC: + // After the above checks, two AF_UNSPEC objects can be + // considered equal, for convenience. + return true; + case AF_INET: { + const in_addr v4a = a.ip.v4; + const in_addr v4b = b.ip.v4; + return (v4a.s_addr == v4b.s_addr); + } + case AF_INET6: { + const in6_addr v6a = a.ip.v6; + const in6_addr v6b = b.ip.v6; + return IN6_ARE_ADDR_EQUAL(&v6a, &v6b); + } + default: + break; + } + return false; + } + + // Classes that use compact_ipdata and this method should be sure to clear + // (i.e. zero or make uniform) any fields not relevant to the class. + friend bool operator!=(const compact_ipdata &a, const compact_ipdata &b) + { + return !(a == b); + } + + // Classes that use compact_ipdata and this method should be sure to clear + // (i.e. zero or make uniform) any fields not relevant to the class. + friend bool operator<(const compact_ipdata &a, const compact_ipdata &b) + { + if (a.family != b.family) + return (a.family < b.family); + switch (a.family) { + case AF_INET: { + const in_addr v4a = a.ip.v4; + const in_addr v4b = b.ip.v4; + if (v4a.s_addr != v4b.s_addr) + return (ntohl(v4a.s_addr) < ntohl(v4b.s_addr)); + break; + } + case AF_INET6: { + const in6_addr v6a = a.ip.v6; + const in6_addr v6b = b.ip.v6; + const int cmp = std::memcmp(v6a.s6_addr, v6b.s6_addr, IPV6_ADDR_LEN); + if (cmp != 0) + return cmp < 0; + break; + } + default: + break; + } + if (a.cidrlen != b.cidrlen) + return (a.cidrlen < b.cidrlen); + if (a.port != b.port) + return (a.port < b.port); + return (a.scope_id < b.scope_id); + } +}; + +static_assert(AF_UNSPEC <= std::numeric_limits::max(), "AF_UNSPEC value too large"); +static_assert(AF_INET <= std::numeric_limits::max(), "AF_INET value too large"); +static_assert(AF_INET6 <= std::numeric_limits::max(), "AF_INET6 value too large"); +static_assert(sizeof(compact_ipdata) == 24U, "compact_ipdata unexpectedly large"); + +struct addrinfo_deleter { + void operator()(struct addrinfo *p) const + { + if (p != nullptr) { + freeaddrinfo(p); + } + } +}; + +typedef std::unique_ptr ScopedAddrinfo; + +inline bool usesScopedIds(const in6_addr &ipv6) +{ + return (IN6_IS_ADDR_LINKLOCAL(&ipv6) || IN6_IS_ADDR_MC_LINKLOCAL(&ipv6)); +} + +class ip_prefix; +class ip_sock_addr; + +class ip_address { +public: + static bool forString(const std::string &repr, ip_address *ip); + static ip_address forString(const std::string &repr) + { + ip_address ip; + if (!forString(repr, &ip)) + return ip_address(); + return ip; + } + + ip_address() = default; + ip_address(const ip_address &) = default; + ip_address(ip_address &&) = default; + + DISABLE_WARNING_PUSH + DISABLE_WARNING_C99_EXTENSIONS + + explicit ip_address(const in_addr &ipv4); + explicit ip_address(const in6_addr &ipv6); + ip_address(const in6_addr &ipv6, uint32_t scope_id); + + DISABLE_WARNING_POP + + ip_address(const ip_address &ip, uint32_t scope_id) : ip_address(ip) + { + mData.scope_id = (family() == AF_INET6 && usesScopedIds(mData.ip.v6)) ? scope_id : 0U; + } + + ip_address &operator=(const ip_address &) = default; + ip_address &operator=(ip_address &&) = default; + + constexpr sa_family_t family() const noexcept + { + return mData.family; + } + constexpr uint32_t scope_id() const noexcept + { + return mData.scope_id; + } + + std::string toString() const noexcept; + + friend std::ostream &operator<<(std::ostream &os, const ip_address &ip) + { + os << ip.toString(); + return os; + } + friend bool operator==(const ip_address &a, const ip_address &b) + { + return (a.mData == b.mData); + } + friend bool operator!=(const ip_address &a, const ip_address &b) + { + return (a.mData != b.mData); + } + friend bool operator<(const ip_address &a, const ip_address &b) + { + return (a.mData < b.mData); + } + friend bool operator>(const ip_address &a, const ip_address &b) + { + return (b.mData < a.mData); + } + friend bool operator<=(const ip_address &a, const ip_address &b) + { + return (a < b) || (a == b); + } + friend bool operator>=(const ip_address &a, const ip_address &b) + { + return (b < a) || (a == b); + } + +private: + friend class ip_prefix; + friend class ip_sock_addr; + + explicit ip_address(const compact_ipdata &ipdata) : mData(ipdata) + { + mData.port = 0U; + switch (mData.family) { + case AF_INET: + mData.cidrlen = IPV4_ADDR_BITS; + mData.scope_id = 0U; + break; + case AF_INET6: + mData.cidrlen = IPV6_ADDR_BITS; + if (usesScopedIds(ipdata.ip.v6)) + mData.scope_id = ipdata.scope_id; + break; + default: + mData.cidrlen = 0U; + mData.scope_id = 0U; + break; + } + } + + compact_ipdata mData {}; +}; + +class ip_prefix { +public: + static bool forString(const std::string &repr, ip_prefix *prefix); + static ip_prefix forString(const std::string &repr) + { + ip_prefix prefix; + if (!forString(repr, &prefix)) + return ip_prefix(); + return prefix; + } + + ip_prefix() = default; + ip_prefix(const ip_prefix &) = default; + ip_prefix(ip_prefix &&) = default; + + explicit ip_prefix(const ip_address &ip) : mData(ip.mData) {} + + // Truncate the IP address |ip| at length |length|. Lengths greater than + // the address-family-relevant maximum, along with negative values, are + // interpreted as if the address-family-relevant maximum had been given. + ip_prefix(const ip_address &ip, size_t length); + + ip_prefix &operator=(const ip_prefix &) = default; + ip_prefix &operator=(ip_prefix &&) = default; + + constexpr sa_family_t family() const noexcept + { + return mData.family; + } + ip_address ip() const noexcept + { + return ip_address(mData); + } + in_addr addr4() const noexcept + { + return mData.ip.v4; + } + in6_addr addr6() const noexcept + { + return mData.ip.v6; + } + constexpr int length() const noexcept + { + return mData.cidrlen; + } + + bool isUninitialized() const noexcept; + std::string toString() const noexcept; + + friend std::ostream &operator<<(std::ostream &os, const ip_prefix &prefix) + { + os << prefix.toString(); + return os; + } + friend bool operator==(const ip_prefix &a, const ip_prefix &b) + { + return (a.mData == b.mData); + } + friend bool operator!=(const ip_prefix &a, const ip_prefix &b) + { + return (a.mData != b.mData); + } + friend bool operator<(const ip_prefix &a, const ip_prefix &b) + { + return (a.mData < b.mData); + } + friend bool operator>(const ip_prefix &a, const ip_prefix &b) + { + return (b.mData < a.mData); + } + friend bool operator<=(const ip_prefix &a, const ip_prefix &b) + { + return (a < b) || (a == b); + } + friend bool operator>=(const ip_prefix &a, const ip_prefix &b) + { + return (b < a) || (a == b); + } + +private: + compact_ipdata mData {}; +}; + +// An Internet socket address. +// +// Cannot represent other types of socket addresses (e.g. UNIX socket address, et cetera). +class ip_sock_addr { +public: + static ip_sock_addr toIPSockAddr(const std::string &repr, in_port_t port) + { + return ip_sock_addr(ip_address::forString(repr), port); + } + static ip_sock_addr toIPSockAddr(const sockaddr &sa) + { + switch (sa.sa_family) { + case AF_INET: + return ip_sock_addr(*reinterpret_cast(&sa)); + case AF_INET6: + return ip_sock_addr(*reinterpret_cast(&sa)); + default: + return ip_sock_addr(); + } + } + static ip_sock_addr toIPSockAddr(const sockaddr_storage &ss) + { + return toIPSockAddr(*reinterpret_cast(&ss)); + } + + ip_sock_addr() = default; + ip_sock_addr(const ip_sock_addr &) = default; + ip_sock_addr(ip_sock_addr &&) = default; + + explicit ip_sock_addr(const ip_address &ip) : mData(ip.mData) {} + ip_sock_addr(const ip_address &ip, in_port_t port) : mData(ip.mData) + { + mData.port = port; + } + explicit ip_sock_addr(const sockaddr_in &ipv4sa) + : ip_sock_addr(ip_address(ipv4sa.sin_addr), ntohs(ipv4sa.sin_port)) + {} + explicit ip_sock_addr(const sockaddr_in6 &ipv6sa) + : ip_sock_addr(ip_address(ipv6sa.sin6_addr, ipv6sa.sin6_scope_id), ntohs(ipv6sa.sin6_port)) + {} + + ip_sock_addr &operator=(const ip_sock_addr &) = default; + ip_sock_addr &operator=(ip_sock_addr &&) = default; + + constexpr sa_family_t family() const noexcept + { + return mData.family; + } + ip_address ip() const noexcept + { + return ip_address(mData); + } + constexpr in_port_t port() const noexcept + { + return mData.port; + } + + // Implicit conversion to sockaddr_storage. + operator sockaddr_storage() const noexcept + { + sockaddr_storage ss; + ss.ss_family = mData.family; + switch (mData.family) { + case AF_INET: + reinterpret_cast(&ss)->sin_addr = mData.ip.v4; + reinterpret_cast(&ss)->sin_port = htons(mData.port); + break; + case AF_INET6: + reinterpret_cast(&ss)->sin6_addr = mData.ip.v6; + reinterpret_cast(&ss)->sin6_port = htons(mData.port); + reinterpret_cast(&ss)->sin6_scope_id = mData.scope_id; + break; + default: + break; + } + return ss; + } + + std::string toString() const noexcept; + + friend std::ostream &operator<<(std::ostream &os, const ip_sock_addr &prefix) + { + os << prefix.toString(); + return os; + } + friend bool operator==(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a.mData == b.mData); + } + friend bool operator!=(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a.mData != b.mData); + } + friend bool operator<(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a.mData < b.mData); + } + friend bool operator>(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (b.mData < a.mData); + } + friend bool operator<=(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (a < b) || (a == b); + } + friend bool operator>=(const ip_sock_addr &a, const ip_sock_addr &b) + { + return (b < a) || (a == b); + } + +private: + compact_ipdata mData {}; +}; + +class sock_addr_utils final { +public: + static socklen_t sockaddrSize(const sockaddr *sa) + { + if (sa == nullptr) { + return 0; + } + + switch (sa->sa_family) { + case AF_INET: + return sizeof(sockaddr_in); + case AF_INET6: + return sizeof(sockaddr_in6); + default: + return 0; + } + } + +public: + sock_addr_utils() = default; /* args */ + ~sock_addr_utils() = default; +}; + +class fd_wrapper final { +public: + fd_wrapper() = default; + explicit fd_wrapper(const int fd) + { + reset(fd); + }; + fd_wrapper(const fd_wrapper &) = delete; + void operator=(const fd_wrapper &) = delete; + ~fd_wrapper() + { + reset(); + } + + int getFd() const + { + return fd_; + } + + operator int() const + { + return getFd(); + } + bool operator>=(int rhs) const + { + return getFd() >= rhs; + } + bool operator<(int rhs) const + { + return getFd() < rhs; + } + bool operator==(int rhs) const + { + return getFd() == rhs; + } + bool operator!=(int rhs) const + { + return getFd() != rhs; + } + bool operator==(const fd_wrapper &rhs) const + { + return getFd() == rhs.getFd(); + } + bool operator!=(const fd_wrapper &rhs) const + { + return getFd() != rhs.getFd(); + } + +public: + void reset(int newFd = -1) + { + if (fd_ != -1) { + close(fd_); + } + fd_ = newFd; + } + +private: + int fd_ = -1; +}; +using socket_fd = fd_wrapper; +} // namespace net_utils +} // namespace common +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NET_UTILS_H__ diff --git a/prebuilts/librarys/netd/include/common/include/server_socket.h b/prebuilts/librarys/netd/include/common/include/server_socket.h new file mode 100755 index 0000000..2643a3b --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/server_socket.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETD_COMMON_SERVER_SOCKET_H__ +#define NETD_COMMON_SERVER_SOCKET_H__ + +#include "socket_base.h" +namespace OHOS { +namespace nmd { +namespace common { +class server_socket : public socket_base { +public: + server_socket(); + ~server_socket(); + + int bindPort(uint16_t port); + int bindFile(const char *filePath, const char *name); + +private: + struct sockaddr addr_ {}; +}; +} // namespace common +} // namespace nmd +} // namespace OHOS +#endif // !NETD_COMMON_SERVER_SOCKET_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/server_template.h b/prebuilts/librarys/netd/include/common/include/server_template.h new file mode 100755 index 0000000..c29ba9d --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/server_template.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_SERVER_TEMPLATE_H__ +#define INCLUDE_SERVER_TEMPLATE_H__ +#include +#include +#include "server_socket.h" +#include "thread_pool.h" +namespace OHOS { +namespace nmd { +namespace common { +class server_template { + const char *const SOCKET_FILE_PATH = "/dev/socket"; + +public: + void start(); + void stop(); + void handler(int socketFd, const uint8_t *msg, const size_t msgLen); + +public: + explicit server_template(const char *socketName, const char *serverName) + : socketName_(socketName), serverName_(serverName), server_(std::make_shared()), + pool_(std::make_shared(16, 256)), job_(nullptr) + {} + virtual ~server_template() = default; + +protected: + virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) = 0; + +protected: + std::string socketName_; + std::string serverName_; + std::shared_ptr server_; + std::shared_ptr pool_; + nmd::job *job_; + bool mRunning = false; +}; +} // namespace common +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_SERVER_TEMPLATE_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/socket_base.h b/prebuilts/librarys/netd/include/common/include/socket_base.h new file mode 100755 index 0000000..6ee2579 --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/socket_base.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETD_SOCKET_BASE_H__ +#define NETD_SOCKET_BASE_H__ + +#include +#include +#include +#include +#include "netnative_log_wrapper.h" + +namespace OHOS { +namespace nmd { +namespace common { +typedef struct end_point { + int port; +} end_point; +class socket_base { +public: + socket_base(); + virtual ~socket_base(); + + int createInet(); + int createUnix(); + int listenSocket(); + int acceptSocket(); + int connectSocket(struct sockaddr_in serverAddr); + ssize_t sendSocket(int socketFd, const char *buffer); + ssize_t sendSocket(const char *buffer); + virtual ssize_t sendMsg(const int socketFd, const msghdr &msg); + char *receiveSocket(char *buffer); + + template + void setRecevedHandler(R (*)(Params...)) + {} + + template + void setRecevedHandler(R (C::*func)(Params...), C *instance) + { + this->handler_ = + std::bind(func, instance, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); + } + + int getSocketFileDescriptor() + { + return this->socketFd_; + } + +protected: + int socketFd_; + int epollFd_ = 0; + int eventCnt_ = 0; + struct epoll_event *epollEvents_; + struct epoll_event event_ {}; + std::function handler_; + +private: + int create(int domain, int protocol); +}; +} // namespace common +} // namespace nmd +} // namespace OHOS +#endif // !NETD_SOCKET_BASE_H__ diff --git a/prebuilts/librarys/netd/include/common/include/thread_pool.h b/prebuilts/librarys/netd/include/common/include/thread_pool.h new file mode 100755 index 0000000..aed9c9b --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/thread_pool.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_THREAD_POOL_H__ +#define INCLUDE_THREAD_POOL_H__ + +#include +#include +#include +#include +#include +#include +#include +#include "blocking_queue.h" +#include "job.h" + +namespace OHOS { +namespace nmd { +class thread_pool { +public: + thread_pool(unsigned int threadNums, unsigned int queueSize); + + void execute(nmd::job *job); + + ~thread_pool(); + +private: + unsigned int threadNums_; + unsigned int queueSize_; + + bool running_ = false; + + std::vector workers_; + nmd::blocking_queue *workQueue_; + + std::mutex mutex_; + std::condition_variable cond_; + + void threadLoop(); + + nmd::job *takeJobFromQueue(); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_THREAD_POOL_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/common/include/warning_disable.h b/prebuilts/librarys/netd/include/common/include/warning_disable.h new file mode 100755 index 0000000..1ae027e --- /dev/null +++ b/prebuilts/librarys/netd/include/common/include/warning_disable.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_WARNING_DISABLE_H__ +#define INCLUDE_WARNING_DISABLE_H__ + +#if defined(__GNUC__) || defined(__clang__) +#define DO_PRAGMA(X) _Pragma(#X) +#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) +#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) +#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored warningName) + +#define DISABLE_WARNING_OLD_STYLE_CAST DISABLE_WARNING("-Wold-style-cast") +#define DISABLE_WARNING_MISSING_FIELD_INITIALIZERS DISABLE_WARNING("-Wmissing-field-initializers") +#define DISABLE_WARNING_SIGN_CONVERSION DISABLE_WARNING("-Wsign-conversion") +#define DISABLE_WARNING_IMPLICIT_INT_CONVERSION DISABLE_WARNING("-Wimplicit-int-conversion") +#define DISABLE_WARNING_SIGN_COMPARE DISABLE_WARNING("-Wsign-compare") +#define DISABLE_WARNING_SHORTEN_64_TO_32 DISABLE_WARNING("-Wshorten-64-to-32") +#define DISABLE_WARNING_CAST_ALIGN DISABLE_WARNING("-Wcast-align") +#define DISABLE_WARNING_UNUSED_PARAMETER DISABLE_WARNING("-Wunused-parameter") +#define DISABLE_WARNING_UNUSED_VARIABLE DISABLE_WARNING("-Wunused-variable") +#define DISABLE_WARNING_C99_EXTENSIONS DISABLE_WARNING("-Wc99-extensions") +// other warnings you want to deactivate... + +#else +#define DISABLE_WARNING_PUSH +#define DISABLE_WARNING_POP +#define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER +#define DISABLE_WARNING_UNREFERENCED_FUNCTION +// other warnings you want to deactivate... + +#endif + +#endif // !INCLUDE_WARNING_DISABLE_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv.h b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv.h new file mode 100755 index 0000000..a3eb1c2 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv.h @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_DNSRESOLV_H__ +#define INCLUDE_DNSRESOLV_H__ +#include +#include +#include +#include "net_utils.h" +#include "warning_disable.h" + +#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST | AI_NUMERICSERV | AI_ADDRCONFIG) + +namespace OHOS { +namespace nmd { +DISABLE_WARNING_PUSH +DISABLE_WARNING_OLD_STYLE_CAST +const uid_t NET_CONTEXT_INVALID_UID = ((uid_t)-1); +DISABLE_WARNING_POP + +const uint8_t RES_DEFAULT_TIMEOUT = 5; // default dns request timeout + +const int32_t ANY_SOCK_TYPE = 0; + +const pid_t NET_CONTEXT_INVALID_PID = -1; + +const uint8_t PTON_MAX = 16; +constexpr int MAX_PACKET = 8 * 1024; + +const uint8_t RCODE_TIMEOUT = 255; +const uint8_t RCODE_INTERNAL_ERROR = 254; + +const uint8_t MAXNS = 4; // max # name servers we'll track + +const long BILLION = 1000000000; + +const uint16_t DNS_REQ_PORT = 53; +const char *const DNS_REQ_PORT_STR = "53"; + +const uint8_t ANYSIZE_ARRAY = 1; + +// MARK_UNSET represents the default (i.e. unset) value for a socket mark. +const uint32_t NETID_UNSET = 0u; +const uint32_t MARK_UNSET = 0u; + +const uint32_t MAX_NAME_LEN = 64; +const uint32_t MAX_NAME_LIST_LEN = 1024; + +struct netd_net_context { + uint16_t appNetId; + uint32_t appMark; + uint16_t dnsNetId; + uint32_t dnsMark; + uid_t uid = NET_CONTEXT_INVALID_UID; + uint32_t flags; + pid_t pid = NET_CONTEXT_INVALID_PID; +}; + +union sockaddr_union { + struct sockaddr sa; + struct sockaddr_in sin; + struct sockaddr_in6 sin6; +}; + +struct res_target { + struct res_target *next; + const char *name; // domain name + int qclass; + int qtype; // class and type of query + std::vector answer = std::vector(MAX_PACKET, 0); // buffer to put answer + size_t n = 0; // result length +}; + +struct dns_res_state { + void init(const netd_net_context *netcontext) + { + if (netcontext == nullptr) { + return; + } + netid = netcontext->dnsNetId; + ndots = 1; + mark = netcontext->dnsMark; + + for (auto &sock : nssocks) { + sock.reset(); + } + } + + void closeSockets() + { + tcpNsSock.reset(); + isTcp = false; + + for (auto &sock : nssocks) { + sock.reset(); + } + } + + size_t nameserverCount() + { + return nsaddrs.size(); + } + + uint16_t netid; // NetId: cache key and socket mark + uid_t uid; // uid of the app that sent the DNS lookup + pid_t pid; // pid of the app that sent the DNS lookup + uint16_t id; // current message id + std::vector searchDomains {}; // domains to search + std::vector nsaddrs; + nmd::common::net_utils::socket_fd nssocks[MAXNS]; // UDP sockets to nameservers + unsigned ndots : 4; // threshold for initial abs. query + unsigned mark; // If non-0 SET_MARK to mark on all request sockets + nmd::common::net_utils::socket_fd tcpNsSock; // TCP socket + bool isTcp = false; +}; + +// Per-netid configuration parameters passed from netd to the resolver +struct dns_res_params { + uint16_t baseTimeoutMsec; // base query retry timeout (if 0, use RES_TIMEOUT) + uint8_t retryCount = 1; // number of retries + void operator=(const dns_res_params ¶m) + { + baseTimeoutMsec = param.baseTimeoutMsec; + retryCount = param.retryCount; + } +}; + +enum dns_request_send_flag : uint32_t { + // Send a single request to a single resolver and fail on timeout or network errors + NETD_DNS_RESOLV_NO_RETRY = 1 << 0, + + // Don't lookup this request in the cache, and don't cache the result of the lookup. + NETD_DNS_RESOLV_NO_CACHE_STORE = 1 << 1, + + // Don't lookup the request in cache. + NETD_DNS_RESOLV_NO_CACHE_LOOKUP = 1 << 2, +}; + +struct dnsresolver_params { + uint16_t netId = 0; + uint16_t baseTimeoutMsec = 0; + uint8_t retryCount = 0; + std::vector servers; + std::vector domains; +}; + +typedef struct alignas(8) dnsresolver_request_cmd { + enum cmd_id { + CREATE_NETWORK_CACHE, + SET_RESOLVER_CONFIG, + DESOTRY_NETWORK_CACHE, + GET_ADDR_INFO, + GET_ADDR_INFO_PROXY, + } cmdID; + uint16_t netid; + union { + struct dnsresolv_req_param { + addrinfo hints; + uid_t uid; + char hostName[MAX_NAME_LEN]; + char serverName[MAX_NAME_LEN]; + } reqParam; + + struct dnsresolv_cfg_param { + uint16_t baseTimeoutMsec; + uint8_t retryCount; + uint8_t serverCount; + uint8_t domainCount; + char servers[MAX_NAME_LIST_LEN]; + char domains[MAX_NAME_LIST_LEN]; + } cfgParam; + } u; +} dnsresolver_request_cmd_t; + +#define cmd_hints u.reqParam.hints +#define cmd_uid u.reqParam.uid +#define cmd_hostName u.reqParam.hostName +#define cmd_serverName u.reqParam.serverName + +#define cmd_baseTimeoutMsec u.cfgParam.baseTimeoutMsec +#define cmd_retryCount u.cfgParam.retryCount +#define cmd_serverCount u.cfgParam.serverCount +#define cmd_domainCount u.cfgParam.domainCount +#define cmd_servers u.cfgParam.servers +#define cmd_domains u.cfgParam.domains + +typedef struct alignas(8) dnsresolver_response_cmd { + enum cmd_id { + QUERY_STATE_OK, + QUERY_STATE_FAIL, + QUERY_SUCCESS_WITH_RESULT, + QUERY_STATE_BUTT + } cmdID = QUERY_STATE_BUTT; + int result = 0; + size_t resSize = 0; + uint8_t resData[ANYSIZE_ARRAY]; +} dnsresolver_response_cmd_t, *p_dnsresolver_response_cmd; + +typedef void (*get_network_context_callback)(uint16_t netid, uid_t uid, netd_net_context &netcontext); +struct dnsresolv_callbacks { + dnsresolv_callbacks() : getNetworkContext(nullptr) {} + get_network_context_callback getNetworkContext; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_DNSRESOLV_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_controller.h new file mode 100755 index 0000000..627fbe3 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_controller.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_DNSRESOLV_CONTROLLER_H__ +#define INCLUDE_DNSRESOLV_CONTROLLER_H__ + +#include +#include +#include +#include +namespace OHOS { +namespace nmd { +struct dnsresolver_params; +struct netd_net_context; +class dnsresolv_controller { +public: + int getResolverInfo(const uint16_t netid, std::vector &servers, std::vector &domains, + struct dns_res_params ¶m); + int setResolverConfig(const dnsresolver_params &resolvParams); + int createNetworkCache(const uint16_t netid); + int destoryNetworkCache(const uint16_t netid); + int flushNetworkCache(const uint16_t netid); + +public: + static int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, + struct addrinfo **res, const uint16_t netid); + static int getaddrinfoForNet(const char *hostname, const char *servname, const struct addrinfo *hints, + uint16_t netid, unsigned mark, struct addrinfo **res); + static int getaddrinfoFornetContext(const char *hostname, const char *servname, const addrinfo *hints, + const netd_net_context &netcontext, addrinfo **res); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_DNSRESOLV_CONTROLLER_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_service.h b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_service.h new file mode 100755 index 0000000..defc48e --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/dnsresolv_service.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_DNSRESOLV_SERVICE_H__ +#define INCLUDE_DNSRESOLV_SERVICE_H__ +#include +#include +#include +#include "dnsresolv.h" +#include "dnsresolv_controller.h" +#include "job.h" +#include "server_template.h" +namespace OHOS { +namespace nmd { +const char *const DNS_RESOLV_SERVICE_SOCK_NAME = "dnsresolvproxy.sock"; +const char *const DNS_RESOLV_SERVICE_NAME = "DNSResolverService"; +class dnsresolv_job : public job { +public: + dnsresolv_job(const int fd, const uint8_t *msg, const size_t msgLen, + const std::shared_ptr serverSocket) + : job(fd, msg, msgLen, serverSocket) + {} + ~dnsresolv_job() = default; + virtual void run() override; + void setupCallbacks(const dnsresolv_callbacks &callbacks) + { + dnsresolvCallbacks_ = callbacks; + } +private: + void doCreateNetworkCache(const dnsresolver_request_cmd *command); + void doSetResolverConfig(const dnsresolver_request_cmd *command); + void doDestroyNetworkCache(const dnsresolver_request_cmd *command); + void doGetAddrInfo(const dnsresolver_request_cmd *command); + void doGetAddrInfoProxy(const dnsresolver_request_cmd *command); + void responseOk(); + void responseOk(const struct addrinfo *res); + void responseFailed(const int ret); + size_t getNameList(const char *buffer, const size_t bufferSize, std::vector &namelist); + ssize_t sendResponseResult(dnsresolver_response_cmd &cmd); +private: + dnsresolv_callbacks dnsresolvCallbacks_; + dnsresolv_controller dnsresolvCtrl_; +}; + +class dnsresolv_service : public common::server_template { +public: + int getResolverInfo(const uint16_t netid, std::vector &servers, std::vector &domains, + dns_res_params ¶m); + int setResolverConfig(const dnsresolver_params &resolvParams); + int createNetworkCache(const uint16_t netid); + int flushNetworkCache(const uint16_t netid); + int destoryNetworkCache(const uint16_t netid); + int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, + struct addrinfo **res, const uint16_t netid); +public: + dnsresolv_service() : common::server_template(DNS_RESOLV_SERVICE_SOCK_NAME, DNS_RESOLV_SERVICE_NAME) {} + ~dnsresolv_service() = default; + bool init(const dnsresolv_callbacks &callbacks); +private: + virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) override; +private: + dnsresolv_controller dnsresolvCtrl_; + dnsresolv_callbacks dnsresolvCallbacks_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_DNSRESOLV_SERVICE_H_ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/event_reporter.h b/prebuilts/librarys/netd/include/net_mgr_native/include/event_reporter.h new file mode 100755 index 0000000..90dc732 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/event_reporter.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_EVENT_REPORTER_H__ +#define INCLUDE_EVENT_REPORTER_H__ +#include + +namespace OHOS { +namespace nmd { +typedef struct inetd_unsolicited_event_listener { + void (*onInterfaceAddressUpdated)(const std::string &addr, const std::string &ifName, int flags, int scope); + void (*onInterfaceAddressRemoved)(const std::string &addr, const std::string &ifName, int flags, int scope); + void (*onInterfaceAdded)(const std::string &ifName); + void (*onInterfaceRemoved)(const std::string &ifName); + void (*onInterfaceChanged)(const std::string &ifName, bool up); + void (*onInterfaceLinkStateChanged)(const std::string &ifName, bool up); + void (*onRouteChanged)( + bool updated, const std::string &route, const std::string &gateway, const std::string &ifName); +} inetd_unsolicited_event_listener; + +class event_reporter { +public: + event_reporter() = default; + void registerEventListener(inetd_unsolicited_event_listener &listener); + inetd_unsolicited_event_listener getListener() + { + return this->listener_; + } + ~event_reporter(); + +private: + inetd_unsolicited_event_listener listener_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_EVENT_REPORTER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/fwmark_server.h b/prebuilts/librarys/netd/include/net_mgr_native/include/fwmark_server.h new file mode 100755 index 0000000..7b09044 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/fwmark_server.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __INCLUDE_FWMARK_SERVER_H__ +#define __INCLUDE_FWMARK_SERVER_H__ + +#include +#include "job.h" +#include "server_template.h" +namespace OHOS { +namespace nmd { +const char *const FWMARK_SERVER_SOCK_NAME = "fwmarkd.sock"; +const char *const FWMARK_SERVER_NAME = "FWMarkServer"; + +class fwmark_job : public job { +public: + fwmark_job(const int fd, const uint8_t *msg, const size_t msgLen, + const std::shared_ptr &serverSocket) + : job(fd, msg, msgLen, serverSocket) + {} + ~fwmark_job() = default; + + virtual void run() override; + +private: + void responseOk(); + void responseFailed(); +}; + +class fwmark_server : public common::server_template { +public: + fwmark_server() : common::server_template(FWMARK_SERVER_SOCK_NAME, FWMARK_SERVER_NAME) {} + + virtual ~fwmark_server() = default; + +private: + virtual void initJob(const int socketFd, const uint8_t *msg, const size_t msgLen) override; +}; +} // namespace nmd +} // namespace OHOS +#endif // !__INCLUDE_FWMARK_SERVER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/interface_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/interface_controller.h new file mode 100755 index 0000000..803f959 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/interface_controller.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __INCLUDE_INTERFACE_CONTROLLER_H__ +#define __INCLUDE_INTERFACE_CONTROLLER_H__ +#include +#include +#include + +namespace OHOS { +namespace nmd { +typedef struct interface_configuration_parcel { + std::string ifName; + std::string hwAddr; + std::string ipv4Addr; + int prefixLength; + std::vector flags; + friend std::ostream &operator<<(std::ostream &os, const nmd::interface_configuration_parcel &parcel) + { + os << "ifName: " << parcel.ifName << "\n" + << "hwAddr: " << parcel.hwAddr << "\n" + << "ipv4Addr: " << parcel.ipv4Addr << "\n" + << "prefixLength: " << parcel.prefixLength << "\n" + << "flags: [" + << "\n"; + for (unsigned long i = 0; i < parcel.flags.size(); i++) { + os << " " << parcel.flags[i] << "\n"; + } + os << "] " + << "\n"; + return os; + } +} interface_configuration_parcel; + +class interface_controller { +public: + interface_controller(); + ~interface_controller(); + static int setMtu(const char *interfaceName, const char *mtuValue); + static int getMtu(const char *interfaceName); + static std::vector getInterfaceNames(); + static int clearAddrs(const std::string &ifName); + static int interfaceAddAddress(const std::string &ifName, const std::string &addr, const int prefixLen); + static int interfaceDelAddress(const std::string &ifName, const std::string &addr, const int prefixLen); + static int setParameter( + const char *family, const char *which, const char *ifName, const char *parameter, const char *value); + static int getParameter( + const char *family, const char *which, const char *ifName, const char *parameter, std::string *value); + static interface_configuration_parcel getConfig(const std::string &ifName); + static int setConfig(const nmd::interface_configuration_parcel &cfg); +}; +} // namespace nmd +} // namespace OHOS + +#endif // !__INCLUDE_INTERFACE_CONTROLLER_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/net_manager_native.h b/prebuilts/librarys/netd/include/net_mgr_native/include/net_manager_native.h new file mode 100755 index 0000000..cd8da04 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/net_manager_native.h @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NET_MANAGER_NATIVE_H__ +#define INCLUDE_NET_MANAGER_NATIVE_H__ + +#include +#include +#include +#include +#include +#include +#include +#include "event_reporter.h" + +namespace OHOS { +namespace nmd { +enum set_proc_sys_net { + IPV4 = 4, + IPV6 = 6, + CONF = 1, + NEIGH = 2, +}; +typedef struct route_info_parcel { + std::string destination; + std::string ifName; + std::string nextHop; + int mtu; +} route_info_parcel; + +typedef struct tether_offload_rule_parcel { + int inputInterfaceIndex; + int outputInterfaceIndex; + std::vector destination; + int prefixLength; + std::vector srcL2Address; + std::vector dstL2Address; + int pmtu = 1500; +} tether_offload_rule_parcel; + +typedef struct tether_config_parcel { + bool usingLegacyDnsProxy; + std::vector dhcpRanges; +} tether_config_parcel; + +typedef struct mark_mask_parcel { + int mark; + int mask; +} mark_mask_parcel; +class NetManagerNative { +public: + NetManagerNative(); + ~NetManagerNative(); + + static void getOriginInterfaceIdex(); + static std::vector getCurrentInterfaceIdex(); + static void updateInterfaceIdex(unsigned int infIdex); + + void initChildChains(); + void initUnixSocket(); + void init(); + + int networkCreatePhysical(int netId, int permission); + int networkDestroy(int netId); + int networkAddInterface(int netId, std::string iface); + int networkRemoveInterface(int netId, std::string iface); + void socketDestroy(std::string iface); + void socketDestroy(int netId); + mark_mask_parcel getFwmarkForNetwork(int netId); + int networkAddRoute(int netId, std::string ifName, std::string destination, std::string nextHop); + int networkRemoveRoute(int netId, std::string ifName, std::string destination, std::string nextHop); + int networkGetDefault(); + int networkSetDefault(int netId); + int networkClearDefault(); + int networkSetPermissionForNetwork(int netId, NetworkPermission permission); + std::vector interfaceGetList(); + + int setProcSysNet(int32_t ipversion, int32_t which, const std::string ifname, const std::string parameter, + const std::string value); + int getProcSysNet(int32_t ipversion, int32_t which, const std::string ifname, const std::string parameter, + std::string *value); + + nmd::interface_configuration_parcel interfaceGetConfig(std::string ifName); + void interfaceSetConfig(interface_configuration_parcel cfg); + void interfaceClearAddrs(const std::string ifName); + int interfaceGetMtu(std::string ifName); + int interfaceSetMtu(std::string ifName, int mtuValue); + int interfaceAddAddress(std::string ifName, std::string addrString, int prefixLength); + int interfaceDelAddress(std::string ifName, std::string addrString, int prefixLength); + + void registerUnsolicitedEventListener(inetd_unsolicited_event_listener listener); + int networkAddRouteParcel(int netId, route_info_parcel routeInfo); + int networkRemoveRouteParcel(int netId, route_info_parcel routeInfo); + + long getCellularRxBytes(); + long getCellularTxBytes(); + long getAllRxBytes(); + long getAllTxBytes(); + long getUidTxBytes(int uid); + long getUidRxBytes(int uid); + traffic_stats_parcel interfaceGetStats(std::string interfaceName); + long getIfaceRxBytes(std::string interfaceName); + long getIfaceTxBytes(std::string interfaceName); + long getTetherRxBytes(); + long getTetherTxBytes(); + +private: + std::shared_ptr networkController_; + std::shared_ptr routeController_; + std::shared_ptr interfaceController_; + static std::vector interfaceIdex_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NET_MANAGER_NATIVE_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_event.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_event.h new file mode 100755 index 0000000..c6d2c88 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_event.h @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_EVENT_H__ +#define INCLUDE_NETLINK_EVENT_H__ + +#include +#include +#include +#include +#include +#include +#include +namespace OHOS { +namespace nmd { +enum class Action { + Unknown = 0, + Add, + Remove, + Change, + LinkUp, + LinkDown, + AddressUpdated, + AddressRemoved, + RouteUpdated, + RouteRemoved, + NewRule, + DelRule, +}; +class netlink_event { +public: + netlink_event() = default; + bool parseInterfaceInfoInfoMessage(struct nlmsghdr *hdr); + bool parseInterafaceAddressMessage(struct nlmsghdr *hdr); + bool parseRouteMessage(struct nlmsghdr *hdr); + bool parseRuleMessage(struct nlmsghdr *hdr); + bool parseNetLinkMessage(char *buffer, ssize_t size); + + void setAction(Action action) + { + this->action_ = action; + } + Action getAction() + { + return this->action_; + } + + void addParam(std::string key, std::string value) + { + this->params_.insert(std::pair(key, value)); + } + const char *findParam(const char *key); + const char *rtMessageName(int type); + + ~netlink_event(); + +private: + Action action_; + std::map params_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NETLINK_EVENT_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_handler.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_handler.h new file mode 100755 index 0000000..200a90a --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_handler.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_HANDLER_H__ +#define INCLUDE_NETLINK_HANDLER_H__ +#include +#include "event_reporter.h" +#include "netlink_listener.h" +#include "netlink_event.h" + +namespace OHOS { +namespace nmd { +class netlink_handler : public netlink_listener { +public: + void onEvent(std::shared_ptr evt); + + void notifyInterfaceAdded(const std::string &ifName); + void notifyInterfaceRemoved(const std::string &ifName); + void notifyInterfaceChanged(const std::string &ifName, bool isUp); + void notifyInterfaceLinkChanged(const std::string &ifName, bool isUp); + void notifyAddressUpdated(const std::string &addr, const std::string &ifName, int flags, int scope); + void notifyAddressRemoved(const std::string &addr, const std::string &ifName, int flags, int scope); + void notifyRouteChange( + bool updated, const std::string &route, const std::string &gateway, const std::string &ifName); + + int start(); + void stop(); + + int getSock() + { + return this->socketFd_; + } + + void setEventListener(const std::shared_ptr &reporter) + { + this->reporter_ = reporter; + } + + netlink_handler(int protocol, int pid); + ~netlink_handler(); + +private: + std::shared_ptr reporter_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NETLINK_HANDLER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_listener.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_listener.h new file mode 100755 index 0000000..1b60816 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_listener.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_LISTENER_H__ +#define INCLUDE_NETLINK_LISTENER_H__ + +#include +#include "netlink_socket.h" +#include "netlink_event.h" + +namespace OHOS { +namespace nmd { +class netlink_listener : public netlink_socket { +public: + netlink_listener(int protocol, int pid); + ~netlink_listener(); + + void setOnEventHandler(const std::function)> &handler); + int listen(); + + void stopListen(); + bool getNetlinkListenerState(); + +private: + bool running_ = false; + std::function)> onEventHandler_; + + void onDataAvaliable(int fd, char *buf, ssize_t size); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NETLINK_LISTENER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_manager.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_manager.h new file mode 100755 index 0000000..97005a0 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_manager.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_MANAGER_H__ +#define INCLUDE_NETLINK_MANAGER_H__ + +#include +#include "event_reporter.h" +#include "netlink_handler.h" +namespace OHOS { +namespace nmd { +namespace listeners { +void defaultOnInterfaceAddressUpdated(const std::string &, const std::string &, int, int); +void defaultOnInterfaceAddressRemoved(const std::string &, const std::string &, int, int); +void defaultOnInterfaceAdded(const std::string &); +void defaultOnInterfaceRemoved(const std::string &); +void defaultOnInterfaceChanged(const std::string &, bool); +void defaultOnInterfaceLinkStateChanged(const std::string &, bool); +void defaultOnRouteChanged(bool, const std::string &, const std::string &, const std::string &); +} // namespace listeners +class netlink_manager { +public: + void start(); + void stop(); + + int getRouteSock() + { + return this->routeHandler_->getSock(); + } + std::shared_ptr getRouteHandler() + { + return this->routeHandler_; + } + + static int getPid() + { + return pid_; + } + static void setPid(int pid) + { + pid_ = pid; + } + static std::shared_ptr getReporter() + { + return reporter_; + } + + explicit netlink_manager(int pid); + ~netlink_manager(); + +private: + static int pid_; + static std::shared_ptr reporter_; + + std::shared_ptr routeHandler_; + void startRouteHandler(); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NETLINK_MANAGER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_socket.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_socket.h new file mode 100755 index 0000000..0ea1934 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netlink_socket.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETLINK_SOCKET_H__ +#define INCLUDE_NETLINK_SOCKET_H__ + +#include +#include +#include +#include +#include +#include + +namespace OHOS { +namespace nmd { +class netlink_socket { +public: + int socketFd_; + int pid_ = 0; + + virtual ~netlink_socket(); + + void setSock(int sock) + { + this->socketFd_ = sock; + } + + int create(int protocol); + int create(int type, int protocol); + int binding(); + + int acceptAndListen(); + + int sendNetlinkMsgToKernel(struct nlmsghdr *msg); + + ssize_t receive(void *buf); + + int shutdown(); + + void setOnDataReceiveHandler(const std::function &handler); + + void setPid(int pid) + { + this->pid_ = pid; + } + +private: + std::function handler_; + struct sockaddr addr_ {}; + /** + * Link layer: RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK, RTM_SETLINK + * Address settings: RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR + * Routing tables: RTM_NEWROUTE, RTM_DELROUTE, RTM_GETROUTE + * Neighbor cache: RTM_NEWNEIGH, RTM_DELNEIGH, RTM_GETNEIGH + * Routing rules: RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE + * Queuing discipline settings: RTM_NEWQDISC, RTM_DELQDISC, RTM_GETQDISC + * Traffic classes used with queues: RTM_NEWTCLASS, RTM_DELTCLASS, RTM_GETTCLASS + * Traffic filters: RTM_NEWTFILTER, RTM_DELTFILTER, RTM_GETTFILTER + * Others: RTM_NEWACTION, RTM_DELACTION, RTM_GETACTION, RTM_NEWPREFIX, RTM_GETPREFIX, RTM_GETMULTICAST, + * RTM_GETANYCAST, RTM_NEWNEIGHTBL, RTM_GETNEIGHTBL, RTM_SETNEIGHTBL + */ + int send(unsigned short action, char *buffer, size_t size, unsigned short rtaType, char *attrBuf, + size_t attrBufLen); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NETLINK_SOCKET_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/netnative_log_wrapper.h b/prebuilts/librarys/netd/include/net_mgr_native/include/netnative_log_wrapper.h new file mode 100755 index 0000000..7e2464a --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/netnative_log_wrapper.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETNATIVE_LOG_WRAPPER_H +#define NETNATIVE_LOG_WRAPPER_H + +#include +#include "hilog/log.h" + +#ifndef NETMGRNATIVE_LOG_TAG +#define NETMGRNATIVE_LOG_TAG "NetdNativeService" +#endif + +static constexpr OHOS::HiviewDFX::HiLogLabel NET_MGR_LABEL = {LOG_CORE, LOG_DOMAIN, NETMGRNATIVE_LOG_TAG}; + +#define FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) + +#define PRINT_NATIVE_LOG(op, fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::op(NET_MGR_LABEL, "[%{public}s-(%{public}s:%{public}d)]" fmt, __FUNCTION__, \ + FILENAME__, __LINE__, ##__VA_ARGS__) + +#define NETNATIVE_LOGD(fmt, ...) PRINT_NATIVE_LOG(Debug, fmt, ##__VA_ARGS__) +#define NETNATIVE_LOGE(fmt, ...) PRINT_NATIVE_LOG(Error, fmt, ##__VA_ARGS__) +#define NETNATIVE_LOGW(fmt, ...) PRINT_NATIVE_LOG(Warn, fmt, ##__VA_ARGS__) +#define NETNATIVE_LOGI(fmt, ...) PRINT_NATIVE_LOG(Info, fmt, ##__VA_ARGS__) +#define NETNATIVE_LOGF(fmt, ...) PRINT_NATIVE_LOG(Fatal, fmt, ##__VA_ARGS__) + +#endif // NETNATIVE_LOG_WRAPPER_H \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/network_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/network_controller.h new file mode 100755 index 0000000..e9135a5 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/network_controller.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NETWORK_CONTROLLER_H__ +#define INCLUDE_NETWORK_CONTROLLER_H__ +#include +#include +#include +#include +#include "nmd_network.h" +namespace OHOS { +namespace nmd { +class network_controller { +public: + network_controller() = default; + ~network_controller(); + + int createPhysicalNetwork(uint16_t netId, Permission permission); + + int destroyNetwork(int netId); + + int setDefaultNetwork(int netId); + + int clearDefaultNetwork(); + + int getDefaultNetwork(); + + int addInterfaceToNetwork(int netId, std::string &interafceName); + + int removeInterfaceFromNetwork(int netId, std::string &interafceName); + + int addRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + int removeRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + int getFwmarkForNetwork(int netId); + + int setPermissionForNetwork(int netId, Permission permission); + + std::vector getNetworks(); + + nmd::NmdNetwork *getNetwork(int netId); + +private: + int defaultNetId_; + std::map networks_; + std::tuple findNetworkById(int netId); + int getNetworkForInterface(std::string &interfaceName); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NETWORK_CONTROLLER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/nmd_network.h b/prebuilts/librarys/netd/include/net_mgr_native/include/nmd_network.h new file mode 100755 index 0000000..81acdb2 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/nmd_network.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_NMD_NETWORK_H__ +#define INCLUDE_NMD_NETWORK_H__ + +#include +#include +namespace OHOS { +namespace nmd { +typedef enum Permission { + PERMISSION_NONE = 0x0, + PERMISSION_NETWORK = 0x1, + PERMISSION_SYSTEM = 0x3, +} NetworkPermission; + +class NmdNetwork { +public: + NmdNetwork(uint16_t netId, NetworkPermission permission); + + void asDefault(); + void removeAsDefault(); + + int addInterface(std::string &interfaceName); + int removeInterface(std::string &interfaceName); + int clearInterfaces(); + + bool hasInterface(std::string &interfaceName); + std::set getAllInterface() + { + return this->interfaces_; + } + + uint16_t getNetId() + { + return this->netId_; + } + NetworkPermission getPermission() + { + return this->permission_; + } + + bool isDefault() + { + return this->isDefault_; + } + + virtual ~NmdNetwork(); + +private: + uint16_t netId_; + + bool isDefault_ = false; + + NetworkPermission permission_; + + std::set interfaces_; +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_NMD_NETWORK_H__ diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/route_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/route_controller.h new file mode 100755 index 0000000..654a075 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/route_controller.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_ROUTE_CONTROLLER_H__ +#define INCLUDE_ROUTE_CONTROLLER_H__ + +#include +#include +#include "nmd_network.h" + +namespace OHOS { +namespace nmd { +typedef struct _inet_addr { + int family; + int bitlen; + int prefixlen; + uint8_t data[sizeof(struct in6_addr)]; +} _inet_addr; + +class route_controller { +public: + route_controller(); + ~route_controller(); + + static int createChildChains(const char *table, const char *parentChain, const char *childChain); + static int addInterfaceToDefaultNetwork(const char *interface, NetworkPermission permission); + static int removeInterfaceFromDefaultNetwork(const char *interface, NetworkPermission permission); + static int addInterfaceToPhysicalNetwork(uint16_t netId, const char *interface, NetworkPermission permission); + + static int removeInterfaceFromPhysicalNetwork( + uint16_t netId, const char *interfaceName, NetworkPermission permission); + + static int addRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + static int removeRoute(int netId, std::string interfaceName, std::string destination, std::string nextHop); + + static int read_addr(const char *addr, _inet_addr *res); + static int read_addr_gw(const char *addr, _inet_addr *res); + +private: + static int executeIptablesRestore(std::string command); + static void updateTableNamesFile(); + static std::map interfaceToTable_; + static uint32_t getRouteTableForInterface(const char *interfaceName); + + void modifyIpRule(std::string interface, NetworkPermission permission); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_ROUTE_CONTROLLER_H__ \ No newline at end of file diff --git a/prebuilts/librarys/netd/include/net_mgr_native/include/traffic_controller.h b/prebuilts/librarys/netd/include/net_mgr_native/include/traffic_controller.h new file mode 100755 index 0000000..121e428 --- /dev/null +++ b/prebuilts/librarys/netd/include/net_mgr_native/include/traffic_controller.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INCLUDE_TRAFFIC_CONTROLLER_H__ +#define INCLUDE_TRAFFIC_CONTROLLER_H__ +#include +#include +#include +namespace OHOS { +namespace nmd { +typedef struct arp_cache_information { + std::string ipAddr; + std::string macAddr; + std::string dev; + std::string state; + + friend std::ostream &operator<<(std::ostream &os, const arp_cache_information &information) + { + os << "ipAddr: " << information.ipAddr << " macAddr: " << information.macAddr + << " dev: " << information.dev << " state: " << information.state; + return os; + } +} arp_cache_information; + +typedef struct tether_traffic_account { + std::string bytes; + std::string sourceIp; + std::string destinationIp; + + friend std::ostream &operator<<(std::ostream &os, const tether_traffic_account &account) + { + os << "bytes: " << account.bytes << " sourceIp: " << account.sourceIp + << " destinationIp: " << account.destinationIp; + return os; + } +} tether_traffic_account; + +typedef struct tether_stats_parcel { + std::string iface; + unsigned int ifIndex = 0; + long rxBytes; + long rxPackets; + long txBytes; + long txPackets; + + friend std::ostream &operator<<(std::ostream &os, const tether_stats_parcel &parcel) + { + os << "iface: " << parcel.iface << "ifIndex: " << parcel.ifIndex << "rxBytes: " << parcel.rxBytes + << "rxPackets: " << parcel.rxPackets << "txBytes: " << parcel.txBytes + << "txPackets: " << parcel.txPackets; + return os; + } +} tether_stats_parcel; + +typedef tether_stats_parcel traffic_stats_parcel; + +class traffic_controller { +public: + traffic_controller(); + ~traffic_controller(); + bool isTetherEnable(); + static nmd::traffic_stats_parcel getInterfaceTraffic(const std::string &ifName); + static long getAllRxTraffic(); + static long getAllTxTraffic(); + static std::vector getTetherClientInfo(); + static void startTrafficTether(); + static long getTxTetherTraffic(); + static long getRxTetherTraffic(); + static long getRxUidTraffic(int uid); + static long getTxUidTraffic(int uid); + static long getCellularRxTraffic(); + static long getCellularTxTraffic(); + static void traffic_controller_log(); + static void execIptablesRuleMethod(std::string &cmd); +}; +} // namespace nmd +} // namespace OHOS +#endif // !INCLUDE_TRAFFIC_CONTROLLER_H__ \ No newline at end of file diff --git a/sa_profile/1151.xml b/sa_profile/1151.xml new file mode 100755 index 0000000..92c4fc9 --- /dev/null +++ b/sa_profile/1151.xml @@ -0,0 +1,27 @@ + + + + netmanager + + 1151 + libnet_conn_manager.z.so + + + true + false + 1 + + diff --git a/sa_profile/1152.xml b/sa_profile/1152.xml new file mode 100755 index 0000000..e023646 --- /dev/null +++ b/sa_profile/1152.xml @@ -0,0 +1,27 @@ + + + + netmanager + + 1152 + libnet_policy_manager.z.so + + + true + false + 1 + + diff --git a/sa_profile/1156.xml b/sa_profile/1156.xml new file mode 100755 index 0000000..e7bfece --- /dev/null +++ b/sa_profile/1156.xml @@ -0,0 +1,27 @@ + + + + netmanager + + 1156 + libdns_resolver_manager.z.so + + + true + false + 1 + + diff --git a/sa_profile/1157.xml b/sa_profile/1157.xml new file mode 100755 index 0000000..67bec0b --- /dev/null +++ b/sa_profile/1157.xml @@ -0,0 +1,27 @@ + + + + netmanager + + 1157 + libethernet_manager.z.so + + + true + false + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn new file mode 100755 index 0000000..ccd3584 --- /dev/null +++ b/sa_profile/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("net_manager_profile") { + sources = [ + "1151.xml", + "1152.xml", + "1156.xml", + "1157.xml", + ] + + part_name = "netmanager_standard" +} diff --git a/services/common/include/broadcast_manager.h b/services/common/include/broadcast_manager.h new file mode 100755 index 0000000..2a9ea06 --- /dev/null +++ b/services/common/include/broadcast_manager.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BROADCAST_MANAGER_H +#define BROADCAST_MANAGER_H + +#include +#include + +#include "singleton.h" + +namespace OHOS { +namespace NetManagerStandard { +struct BroadcastInfo { + std::string action; + std::string data; + int32_t code; + bool ordered; + BroadcastInfo() : code(0), ordered(true) {} +}; + +class BroadcastManager { + DECLARE_DELAYED_SINGLETON(BroadcastManager) +public: + bool SendBroadcast(const BroadcastInfo &info, const std::map ¶m); + + bool SendBroadcast(const BroadcastInfo &info, const std::map ¶m); + + bool SendBroadcast(const BroadcastInfo &info, const std::map ¶m); + +private: + template + bool SendBroadcastEx(const BroadcastInfo &info, const std::map ¶m); +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // BROADCAST_MANAGER_H diff --git a/services/common/include/netd_controller.h b/services/common/include/netd_controller.h new file mode 100755 index 0000000..d6e4794 --- /dev/null +++ b/services/common/include/netd_controller.h @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETD_CONTROLLER_H +#define NETD_CONTROLLER_H + +#include +#include +#ifdef NATIVE_NETD_FEATURE +#include "dnsresolv_service.h" +#include "fwmark_server.h" +#include "net_manager_native.h" +#include "netlink_manager.h" +#else +#include +#include +#include +#include +#include +#include +#endif + +#include "net_mgr_log_wrapper.h" +#include "route.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetdController { +public: + NetdController(); + ~NetdController(); + void Init(); + + static NetdController *GetInstance(); + /** + * @brief Create a physical network + * + * @param netId + * @param permission Permission to create a physical network + * @return Return the return value of the netd interface call + */ + int32_t NetworkCreatePhysical(int32_t netId, int32_t permission); + + /** + * @brief Destroy the network + * + * @param netId + * @return Return the return value of the netd interface call + */ + int32_t NetworkDestroy(int32_t netId); + + /** + * @brief Add network port device + * + * @param netId + * @param iface Network port device name + * @return Return the return value of the netd interface call + */ + int32_t NetworkAddInterface(int32_t netId, const std::string &iface); + + /** + * @brief Delete network port device + * + * @param netId + * @param iface Network port device name + * @return Return the return value of the netd interface call + */ + int32_t NetworkRemoveInterface(int32_t netId, const std::string &iface); + + /** + * @brief Add route + * + * @param netId + * @param ifName Network port device name + * @param destination Target host ip + * @param nextHop Next hop address + * @return Return the return value of the netd interface call + */ + int32_t NetworkAddRoute(int32_t netId, const std::string &ifName, const std::string &destination, + const std::string &nextHop); + + /** + * @brief Remove route + * + * @param netId + * @param ifName Network port device name + * @param destination Target host ip + * @param nextHop Next hop address + * @return Return the return value of the netd interface call + */ + int32_t NetworkRemoveRoute(int32_t netId, const std::string &ifName, const std::string &destination, + const std::string &nextHop); + + /** + * @brief Turn off the device + * + * @param iface Network port device name + */ + void SetInterfaceDown(const std::string &iface); + + /** + * @brief Turn on the device + * + * @param iface Network port device name + */ + void SetInterfaceUp(const std::string &iface); + + /** + * @brief Clear the network interface ip address + * + * @param ifName Network port device name + */ + void InterfaceClearAddrs(const std::string &ifName); + + /** + * @brief Obtain mtu from the network interface device + * + * @param ifName Network port device name + * @return Return the return value of the netd interface call + */ + int32_t InterfaceGetMtu(const std::string &ifName); + + /** + * @brief Set mtu to network interface device + * + * @param ifName Network port device name + * @param mtu + * @return Return the return value of the netd interface call + */ + int32_t InterfaceSetMtu(const std::string &ifName, int32_t mtu); + + /** + * @brief Add ip address + * + * @param ifName Network port device name + * @param ipAddr ip address + * @param prefixLength subnet mask + * @return Return the return value of the netd interface call + */ + int32_t InterfaceAddAddress(const std::string &ifName, const std::string &ipAddr, int32_t prefixLength); + + /** + * @brief Delete ip address + * + * @param ifName Network port device name + * @param ipAddr ip address + * @param prefixLength subnet mask + * @return Return the return value of the netd interface call + */ + int32_t InterfaceDelAddress(const std::string &ifName, const std::string &ipAddr, int32_t prefixLength); + + /** + * @brief Set dns + * + * @param netId + * @param baseTimeoutMsec + * @param retryCount + * @param servers + * @param domains + * @return Return the return value of the netd interface call + */ + int32_t SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains); + /** + * @brief Get dns server param info + * + * @param netId + * @param servers + * @param domains + * @param baseTimeoutMsec + * @param retryCount + * @return Return the return value of the netd interface call + */ + int32_t GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount); + + /** + * @brief Create dns cache before set dns + * + * @param netId + * @return Return the return value for status of call + */ + int CreateNetworkCache(uint16_t netId); + + /** + * @brief Destory dns cache + * + * @param netId + * @return Return the return value of the netd interface call + */ + int DestoryNetworkCache(uint16_t netId); + + /** + * @brief Flush dns cache + * + * @param netId + * @return Return the return value of the netd interface call + */ + int FlushNetworkCache(uint16_t netId); + + /** + * @brief Domain name resolution Obtains the domain name address + * + * @param hostName + * @param serverName + * @param hints + * @param res + * @return Return the return value of the netd interface call + */ + int GetAddrInfo(const std::string &hostName, const std::string &serverName, + const struct addrinfo &hints, std::unique_ptr &res, uint16_t netId); + +#ifdef NATIVE_NETD_FEATURE +#else + int AddRoute(const std::string &ip, const std::string &mask, + const std::string &gateWay, const std::string &devName); +#endif +private: +#ifdef NATIVE_NETD_FEATURE + std::unique_ptr netdService_ = nullptr; + std::unique_ptr manager_ = nullptr; + std::unique_ptr fwmarkServer_ = nullptr; + std::unique_ptr dnsResolvService_ = nullptr; +#endif + static NetdController *singleInstance_; + static std::mutex mutex_; + bool initFlag_ = false; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NETD_CONTROLLER_H diff --git a/services/common/include/timer.h b/services/common/include/timer.h new file mode 100755 index 0000000..b10d4a8 --- /dev/null +++ b/services/common/include/timer.h @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_MANAGER_TIMER_H +#define NET_MANAGER_TIMER_H + +#include +#include +#include +#include +#include +#include +#include + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +class Timer { +public: + Timer() : stopStatus_(true), tryStopFlag_(false) {} + + Timer(const Timer &timer) + { + stopStatus_ = timer.stopStatus_.load(); + tryStopFlag_ = timer.tryStopFlag_.load(); + } + + ~Timer() + { + Stop(); + } + + void Start(int interval, std::function taskFun) + { + if (stopStatus_ == false) { + return; + } + NETMGR_LOGI("start thread..."); + stopStatus_ = false; + std::thread([this, interval, taskFun]() { + while (!tryStopFlag_) { + std::this_thread::sleep_for(std::chrono::milliseconds(interval)); + taskFun(); + } + + std::lock_guard locker(mutex_); + stopStatus_ = true; + timerCond_.notify_one(); + }).detach(); + } + + void StartOnce(int interval, std::function taskFun) + { + std::thread([this, interval, taskFun]() { + if (!tryStopFlag_) { + std::this_thread::sleep_for(std::chrono::milliseconds(interval)); + taskFun(); + } + }).detach(); + } + + void Stop() + { + if (stopStatus_ || tryStopFlag_) { + return; + } + NETMGR_LOGI("stop thread..."); + tryStopFlag_ = true; + std::unique_lock locker(mutex_); + timerCond_.wait(locker, [this] { return stopStatus_ == true; }); + + if (stopStatus_ == true) + tryStopFlag_ = false; + } + +private: + std::atomic stopStatus_; + std::atomic tryStopFlag_; + std::mutex mutex_; + std::condition_variable timerCond_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_MANAGER_TIMER_H diff --git a/services/common/src/broadcast_manager.cpp b/services/common/src/broadcast_manager.cpp new file mode 100755 index 0000000..d95e9c3 --- /dev/null +++ b/services/common/src/broadcast_manager.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "broadcast_manager.h" + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "want.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +BroadcastManager::BroadcastManager() {} + +BroadcastManager::~BroadcastManager() {} + +bool BroadcastManager::SendBroadcast(const BroadcastInfo &info, const std::map ¶m) +{ + return SendBroadcastEx(info, param); +} + +bool BroadcastManager::SendBroadcast(const BroadcastInfo &info, const std::map ¶m) +{ + return SendBroadcastEx(info, param); +} + +bool BroadcastManager::SendBroadcast(const BroadcastInfo &info, const std::map ¶m) +{ + return SendBroadcastEx(info, param); +} + +template +bool BroadcastManager::SendBroadcastEx(const BroadcastInfo &info, const std::map ¶m) +{ + if (info.action.empty()) { + NETMGR_LOGE("The parameter of action is empty"); + return false; + } + + AAFwk::Want want; + want.SetAction(info.action); + for (const auto &x : param) { + want.SetParam(x.first, x.second); + } + + EventFwk::CommonEventData eventData; + eventData.SetWant(want); + eventData.SetCode(info.code); + eventData.SetData(info.data); + EventFwk::CommonEventPublishInfo publishInfo; + publishInfo.SetOrdered(info.ordered); + + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(eventData, publishInfo, nullptr); + if (publishResult) { + NETMGR_LOGI("Send broadcast is successfull"); + } else { + NETMGR_LOGE("Send broadcast is failed"); + } + + return publishResult; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/common/src/netd_controller.cpp b/services/common/src/netd_controller.cpp new file mode 100755 index 0000000..d16d0bb --- /dev/null +++ b/services/common/src/netd_controller.cpp @@ -0,0 +1,430 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "netd_controller.h" + +#include "securec.h" +#ifdef NATIVE_NETD_FEATURE +#include +#include "net_conn_types.h" +#else +#include +#include +#endif + +namespace OHOS { +namespace NetManagerStandard { +NetdController *NetdController::singleInstance_ = nullptr; +std::mutex NetdController::mutex_; + +NetdController::NetdController() +{ + Init(); +} + +NetdController::~NetdController() {} + +void NetdController::Init() +{ + NETMGR_LOGI("netd Init"); + if (initFlag_) { + NETMGR_LOGI("netd initialization is complete"); + return; + } + initFlag_ = true; +#ifdef NATIVE_NETD_FEATURE + netdService_ = std::make_unique(); + netdService_->init(); + + int32_t pid = getpid(); + manager_ = std::make_unique(pid); + std::thread nlManager([&] { manager_->start(); }); + + fwmarkServer_ = std::make_unique(); + std::thread fwserve([&] { fwmarkServer_->start(); }); + + dnsResolvService_ = std::make_unique(); + std::thread dnsresolvServe([&] { dnsResolvService_->start(); }); + + nlManager.detach(); + fwserve.detach(); + dnsresolvServe.detach(); +#else + return; +#endif +} + +NetdController *NetdController::GetInstance() +{ + if (singleInstance_ == nullptr) { + std::unique_lock lock(mutex_); + if (singleInstance_ == nullptr) { + singleInstance_ = std::make_unique().release(); + } + } + + return singleInstance_; +} + +int32_t NetdController::NetworkCreatePhysical(int32_t netId, int32_t permission) +{ + NETMGR_LOGI("Create Physical network: netId[%{public}d], permission[%{public}d]", netId, permission); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->networkCreatePhysical(netId, permission); +#else + return 0; +#endif +} + +int32_t NetdController::NetworkDestroy(int32_t netId) +{ + NETMGR_LOGI("Destroy network: netId[%{public}d]", netId); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->networkDestroy(netId); +#else + return 0; +#endif +} + +int32_t NetdController::NetworkAddInterface(int32_t netId, const std::string &iface) +{ + NETMGR_LOGI("Add network interface: netId[%{public}d], iface[%{public}s]", netId, iface.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->networkAddInterface(netId, iface); +#else + return 0; +#endif +} + +int32_t NetdController::NetworkRemoveInterface(int32_t netId, const std::string &iface) +{ + NETMGR_LOGI("Remove network interface: netId[%{public}d], iface[%{public}s]", netId, iface.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->networkRemoveInterface(netId, iface); +#else + return 0; +#endif +} + +int32_t NetdController::NetworkAddRoute(int32_t netId, const std::string &ifName, + const std::string &destination, const std::string &nextHop) +{ + NETMGR_LOGI("Add Route: netId[%{public}d], ifName[%{public}s], destination[%{public}s], nextHop[%{public}s]", + netId, ifName.c_str(), destination.c_str(), nextHop.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->networkAddRoute(netId, ifName, destination, nextHop); +#else + std::string mask = "0.0.0.0"; + return AddRoute(destination, mask, nextHop, ifName); +#endif +} + +int32_t NetdController::NetworkRemoveRoute(int32_t netId, const std::string &ifName, + const std::string &destination, const std::string &nextHop) +{ + NETMGR_LOGI("Remove Route: netId[%{public}d], ifName[%{public}s], destination[%{public}s], nextHop[%{public}s]", + netId, ifName.c_str(), destination.c_str(), nextHop.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->networkRemoveRoute(netId, ifName, destination, nextHop); +#else + return 0; +#endif +} + +void NetdController::SetInterfaceDown(const std::string &iface) +{ + NETMGR_LOGI("Set interface down: iface[%{public}s]", iface.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return; + } + auto interfaceConfig = netdService_->interfaceGetConfig(iface); + auto fit = std::find(interfaceConfig.flags.begin(), interfaceConfig.flags.end(), "up"); + if (fit != interfaceConfig.flags.end()) { + interfaceConfig.flags.erase(fit); + } + interfaceConfig.flags.push_back("down"); + netdService_->interfaceSetConfig(interfaceConfig); +#else + return; +#endif +} + +void NetdController::SetInterfaceUp(const std::string &iface) +{ + NETMGR_LOGI("Set interface up: iface[%{public}s]", iface.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return; + } + auto interfaceConfig = netdService_->interfaceGetConfig(iface); + auto fit = std::find(interfaceConfig.flags.begin(), interfaceConfig.flags.end(), "down"); + if (fit != interfaceConfig.flags.end()) { + interfaceConfig.flags.erase(fit); + } + interfaceConfig.flags.push_back("up"); + netdService_->interfaceSetConfig(interfaceConfig); +#else + return; +#endif +} + +void NetdController::InterfaceClearAddrs(const std::string &ifName) +{ + NETMGR_LOGI("Clear addrs: ifName[%{public}s]", ifName.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return; + } + return netdService_->interfaceClearAddrs(ifName); +#else + return; +#endif +} + +int32_t NetdController::InterfaceGetMtu(const std::string &ifName) +{ + NETMGR_LOGI("Get mtu: ifName[%{public}s]", ifName.c_str()); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->interfaceGetMtu(ifName); +#else + return 0; +#endif +} + +int32_t NetdController::InterfaceSetMtu(const std::string &ifName, int32_t mtu) +{ + NETMGR_LOGI("Set mtu: ifName[%{public}s], mtu[%{public}d]", ifName.c_str(), mtu); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->interfaceSetMtu(ifName, mtu); +#else + return 0; +#endif +} + +int32_t NetdController::InterfaceAddAddress(const std::string &ifName, + const std::string &ipAddr, int32_t prefixLength) +{ + NETMGR_LOGI("Add address: ifName[%{public}s], ipAddr[%{public}s], prefixLength[%{public}d]", + ifName.c_str(), ipAddr.c_str(), prefixLength); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->interfaceAddAddress(ifName, ipAddr, prefixLength); +#else + return 0; +#endif +} + +int32_t NetdController::InterfaceDelAddress(const std::string &ifName, + const std::string &ipAddr, int32_t prefixLength) +{ + NETMGR_LOGI("Delete address: ifName[%{public}s], ipAddr[%{public}s], prefixLength[%{public}d]", + ifName.c_str(), ipAddr.c_str(), prefixLength); +#ifdef NATIVE_NETD_FEATURE + if (netdService_ == nullptr) { + NETMGR_LOGE("netdService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return netdService_->interfaceDelAddress(ifName, ipAddr, prefixLength); +#else + return 0; +#endif +} + +int32_t NetdController::SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains) +{ + std::unique_lock lock(mutex_); + NETMGR_LOGI("Set resolver config: netId[%{public}d]", netId); +#ifdef NATIVE_NETD_FEATURE + if (dnsResolvService_ == nullptr) { + NETMGR_LOGE("dnsResolvService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + const nmd::dnsresolver_params params = {netId, baseTimeoutMsec, retryCount, servers, domains}; + return dnsResolvService_->setResolverConfig(params); +#else + return 0; +#endif +} + +int32_t NetdController::GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, + uint16_t &baseTimeoutMsec, uint8_t &retryCount) +{ + std::unique_lock lock(mutex_); + NETMGR_LOGI("Get resolver config: netId[%{public}d]", netId); +#ifdef NATIVE_NETD_FEATURE + if (dnsResolvService_ == nullptr) { + NETMGR_LOGE("dnsResolvService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + nmd::dns_res_params getParam; + int ret = dnsResolvService_->getResolverInfo(netId, servers, domains, getParam); + baseTimeoutMsec = getParam.baseTimeoutMsec; + retryCount = getParam.retryCount; + return ret; +#else + return 0; +#endif +} + +int32_t NetdController::CreateNetworkCache(uint16_t netId) +{ + std::unique_lock lock(mutex_); + NETMGR_LOGI("create Network cache: netId[%{public}d]", netId); +#ifdef NATIVE_NETD_FEATURE + if (dnsResolvService_ == nullptr) { + NETMGR_LOGE("dnsResolvService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return dnsResolvService_->createNetworkCache(netId); +#else + return 0; +#endif +} + +int NetdController::DestoryNetworkCache(uint16_t netId) +{ + std::unique_lock lock(mutex_); + NETMGR_LOGI("Destory dns cache: netId[%{public}d]", netId); +#ifdef NATIVE_NETD_FEATURE + if (dnsResolvService_ == nullptr) { + NETMGR_LOGE("dnsResolvService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return dnsResolvService_->destoryNetworkCache(netId); +#else + return 0; +#endif +} + +int NetdController::FlushNetworkCache(uint16_t netId) +{ + std::unique_lock lock(mutex_); + NETMGR_LOGI("Destory Flush dns cache: netId[%{public}d]", netId); +#ifdef NATIVE_NETD_FEATURE + if (dnsResolvService_ == nullptr) { + NETMGR_LOGE("dnsResolvService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + return dnsResolvService_->flushNetworkCache(netId); +#else + return 0; +#endif +} + +int NetdController::GetAddrInfo(const std::string &hostName, + const std::string &serverName, const struct addrinfo &hints, std::unique_ptr &res, uint16_t netId) +{ + std::unique_lock lock(mutex_); + NETMGR_LOGI("NetdController GetAddrInfo"); +#ifdef NATIVE_NETD_FEATURE + if (dnsResolvService_ == nullptr) { + NETMGR_LOGE("NetdController GetAddrInfo dnsResolvService_ is null"); + return ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL; + } + struct addrinfo *addrRes = nullptr; + int ret = dnsResolvService_->getaddrinfo(hostName.c_str(), nullptr, &hints, &addrRes, netId); + res.reset(addrRes); + return ret; +#else + return 0; +#endif +} + +#ifndef NATIVE_NETD_FEATURE +int NetdController::AddRoute(const std::string &ip, const std::string &mask, + const std::string &gateWay, const std::string &devName) +{ + int fd = 0; + fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd < 0) { + NETMGR_LOGE("NetdController create socket fd[%{public}d]", fd); + return -1; + } + struct sockaddr_in _sin; + struct sockaddr_in *sin = &_sin; + struct rtentry rt; + bzero(&rt, sizeof(struct rtentry)); + bzero(sin, sizeof(struct sockaddr_in)); + sin->sin_family = AF_INET; + sin->sin_port = 0; + if (inet_aton(gateWay.c_str(), &sin->sin_addr) < 0) { + NETMGR_LOGE("NetdController inet_aton gateWay[%{public}s]", gateWay.c_str()); + return -1; + } + memcpy_s(&rt.rt_gateway, sizeof(rt.rt_gateway), sin, sizeof(struct sockaddr_in)); + (reinterpret_cast(&rt.rt_dst))->sin_family=AF_INET; + if (inet_aton(ip.c_str(), &((struct sockaddr_in*)&rt.rt_dst)->sin_addr) < 0) { + NETMGR_LOGE("NetdController inet_aton ip[%{public}s]", ip.c_str()); + return -1; + } + (reinterpret_cast(&rt.rt_genmask))->sin_family=AF_INET; + if (inet_aton(mask.c_str(), &(reinterpret_cast(&rt.rt_genmask))->sin_addr) < 0) { + NETMGR_LOGE("NetdController inet_aton mask[%{public}s]", mask.c_str()); + return -1; + } + if (!devName.empty()) { + rt.rt_dev = (char*)devName.c_str(); + } + rt.rt_flags = RTF_GATEWAY; + if (ioctl(fd, SIOCADDRT, &rt) < 0) { + NETMGR_LOGE("NetdController ioctl error"); + return -1; + } + close(fd); + return 0; +} +#endif +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/dnsresolvermanager/BUILD.gn b/services/dnsresolvermanager/BUILD.gn new file mode 100755 index 0000000..4926eb6 --- /dev/null +++ b/services/dnsresolvermanager/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +ohos_shared_library("dns_resolver_manager") { + sources = [ + "$DNSRESOLVERMANAGER_SOURCE_DIR/src/dns_resolver_service.cpp", + "$DNSRESOLVERMANAGER_SOURCE_DIR/src/ipc/dns_resolver_service_stub.cpp", + ] + + include_dirs = [ + "$DNSRESOLVERMANAGER_SOURCE_DIR/include", + "$DNSRESOLVERMANAGER_SOURCE_DIR/include/ipc", + "$INNERKITS_ROOT/native/dnsresolvermanager/include", + "$INNERKITS_ROOT/native/netconnmanager/include", + "$INNERKITS_ROOT/native/include", + "$NETCONNMANAGER_COMMON_DIR/include", + ] + + deps = [ + "$INNERKITS_ROOT/native/dnsresolvermanager:dns_resolver_manager_if", + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$NETMANAGER_BASE_ROOT/services/netconnmanager:net_conn_manager", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "$NETMANAGER_PREBUILTS_DIR/librarys/netd:libnet_manager_native", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:libeventhandler", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "NETMGR_LOG_TAG = \"DnsResolverManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + defines += [ "NATIVE_NETD_FEATURE" ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/services/dnsresolvermanager/include/dns_resolver_service.h b/services/dnsresolvermanager/include/dns_resolver_service.h new file mode 100755 index 0000000..45f9efd --- /dev/null +++ b/services/dnsresolvermanager/include/dns_resolver_service.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DNS_RESOLVER_SERVICE_H +#define DNS_RESOLVER_SERVICE_H + +#include "singleton.h" +#include "system_ability.h" + +#include "ipc/dns_resolver_service_stub.h" + +namespace OHOS { +namespace NetManagerStandard { +class DnsResolverService : public SystemAbility, + public DnsResolverServiceStub, + public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(DnsResolverService) + DECLARE_SYSTEM_ABILITY(DnsResolverService) + + enum ServiceRunningState { + STATE_STOPPED = 0, + STATE_RUNNING, + }; + +public: + void OnStart() override; + void OnStop() override; + + int32_t GetAddressesByName(const std::string &hostName, std::vector &addrInfo) override; + int32_t GetAddrInfo(const std::string &hostName, const std::string &server, + const sptr &hints, std::vector> &dnsAddrInfo) override; + int32_t CreateNetworkCache(uint16_t netId) override; + int32_t DestoryNetworkCache(uint16_t netId) override; + int32_t FlushNetworkCache(uint16_t netId) override; + int32_t SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains) override; + int32_t GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount) override; + +private: + bool Init(); + +private: + ServiceRunningState state_ = ServiceRunningState::STATE_STOPPED; + bool registerToService_ = false; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // DNS_RESOLVER_SERVICE_H \ No newline at end of file diff --git a/services/dnsresolvermanager/include/ipc/dns_resolver_service_proxy.h b/services/dnsresolvermanager/include/ipc/dns_resolver_service_proxy.h new file mode 100755 index 0000000..d0e8d1d --- /dev/null +++ b/services/dnsresolvermanager/include/ipc/dns_resolver_service_proxy.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DNS_RESOLVER_SERVICE_PROXY_H +#define DNS_RESOLVER_SERVICE_PROXY_H + +#include + +#include "iremote_proxy.h" +#include "i_dns_resolver_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class DnsResolverServiceProxy : public IRemoteProxy { +public: + explicit DnsResolverServiceProxy(const sptr &impl); + virtual ~DnsResolverServiceProxy(); + bool WriteInterfaceToken(MessageParcel &data); + int32_t GetAddressesByName(const std::string &hostName, std::vector &addrInfo) override; + int32_t GetAddrInfo(const std::string &hostName, const std::string &server, + const sptr &hints, std::vector> &dnsAddrInfo) override; + int32_t CreateNetworkCache(uint16_t netId) override; + int32_t DestoryNetworkCache(uint16_t netId) override; + int32_t FlushNetworkCache(uint16_t netId) override; + int32_t SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains) override; + int32_t GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // DNS_RESOLVER_SERVICE_PROXY_H \ No newline at end of file diff --git a/services/dnsresolvermanager/include/ipc/dns_resolver_service_stub.h b/services/dnsresolvermanager/include/ipc/dns_resolver_service_stub.h new file mode 100755 index 0000000..5ecf964 --- /dev/null +++ b/services/dnsresolvermanager/include/ipc/dns_resolver_service_stub.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DNS_RESOLVER_SERVICE_STUB_H +#define DNS_RESOLVER_SERVICE_STUB_H + +#include +#include "iremote_stub.h" +#include "i_dns_resolver_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class DnsResolverServiceStub : public IRemoteStub { + using DnsResolverServiceFunc = int32_t (DnsResolverServiceStub::*)(MessageParcel &, MessageParcel &); + +public: + DnsResolverServiceStub(); + ~DnsResolverServiceStub(); + int32_t OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t OnGetAddressesByName(MessageParcel &data, MessageParcel &reply); + int32_t OnGetAddrInfo(MessageParcel &data, MessageParcel &reply); + int32_t OnCreateNetworkCache(MessageParcel &data, MessageParcel &reply); + int32_t OnDestoryNetworkCache(MessageParcel &data, MessageParcel &reply); + int32_t OnFlushNetworkCache(MessageParcel &data, MessageParcel &reply); + int32_t OnSetResolverConfig(MessageParcel &data, MessageParcel &reply); + int32_t OnGetResolverInfo(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // DNS_RESOLVER_SERVICE_STUB_H + diff --git a/services/dnsresolvermanager/include/ipc/i_dns_resolver_service.h b/services/dnsresolvermanager/include/ipc/i_dns_resolver_service.h new file mode 100755 index 0000000..2927f6c --- /dev/null +++ b/services/dnsresolvermanager/include/ipc/i_dns_resolver_service.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_DNS_RESOLVER_SERVICE_H +#define I_DNS_RESOLVER_SERVICE_H + +#include +#include + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "inet_addr.h" + +#include "dns_addr_info.h" + +namespace OHOS { +namespace NetManagerStandard { +class IDnsResolverService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.NetManagerStandard.IDnsResolverService"); + enum { + CMD_GET_ADDR_BY_NAME, + CMD_GET_ADDR_INFO, + CMD_CRT_NETWORK_CACHE, + CMD_DEL_NETWORK_CACHE, + CMD_FLS_NETWORK_CACHE, + CMD_SET_RESOLVER_CONFIG, + CMD_GET_RESOLVER_INFO, + }; + +public: + virtual int32_t GetAddressesByName(const std::string &hostName, std::vector &addrInfo) = 0; + virtual int32_t GetAddrInfo(const std::string &hostName, const std::string &server, + const sptr &hints, std::vector> &dnsAddrInfo) = 0; + virtual int32_t CreateNetworkCache(uint16_t netId) = 0; + virtual int32_t DestoryNetworkCache(uint16_t netId) = 0; + virtual int32_t FlushNetworkCache(uint16_t netId) = 0; + virtual int32_t SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains) = 0; + virtual int32_t GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount) = 0; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // I_DNS_RESOLVER_SERVICE_H \ No newline at end of file diff --git a/services/dnsresolvermanager/src/dns_resolver_service.cpp b/services/dnsresolvermanager/src/dns_resolver_service.cpp new file mode 100755 index 0000000..9370bbc --- /dev/null +++ b/services/dnsresolvermanager/src/dns_resolver_service.cpp @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dns_resolver_service.h" + +#include +#include +#include + +#include "system_ability_definition.h" + +#include "dns_resolver_constants.h" +#include "net_mgr_log_wrapper.h" +#include "netd_controller.h" + +namespace OHOS { +namespace NetManagerStandard { +const bool REGISTER_LOCAL_RESULT_DNS = SystemAbility::MakeAndRegisterAbility( + DelayedSingleton::GetInstance().get()); +constexpr int32_t IPV4_SIZE = 16; +constexpr int32_t IPV6_SIZE = 48; + +DnsResolverService::DnsResolverService() + : SystemAbility(COMM_DNS_MANAGER_SYS_ABILITY_ID, true) +{} + +DnsResolverService::~DnsResolverService() {} + +void DnsResolverService::OnStart() +{ + NETMGR_LOGI("DnsResolverService::OnStart"); + if (state_ == STATE_RUNNING) { + NETMGR_LOGI("DnsResolverService the state is already running"); + return; + } + if (!Init()) { + NETMGR_LOGE("DnsResolverService init failed"); + return; + } + state_ = STATE_RUNNING; +} + +void DnsResolverService::OnStop() +{ + state_ = STATE_STOPPED; + registerToService_ = false; +} + +bool DnsResolverService::Init() +{ + if (!REGISTER_LOCAL_RESULT_DNS) { + NETMGR_LOGE("DnsResolverService Register to local sa manager failed"); + return false; + } + if (!registerToService_) { + if (!Publish(DelayedSingleton::GetInstance().get())) { + NETMGR_LOGE("DnsResolverService Register to sa manager failed"); + return false; + } + registerToService_ = true; + } + NETMGR_LOGI("GetDnsServer suc"); + return true; +} + +static void FreeAddrInfo2(struct addrinfo *aiHead) +{ + struct addrinfo *ai = nullptr, *aiNext = nullptr; + for (ai = aiHead; ai != nullptr; ai = aiNext) { + if (ai->ai_addr != nullptr) { + free(ai->ai_addr); + ai->ai_addr = nullptr; + } + if (ai->ai_canonname != nullptr) { + free(ai->ai_canonname); + ai->ai_canonname = nullptr; + } + aiNext = ai->ai_next ; + free(ai); + if (aiNext == nullptr) { + return; + } + } +} + +static bool IsDomainValid(const std::string &hostName) +{ + if (hostName.empty()) { + return false; + } + static std::regex domainPattern("([0-9A-Za-z\\-_\\.]+)\\.([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)"); + if (regex_match(hostName, domainPattern)) { + return true; + } + return false; +} + +static void ProcessIPV4(const struct addrinfo &addr, std::vector &addrInfo) +{ + char ip4Buf[IPV4_SIZE]; + bzero(ip4Buf, IPV4_SIZE); + struct sockaddr_in *sockAddr4 = reinterpret_cast(addr.ai_addr); + inet_ntop(AF_INET, &sockAddr4->sin_addr, ip4Buf, IPV4_SIZE); + INetAddr iNetAddr; + iNetAddr.family_ = addr.ai_family; + iNetAddr.address_ = std::string(ip4Buf); + addrInfo.push_back(iNetAddr); +} + +static void ProcessIPV6(const struct addrinfo &addr, std::vector &addrInfo) +{ + char ip6Buf[IPV6_SIZE]; + bzero(ip6Buf, IPV6_SIZE); + struct sockaddr_in6 *sockAddr6 = reinterpret_cast(addr.ai_addr); + inet_ntop(AF_INET6, &sockAddr6->sin6_addr, ip6Buf, IPV6_SIZE); + INetAddr iNetAddr; + iNetAddr.family_ = addr.ai_family; + iNetAddr.address_ = std::string(ip6Buf); + addrInfo.push_back(iNetAddr); +} + +inline void InitAddrInfo(struct addrinfo &hints, int32_t family, int32_t flags, int32_t protocol, int32_t sockType) +{ + bzero(&hints, sizeof(struct addrinfo)); + hints.ai_family = family; + hints.ai_flags = flags; + hints.ai_protocol = protocol; + hints.ai_socktype = sockType; +} + +int32_t DnsResolverService::GetAddressesByName(const std::string &hostName, std::vector &addrInfo) +{ + if (!IsDomainValid(hostName)) { + NETMGR_LOGE("Invalid domain name format"); + return DNS_ERROR; + } + struct addrinfo hints; + InitAddrInfo(hints, AF_INET, AI_PASSIVE, 0, SOCK_DGRAM); + std::unique_ptr res; + std::string server; + uint16_t netId = 0; + int32_t ret = NetdController::GetInstance()->GetAddrInfo(hostName, server, hints, res, netId); + if (ret != 0) { + NETMGR_LOGE("GetAddressesByName Call GetAddrInfo of NetdController ret[%{public}d]", ret); + return ret; + } + struct addrinfo *cur = nullptr; + struct addrinfo *resAddr = res.release(); + if (resAddr == nullptr) { + NETMGR_LOGE("GetAddrInfo of NetdController return resAddr error"); + return DNS_ERROR; + } + for (cur = resAddr; cur != nullptr; cur = cur->ai_next) { + if (cur->ai_family == AF_INET) { + ProcessIPV4(*cur, addrInfo); + } else if (cur->ai_family == AF_INET6) { + ProcessIPV6(*cur, addrInfo); + } + } + if (resAddr != nullptr) { + FreeAddrInfo2(resAddr); + } + NETMGR_LOGE("GetAddressesByName addrInfo size [%{public}d]", addrInfo.size()); + return DNS_SUCCESS; +} + +int32_t DnsResolverService::GetAddrInfo(const std::string &hostName, const std::string &server, + const sptr &hints, std::vector> &dnsAddrInfo) +{ + if (!IsDomainValid(hostName)) { + return DNS_ERROR; + } + struct addrinfo hints2; + InitAddrInfo(hints2, hints->family_, hints->flags_, hints->protocol_, hints->sockType_); + std::unique_ptr res; + uint16_t netId = 0; + int32_t ret = NetdController::GetInstance()->GetAddrInfo(hostName, server, hints2, res, netId); + if (ret < 0) { + return ret; + } + struct addrinfo *cur = nullptr; + struct addrinfo *resAddr = res.release(); + if (resAddr == nullptr) { + return DNS_ERROR; + } + char ipbuf[IPV4_SIZE]; + for (cur = resAddr; cur != nullptr; cur = cur->ai_next) { + sptr d = (std::make_unique()).release(); + if (d == nullptr) { + continue; + } + d->flags_ = cur->ai_flags; + d->family_ = cur->ai_family; + d->sockType_ = cur->ai_socktype; + d->protocol_ = cur->ai_protocol; + if (d->family_ == AF_INET) { + bzero(ipbuf, IPV4_SIZE); + auto addr = reinterpret_cast(cur->ai_addr); + inet_ntop(AF_INET, &addr->sin_addr, ipbuf, IPV4_SIZE); + d->addr_ = std::string(ipbuf); + } + dnsAddrInfo.push_back(d); + } + return DNS_SUCCESS; +} + +int32_t DnsResolverService::CreateNetworkCache(uint16_t netId) +{ + NETMGR_LOGI("DnsResolverService CreateNetworkCache netId[%{public}d]", netId); + return static_cast(NetdController::GetInstance()->CreateNetworkCache(netId)); +} + +int32_t DnsResolverService::DestoryNetworkCache(uint16_t netId) +{ + NETMGR_LOGI("DnsResolverService DestoryNetworkCache netId[%{public}d]", netId); + return static_cast(NetdController::GetInstance()->DestoryNetworkCache(netId)); +} + +int32_t DnsResolverService::FlushNetworkCache(uint16_t netId) +{ + NETMGR_LOGI("DnsResolverService FlushNetworkCache netId[%{public}d]", netId); + return static_cast(NetdController::GetInstance()->FlushNetworkCache(netId)); +} + +int32_t DnsResolverService::SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains) +{ + NETMGR_LOGI("DnsResolverService SetResolverConfig netId[%{public}d]", netId); + return static_cast(NetdController::GetInstance()->SetResolverConfig(netId, baseTimeoutMsec, + retryCount, servers, domains)); +} + +int32_t DnsResolverService::GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount) +{ + NETMGR_LOGI("DnsResolverService GetResolverInfo netId[%{public}d]", netId); + return static_cast(NetdController::GetInstance()->GetResolverInfo(netId, servers, domains, + baseTimeoutMsec, retryCount)); +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/dnsresolvermanager/src/ipc/dns_resolver_service_proxy.cpp b/services/dnsresolvermanager/src/ipc/dns_resolver_service_proxy.cpp new file mode 100755 index 0000000..4b77afe --- /dev/null +++ b/services/dnsresolvermanager/src/ipc/dns_resolver_service_proxy.cpp @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dns_resolver_service_proxy.h" +#include "ipc_types.h" +#include "net_mgr_log_wrapper.h" +#include "dns_resolver_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +DnsResolverServiceProxy::DnsResolverServiceProxy(const sptr &impl) + :IRemoteProxy(impl) +{ +} + +DnsResolverServiceProxy::~DnsResolverServiceProxy() {} + +bool DnsResolverServiceProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(DnsResolverServiceProxy::GetDescriptor())) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return false; + } + return true; +} + +int32_t DnsResolverServiceProxy::GetAddressesByName(const std::string &hostName, std::vector &addrInfo) +{ + MessageParcel data; + if (hostName.empty()) { + return NETMANAGER_ERR_STRING_EMPTY; + } + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteString(hostName)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_GET_ADDR_BY_NAME, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + int32_t vsize = 0; + if (!reply.ReadInt32(vsize)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + for (int32_t i = 0; i < vsize; ++i) { + sptr addr = INetAddr::Unmarshalling(reply); + addrInfo.push_back(*addr); + } + return reply.ReadInt32(); +} + +int32_t DnsResolverServiceProxy::GetAddrInfo(const std::string &hostName, const std::string &server, + const sptr &hints, std::vector> &dnsAddrInfo) +{ + MessageParcel data; + if (hostName.empty()) { + return NETMANAGER_ERR_STRING_EMPTY; + } + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteString(hostName)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + if (!data.WriteString(server)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + if (!hints->Marshalling(data)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_GET_ADDR_INFO, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + int32_t vsize; + if (!reply.ReadInt32(vsize)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + for (int32_t i = 0; i < vsize; ++i) { + auto d = DnsAddrInfo::Unmarshalling(reply); + if (d != nullptr) { + dnsAddrInfo.push_back(d); + } else { + return NETMANAGER_ERR_LOCAL_PTR_NULL; + } + } + return reply.ReadInt32(); +} + +int32_t DnsResolverServiceProxy::CreateNetworkCache(uint16_t netId) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteUint16(netId)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_CRT_NETWORK_CACHE, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + return reply.ReadInt32(); +} + +int32_t DnsResolverServiceProxy::DestoryNetworkCache(uint16_t netId) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteUint16(netId)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_DEL_NETWORK_CACHE, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + return reply.ReadInt32(); +} + +int32_t DnsResolverServiceProxy::FlushNetworkCache(uint16_t netId) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteUint16(netId)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_FLS_NETWORK_CACHE, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + return reply.ReadInt32(); +} + +int32_t DnsResolverServiceProxy::SetResolverConfig(uint16_t netId, uint16_t baseTimeoutMsec, uint8_t retryCount, + const std::vector &servers, const std::vector &domains) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteUint16(netId)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + if (!data.WriteUint16(baseTimeoutMsec)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + if (!data.WriteUint8(retryCount)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + int32_t vsize = servers.size(); + if (!data.WriteInt32(vsize)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + for (auto it = servers.begin(); it != servers.end(); ++it) { + if (!data.WriteString(*it)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + } + vsize = domains.size(); + if (!data.WriteInt32(vsize)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + for (auto it = domains.begin(); it != domains.end(); ++it) { + if (!data.WriteString(*it)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_SET_RESOLVER_CONFIG, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + return reply.ReadInt32(); +} + +int32_t DnsResolverServiceProxy::GetResolverInfo(uint16_t netId, std::vector &servers, + std::vector &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteUint16(netId)) { + return NETMANAGER_ERR_WRITE_DATA_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_GET_RESOLVER_INFO, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + int32_t size = 0; + if (!reply.ReadInt32(size)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + std::string s; + for (int32_t i = 0; i < size; ++i) { + std::string().swap(s); + if (!reply.ReadString(s)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + servers.push_back(s); + } + if (!reply.ReadInt32(size)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + for (int32_t i = 0; i < size; ++i) { + std::string().swap(s); + if (!reply.ReadString(s)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + domains.push_back(s); + } + if (!reply.ReadUint16(baseTimeoutMsec)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + if (!reply.ReadUint8(retryCount)) { + return NETMANAGER_ERR_READ_REPLY_FAIL; + } + return reply.ReadInt32(); +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/dnsresolvermanager/src/ipc/dns_resolver_service_stub.cpp b/services/dnsresolvermanager/src/ipc/dns_resolver_service_stub.cpp new file mode 100755 index 0000000..50b68ba --- /dev/null +++ b/services/dnsresolvermanager/src/ipc/dns_resolver_service_stub.cpp @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dns_resolver_service_stub.h" + +#include "dns_resolver_constants.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +DnsResolverServiceStub::DnsResolverServiceStub() +{ + memberFuncMap_[CMD_GET_ADDR_BY_NAME] = &DnsResolverServiceStub::OnGetAddressesByName; + memberFuncMap_[CMD_GET_ADDR_INFO] = &DnsResolverServiceStub::OnGetAddrInfo; + memberFuncMap_[CMD_CRT_NETWORK_CACHE] = &DnsResolverServiceStub::OnCreateNetworkCache; + memberFuncMap_[CMD_DEL_NETWORK_CACHE] = &DnsResolverServiceStub::OnDestoryNetworkCache; + memberFuncMap_[CMD_FLS_NETWORK_CACHE] = &DnsResolverServiceStub::OnFlushNetworkCache; + memberFuncMap_[CMD_SET_RESOLVER_CONFIG] = &DnsResolverServiceStub::OnSetResolverConfig; + memberFuncMap_[CMD_GET_RESOLVER_INFO] = &DnsResolverServiceStub::OnGetResolverInfo; +} + +DnsResolverServiceStub::~DnsResolverServiceStub() {} + +int32_t DnsResolverServiceStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + NETMGR_LOGI("stub call start, code = [%{public}d]", code); + + std::u16string myDescripter = DnsResolverServiceStub::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (myDescripter != remoteDescripter) { + NETMGR_LOGE("descriptor checked fail"); + return NETMANAGER_ERR_DESCRIPTOR_MISMATCH; + } + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + + NETMGR_LOGI("stub default case, need check"); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t DnsResolverServiceStub::OnGetAddressesByName(MessageParcel &data, MessageParcel &reply) +{ + std::string hostName; + if (!data.ReadString(hostName)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + std::vector addrInfo; + int32_t ret = GetAddressesByName(hostName, addrInfo); + if (!reply.WriteInt32(addrInfo.size())) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + for (auto s : addrInfo) { + if (!s.Marshalling(reply)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + } + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t DnsResolverServiceStub::OnGetAddrInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string hostname; + std::string server; + if (!data.ReadString(hostname)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + if (!data.ReadString(server)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + sptr hints = DnsAddrInfo::Unmarshalling(data); + std::vector> dnsAddrInfo; + int32_t ret = GetAddrInfo(hostname, server, hints, dnsAddrInfo); + + int32_t vsize = dnsAddrInfo.size(); + if (!reply.WriteInt32(vsize)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + for (std::vector>::iterator it = dnsAddrInfo.begin(); it != dnsAddrInfo.end(); ++it) { + (*it)->Marshalling(reply); + } + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t DnsResolverServiceStub::OnCreateNetworkCache(MessageParcel &data, MessageParcel &reply) +{ + uint16_t netId = 0; + if (!data.ReadUint16(netId)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + int32_t ret = CreateNetworkCache(netId); + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t DnsResolverServiceStub::OnDestoryNetworkCache(MessageParcel &data, MessageParcel &reply) +{ + uint16_t netId = 0; + if (!data.ReadUint16(netId)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + int32_t ret = DestoryNetworkCache(netId); + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t DnsResolverServiceStub::OnFlushNetworkCache(MessageParcel &data, MessageParcel &reply) +{ + uint16_t netId = 0; + if (!data.ReadUint16(netId)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + int32_t ret = FlushNetworkCache(netId); + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t DnsResolverServiceStub::OnSetResolverConfig(MessageParcel &data, MessageParcel &reply) +{ + uint16_t netId = 0; + uint16_t baseTimeoutMsec = 0; + uint8_t retryCount = 0; + std::vector servers; + std::vector domains; + + if (!data.ReadUint16(netId)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + if (!data.ReadUint16(baseTimeoutMsec)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + if (!data.ReadUint8(retryCount)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + int32_t size; + if (!data.ReadInt32(size)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + + std::string s; + for (int32_t i = 0; i < size; ++i) { + std::string().swap(s); + if (!data.ReadString(s)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + servers.push_back(s); + } + + if (!data.ReadInt32(size)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + + for (int32_t i = 0; i < size; ++i) { + std::string().swap(s); + if (!data.ReadString(s)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + domains.push_back(s); + } + int32_t ret = SetResolverConfig(netId, baseTimeoutMsec, retryCount, servers, domains); + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t DnsResolverServiceStub::OnGetResolverInfo(MessageParcel &data, MessageParcel &reply) +{ + uint16_t netId = 0; + std::vector servers; + std::vector domains; + uint16_t baseTimeoutMsec = 0; + uint8_t retryCount = 0; + if (!data.ReadUint16(netId)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + int32_t ret = GetResolverInfo(netId, servers, domains, baseTimeoutMsec, retryCount); + + int32_t vsize = servers.size(); + if (!reply.WriteInt32(vsize)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + for (std::vector::iterator it = servers.begin(); it != servers.end(); ++it) { + if (!reply.WriteString(*it)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + } + + vsize = domains.size(); + if (!reply.WriteInt32(vsize)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + for (std::vector::iterator it = domains.begin(); it != domains.end(); ++it) { + if (!reply.WriteString(*it)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + } + + if (!reply.WriteUint16(baseTimeoutMsec)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + + if (!reply.WriteUint8(retryCount)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/dnsresolvermanager/test/BUILD.gn b/services/dnsresolvermanager/test/BUILD.gn new file mode 100755 index 0000000..d55667c --- /dev/null +++ b/services/dnsresolvermanager/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +group("unittest") { + testonly = true + deps = [] + deps += [ "unittest/dns_resolver_manager_test:unittest" ] +} diff --git a/services/dnsresolvermanager/test/unittest/dns_resolver_manager_test/BUILD.gn b/services/dnsresolvermanager/test/unittest/dns_resolver_manager_test/BUILD.gn new file mode 100755 index 0000000..061f810 --- /dev/null +++ b/services/dnsresolvermanager/test/unittest/dns_resolver_manager_test/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +ohos_unittest("dns_resolver_manager_test") { + module_out_path = "netmanager_base/dns_resolver_manager_test" + + sources = [ + "$NETMANAGER_PREBUILTS_DIR/src/ipc/dns_resolver_service_proxy.cpp", + "dns_resolver_manager_test.cpp", + ] + + include_dirs = [ + "$INNERKITS_ROOT/native/dnsresolvermanager/include", + "$INNERKITS_ROOT/native/dnsresolvermanager/include/ipc", + "$NETMANAGER_PREBUILTS_DIR/include/ipc", + "$NETMANAGER_PREBUILTS_DIR/include", + ] + + deps = [ + "$INNERKITS_ROOT/native/dnsresolvermanager:dns_resolver_manager_if", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "$NETMANAGER_PREBUILTS_DIR:dnsresolvermanager", + ] + + external_deps = [ "ipc:ipc_core" ] + + defines = [ + "NETMGR_LOG_TAG = \"DnsResolverManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":ethernet_manager_test" ] +} diff --git a/services/dnsresolvermanager/test/unittest/dns_resolver_manager_test/dns_resolver_manager_test.cpp b/services/dnsresolvermanager/test/unittest/dns_resolver_manager_test/dns_resolver_manager_test.cpp new file mode 100755 index 0000000..094962b --- /dev/null +++ b/services/dnsresolvermanager/test/unittest/dns_resolver_manager_test/dns_resolver_manager_test.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "dns_resolver_client.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +using namespace testing::ext; +class DnsResolverManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void DnsResolverManagerTest::SetUpTestCase() {} + +void DnsResolverManagerTest::TearDownTestCase() {} + +void DnsResolverManagerTest::SetUp() {} + +void DnsResolverManagerTest::TearDown() {} + +/** + * @tc.name: DnsResolverManagerTest001 + * @tc.desc: Test DnsResolverManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(DnsResolverManagerTest, DnsResolverManagerTest001, TestSize.Level1) +{ + std::string server = "domain1"; + std::vector addrInfo; + uint16_t netId = 0; + uint16_t baseTimeoutMsec = 0x00; + uint8_t retryCount = 0x01; + std::vector servers = {"8.8.8.8", "114.114.114.114"}; + std::vector domains = {"domian1", "domian2"}; + int32_t ret = DelayedSingleton::GetInstance()->CreateNetworkCache(netId); + ret = DelayedSingleton::GetInstance()->SetResolverConfig(netId, + baseTimeoutMsec, retryCount, servers, domains); + ret = DelayedSingleton::GetInstance()->GetAddressesByName(server, addrInfo); + std::cout << "GetAddressesByName ret:" << ret << std::endl; + std::cout << "GetAddressesByName size:%d" << dnsAddrInfos.size() << std::endl; + for (auto s : addrInfo) { + std::cout << "dnsResolverService GetAddrInfo ip:"; + std::cout << static_cast(s.family_) << std::endl; + std::cout << s.address_ << std::endl; + } +} + +/** + * @tc.name: DnsResolverManagerTest001 + * @tc.desc: Test DnsResolverManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(DnsResolverManagerTest, DnsResolverManagerTest002, TestSize.Level1) +{ + std::string server = "www.163.com"; + std::vector> dnsAddrInfos; + sptr hints = std::make_unique().release(); + hints->family_ = AF_INET; + hints->flags_ = AI_PASSIVE; + hints->protocol_ = 0; + hints->sockType_ = SOCK_DGRAM; + + DelayedSingleton::GetInstance()->GetAddrInfo(server, "", hints, dnsAddrInfos); + std::cout << "dnsAddrInfos size:%d" << dnsAddrInfos.size() << std::endl; + for (std::vector>::iterator it = dnsAddrInfos.begin(); it != dnsAddrInfos.end(); it++) { + std::cout << "dnsResolverService GetAddrInfo ip:" << std::endl; + std::cout << "ip type:" << static_cast(s.family_) << std::endl; + std::cout << "ip address:" << s.address_ << std::endl; + } +} + +/** + * @tc.name: DnsResolverManagerTest002 + * @tc.desc: Test DnsResolverManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(DnsResolverManagerTest, DnsResolverManagerTest003, TestSize.Level1) +{ + int32_t netId = 0; + int32_t result = DelayedSingleton::GetInstance()->CreateNetworkCache(netId); + ASSERT_TRUE(result == 0); +} + +/** + * @tc.name: DnsResolverManagerTest003 + * @tc.desc: Test DnsResolverManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(DnsResolverManagerTest, DnsResolverManagerTest004, TestSize.Level1) +{ + int32_t netId = 0; + int32_t result = DelayedSingleton::GetInstance()->DestoryNetworkCache(netId); + ASSERT_TRUE(result == 0); +} + +/** + * @tc.name: DnsResolverManagerTest004 + * @tc.desc: Test DnsResolverManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(DnsResolverManagerTest, DnsResolverManagerTest005, TestSize.Level1) +{ + int32_t netId = 0; + int32_t result = DelayedSingleton::GetInstance()->FlushNetworkCache(netId); + ASSERT_TRUE(result == 0); +} + +/** + * @tc.name: DnsResolverManagerTest005 + * @tc.desc: Test DnsResolverManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(DnsResolverManagerTest, DnsResolverManagerTest006, TestSize.Level1) +{ + int32_t netId = 0; + uint16_t baseTimeoutMsec = 0x00; + uint8_t retryCount = 0x01; + std::vector servers = {"8.8.8.8", "114.114.114.114"}; + std::vector domains = {"domian1", "domian2"}; + int32_t result = DelayedSingleton::GetInstance()->SetResolverConfig(netId, + baseTimeoutMsec, retryCount, servers, domains); + ASSERT_TRUE(result == 0); +} + +/** + * @tc.name: DnsResolverManagerTest005 + * @tc.desc: Test DnsResolverManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(DnsResolverManagerTest, DnsResolverManagerTest006, TestSize.Level1) +{ + int32_t netId = 0; + std::vector servers; + std::vector domains; + uint16_t baseTimeoutMsec; + uint8_t retryCount; + int32_t result = DelayedSingleton::GetInstance()->GetResolverInfo(netId, + servers, domains, baseTimeoutMsec, retryCount); + ASSERT_TRUE(result == 0); + for (std::string& s : servers) { + std::cout << "GetResolverInfo server" << s << std::endl; + } + for (std::string& s : domains) { + std::cout << "GetResolverInfo domains" << s << std::endl; + } + std::cout << "GetResolverInfo baseTimeoutMsec" << baseTimeoutMsec << std::endl; + std::cout << "GetResolverInfo retryCount" << static_cast(retryCount) << std::endl; + std::cout << "TestGetResolverInfo ret:" << ret << std::endl; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/etc/init/BUILD.gn b/services/etc/init/BUILD.gn new file mode 100755 index 0000000..a0e0374 --- /dev/null +++ b/services/etc/init/BUILD.gn @@ -0,0 +1,39 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") + +## Install netmanager_base.rc/netmanager_base.rc to /system/etc/init +ohos_prebuilt_etc("netmanager_base.rc") { + if (use_musl) { + source = "netmanager_base.cfg" + } else { + source = "netmanager_base.rc" + } + + relative_install_dir = "init" + part_name = "netmanager_standard" + subsystem_name = "communication" +} + +## Install netd.rc/netd.cfg to /system/etc/init +ohos_prebuilt_etc("netd.rc") { + if (use_musl) { + source = "netd.cfg" + } else { + source = "netd.rc" + } + + relative_install_dir = "init" + part_name = "netmanager_standard" + subsystem_name = "communication" +} \ No newline at end of file diff --git a/services/etc/init/netd.cfg b/services/etc/init/netd.cfg new file mode 100755 index 0000000..4827be8 --- /dev/null +++ b/services/etc/init/netd.cfg @@ -0,0 +1,10 @@ +{ + "jobs" : [{ + "name" : "boot", + "cmds" : [ + "exec /system/bin/sleep 4", + "start netd" + ] + } + ] +} diff --git a/services/etc/init/netd.rc b/services/etc/init/netd.rc new file mode 100755 index 0000000..bf55a8d --- /dev/null +++ b/services/etc/init/netd.rc @@ -0,0 +1,19 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +on boot + start netd + +#service netd /system/bin/sa_main /system/profile/netmanager.xml +# user root +# group root +# seclabel u:r:telephony:s0 diff --git a/services/etc/init/netmanager_base.cfg b/services/etc/init/netmanager_base.cfg new file mode 100755 index 0000000..908ede7 --- /dev/null +++ b/services/etc/init/netmanager_base.cfg @@ -0,0 +1,17 @@ +{ + "jobs" : [{ + "name" : "boot", + "cmds" : [ + "exec /system/bin/sleep 4", + "start netmanager" + ] + } + ], + "services" : [{ + "name" : "netmanager", + "path" : ["/system/bin/sa_main", "/system/profile/netmanager.xml"], + "uid" : "system", + "gid" : ["system", "shell"] + } + ] +} diff --git a/services/etc/init/netmanager_base.rc b/services/etc/init/netmanager_base.rc new file mode 100755 index 0000000..3d3c2a7 --- /dev/null +++ b/services/etc/init/netmanager_base.rc @@ -0,0 +1,19 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +on boot + start netmanager + +service netmanager /system/bin/sa_main /system/profile/netmanager.xml + user system + group system shell + seclabel u:r:telephony:s0 \ No newline at end of file diff --git a/services/ethernetmanager/BUILD.gn b/services/ethernetmanager/BUILD.gn new file mode 100755 index 0000000..d37b4b5 --- /dev/null +++ b/services/ethernetmanager/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +ohos_shared_library("ethernet_manager") { + sources = [ + "$ETHERNETMANAGER_SOURCE_DIR/src/dev_interface_state.cpp", + "$ETHERNETMANAGER_SOURCE_DIR/src/ethernet_management.cpp", + "$ETHERNETMANAGER_SOURCE_DIR/src/ethernet_service.cpp", + "$ETHERNETMANAGER_SOURCE_DIR/src/ipc/ethernet_service_stub.cpp", + "$ETHERNETMANAGER_SOURCE_DIR/src/netLink_rtnl.cpp", + ] + + include_dirs = [ + "$ETHERNETMANAGER_SOURCE_DIR/include", + "$ETHERNETMANAGER_SOURCE_DIR/include/ipc", + "$ETHERNETMANAGER_SOURCE_DIR/include/dhcp", + "$INNERKITS_ROOT/native/include", + "$INNERKITS_ROOT/native/netconnmanager/include", + "$INNERKITS_ROOT/native/dnsresolvermanager/include", + "$INNERKITS_ROOT/native/ethernetmanager/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + ] + + deps = [ + "$INNERKITS_ROOT/native/ethernetmanager:ethernet_manager_if", + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$NETMANAGER_BASE_ROOT/services/netconnmanager:net_conn_manager", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "$NETMANAGER_PREBUILTS_DIR/librarys/netd:libnet_manager_native", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:libeventhandler", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "NETMGR_LOG_TAG = \"EthernetManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + defines += [ "NATIVE_NETD_FEATURE" ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/services/ethernetmanager/include/dev_interface_state.h b/services/ethernetmanager/include/dev_interface_state.h new file mode 100755 index 0000000..b735237 --- /dev/null +++ b/services/ethernetmanager/include/dev_interface_state.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEV_INTERFACE_CFG_H +#define DEV_INTERFACE_CFG_H + +#include +#include + +#include "i_net_conn_service.h" +#include "dhcp_define.h" + +#include "interface_configuration.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int32_t MINIMUM_SUPPLIER_ID = 1000; +class DevInterfaceState : public virtual RefBase { + typedef enum { + REGISTERED, + UNREGISTERED, + LINK_AVAILABLE, + LINK_UNAVAILABLE + } ConnLinkState; + +public: + DevInterfaceState(); + ~DevInterfaceState(); + void SetDevName(const std::string &devName); + void SetDevHWaddr(const std::vector &hwAddr); + void SetNetCapabilities(uint64_t netCapabilities); + void SetLinkUp(bool up); + void SetLowerUp(bool lowerUp); + void SetlinkInfo(sptr &linkInfo); + void SetIfcfg(sptr &ifcfg); + void SetDhcpReqState(bool dhcpReqState); + void UpdateLinkInfo(const std::string &iface, const OHOS::Wifi::DhcpResult &result); + std::string GetDevName() const; + std::vector GetHWaddr() const; + uint64_t GetNetCapabilities() const; + bool GetLinkUp() const; + bool GetLowerUp() const; + sptr GetLinkInfo() const; + sptr GetIfcfg() const; + IPSetMode GetIPSetMode() const; + bool GetDhcpReqState() const; + + int32_t RemoteRegisterNetSupplier(); + int32_t RemoteUnregisterNetSupplier(); + int32_t RemoteUpdateNetLinkInfo(); + int32_t RemoteUpdateNetSupplierInfo(); + +private: + void UpdateLinkInfo(); + void UpdateSupplierAvailable(); + void SetIpAddr(); + +private: + ConnLinkState connLinkState_ = UNREGISTERED; + int32_t netSupplier_ = 0; + std::string devName_; + std::vector devHWaddr_; + bool linkUp_ = false; + bool lowerUp_ = false; + bool dhcpReqState_ = false; + sptr linkInfo_ = nullptr; + sptr netSupplierInfo_ = nullptr; + sptr ifcfg_ = nullptr; + const NetworkType networkType_ = NET_TYPE_ETHERNET; + uint64_t netCapabilities_ = NET_CAPABILITIES_INTERNET; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // DEV_INTERFACE_CFG_H \ No newline at end of file diff --git a/services/ethernetmanager/include/ethernet_management.h b/services/ethernetmanager/include/ethernet_management.h new file mode 100755 index 0000000..50f9858 --- /dev/null +++ b/services/ethernetmanager/include/ethernet_management.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ETHERNET_MANAGEMENT_H +#define ETHERNET_MANAGEMENT_H + +#include +#include + +#include "iservice_registry.h" +#include "i_dhcp_result_notify.h" +#include "dhcp_service.h" +#include "system_ability_definition.h" + +#include "dev_interface_state.h" +#include "nlk_event_handle.h" +#include "netLink_rtnl.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int32_t DHCP_TIMEOUT = 60; +class EthernetManagement : public NlkEventHandle { +public: + class EthDhcpResultNotify : public OHOS::Wifi::IDhcpResultNotify { + public: + explicit EthDhcpResultNotify(EthernetManagement ðernetManagement); + ~EthDhcpResultNotify() override; + void OnSuccess(int status, const std::string &ifname, OHOS::Wifi::DhcpResult &result) override; + void OnFailed(int status, const std::string &ifname, const std::string &reason) override; + void OnSerExitNotify(const std::string& ifname) override; + + private: + EthernetManagement ðernetManagement_; + }; + +public: + EthernetManagement(); + ~EthernetManagement(); + void Init(); + void UpdateInterfaceState(const std::string &dev, bool up, bool lowerUp); + int32_t UpdateDevInterfaceState(const std::string &iface, sptr cfg); + int32_t UpdateDevInterfaceLinkInfo(const std::string &iface, const OHOS::Wifi::DhcpResult &result); + sptr GetDevInterfaceCfg(const std::string &iface); + int32_t IsActivate(const std::string &iface); + std::vector GetActivateInterfaces(); + void RegisterNlk(NetLinkRtnl &nlk); + void Handle(const struct NlkEventInfo &info) override; + +private: + sptr netConnService_ = nullptr; + std::map> devs_; + std::unique_ptr dhcpService_ = nullptr; + std::unique_ptr dhcpResultNotify_ = nullptr; + std::mutex mutex_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // ETHERNET_MANAGEMENT_H \ No newline at end of file diff --git a/services/ethernetmanager/include/ethernet_service.h b/services/ethernetmanager/include/ethernet_service.h new file mode 100755 index 0000000..9abcbb0 --- /dev/null +++ b/services/ethernetmanager/include/ethernet_service.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ETHERNET_SERVICE_H +#define ETHERNET_SERVICE_H + +#include "singleton.h" +#include "system_ability.h" + +#include "ipc/ethernet_service_stub.h" +#include "ethernet_management.h" + +namespace OHOS { +namespace NetManagerStandard { +class EthernetService : public SystemAbility, public EthernetServiceStub, + public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(EthernetService) + DECLARE_SYSTEM_ABILITY(EthernetService) + + enum ServiceRunningState { + STATE_STOPPED = 0, + STATE_RUNNING, + }; + +public: + void OnStart() override; + void OnStop() override; + + int32_t SetIfaceConfig(const std::string &iface, sptr &ic) override; + sptr GetIfaceConfig(const std::string &iface) override; + int32_t IsActivate(const std::string &iface) override; + std::vector GetActivateInterfaces() override; + +private: + bool Init(); + +private: + ServiceRunningState state_ = ServiceRunningState::STATE_STOPPED; + bool registerToService_ = false; + std::unique_ptr ethManagement_; + NetLinkRtnl nlkRtnl_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // ETHERNET_SERVICE_H \ No newline at end of file diff --git a/services/ethernetmanager/include/ipc/ethernet_service_proxy.h b/services/ethernetmanager/include/ipc/ethernet_service_proxy.h new file mode 100755 index 0000000..8732b7a --- /dev/null +++ b/services/ethernetmanager/include/ipc/ethernet_service_proxy.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ETHERNET_SERVICE_PROXY_H +#define ETHERNET_SERVICE_PROXY_H + +#include + +#include "iremote_proxy.h" +#include "i_ethernet_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class EthernetServiceProxy : public IRemoteProxy { +public: + explicit EthernetServiceProxy(const sptr &impl); + virtual ~EthernetServiceProxy(); + bool WriteInterfaceToken(MessageParcel &data); + + int32_t SetIfaceConfig(const std::string &iface, sptr &ic) override; + sptr GetIfaceConfig(const std::string &iface) override; + int32_t IsActivate(const std::string &iface) override; + std::vector GetActivateInterfaces() override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // ETHERNET_SERVICE_PROXY_H \ No newline at end of file diff --git a/services/ethernetmanager/include/ipc/ethernet_service_stub.h b/services/ethernetmanager/include/ipc/ethernet_service_stub.h new file mode 100755 index 0000000..343c362 --- /dev/null +++ b/services/ethernetmanager/include/ipc/ethernet_service_stub.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ETHERNET_SERVICE_STUB_H +#define ETHERNET_SERVICE_STUB_H + +#include +#include "iremote_stub.h" +#include "i_ethernet_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class EthernetServiceStub : public IRemoteStub { + using EthernetServiceFunc = int32_t (EthernetServiceStub::*)(MessageParcel &, MessageParcel &); + +public: + EthernetServiceStub(); + ~EthernetServiceStub(); + int32_t OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t OnSetIfaceConfig(MessageParcel &data, MessageParcel &reply); + int32_t OnGetIfaceConfig(MessageParcel &data, MessageParcel &reply); + int32_t OnIsActivate(MessageParcel &data, MessageParcel &reply); + int32_t OnGetActivateInterfaces(MessageParcel &data, MessageParcel &reply); + +private: + std::map memberFuncMap_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // ETHERNET_SERVICE_STUB_H + diff --git a/services/ethernetmanager/include/ipc/i_ethernet_service.h b/services/ethernetmanager/include/ipc/i_ethernet_service.h new file mode 100755 index 0000000..21120b0 --- /dev/null +++ b/services/ethernetmanager/include/ipc/i_ethernet_service.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_ETHERNET_SERVICE_H +#define I_ETHERNET_SERVICE_H + +#include +#include + +#include "iremote_broker.h" +#include "iremote_object.h" + +#include "interface_configuration.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int32_t GET_CFG_SUC = 1; +class IEthernetService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.NetManagerStandard.IEthernetService"); + enum { + CMD_SET_IF_CFG, + CMD_GET_IF_CFG, + CMD_IS_ACTIVATE, + CMD_GET_ACTIVATE_INTERFACE, + }; + +public: + virtual int32_t SetIfaceConfig(const std::string &iface, sptr &ic) = 0; + virtual sptr GetIfaceConfig(const std::string &iface) = 0; + virtual int32_t IsActivate(const std::string &iface) = 0; + virtual std::vector GetActivateInterfaces() = 0; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // I_ETHERNET_SERVICE_H \ No newline at end of file diff --git a/services/ethernetmanager/include/netLink_rtnl.h b/services/ethernetmanager/include/netLink_rtnl.h new file mode 100755 index 0000000..f7847ed --- /dev/null +++ b/services/ethernetmanager/include/netLink_rtnl.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETLINK_RTNL_H +#define NETLINK_RTNL_H + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "nlk_event_handle.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int32_t NLK_SOCK_BUF_LEN = 20480; +constexpr int32_t NLK_BUFF_LEN = 2048; +constexpr int32_t NLK_HWADDR_BUF_LEN = 16; +constexpr int32_t NLK_HWADDR_LEN = 6; +constexpr int32_t NLK_TV_SEC = 5; +constexpr int32_t NLK_TV_USEC = 0; +class NetLinkRtnl { +public: + NetLinkRtnl(); + ~NetLinkRtnl(); + void NetLinkListenerThead(); + void Init(); + void RegisterHandle(sptr h); + static int32_t SetIpAddr(const std::string &ifName, const std::string &ip); + static std::vector GetHWaddr(const std::string &devName); + static void GetLinkInfo(std::vector &infos); + +private: + static int32_t CreateNetLinkSocket(); + static int32_t NetLinkSendMsg(int32_t fd, struct nlmsghdr &nlh); + static void ProcessReadMsg(std::unique_ptr &pBuff, int32_t len, std::vector &infos); + static NlkEventInfo ProcessLinkMsg(const struct nlmsghdr &nh); + int NetLinkHandle(int32_t netLinkSocket, fd_set& rdSet, struct timeval& timeout); + void ProcessIfInfoMsg(const struct nlmsghdr &nh); + void ProcessLinkEventMsg(std::unique_ptr &pBuff, int32_t len); + +private: + std::list> nlkHandles_; + static int32_t seq_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NETLINK_RTNL_H \ No newline at end of file diff --git a/services/ethernetmanager/include/nlk_event_handle.h b/services/ethernetmanager/include/nlk_event_handle.h new file mode 100755 index 0000000..6818c21 --- /dev/null +++ b/services/ethernetmanager/include/nlk_event_handle.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NLK_EVENT_HANDLE_H +#define NLK_EVENT_HANDLE_H + +#include + +#include "refbase.h" + +namespace OHOS { +namespace NetManagerStandard { +struct NlkEventInfo { + std::string iface_; + uint64_t ifiFlags_ = 0; +}; + +class NlkEventHandle : public virtual RefBase { +public: + virtual void Handle(const struct NlkEventInfo &info) = 0; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NLK_EVENT_HANDLE_H \ No newline at end of file diff --git a/services/ethernetmanager/src/dev_interface_state.cpp b/services/ethernetmanager/src/dev_interface_state.cpp new file mode 100755 index 0000000..8d74934 --- /dev/null +++ b/services/ethernetmanager/src/dev_interface_state.cpp @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dev_interface_state.h" + +#include "net_conn_client.h" +#include "net_mgr_log_wrapper.h" + +#include "netLink_rtnl.h" +#include "ethernet_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +DevInterfaceState::DevInterfaceState() +{ + netSupplierInfo_ = std::make_unique().release(); +} + +DevInterfaceState::~DevInterfaceState() {} + +void DevInterfaceState::SetDevName(const std::string &devName) +{ + devName_ = devName; +} + +void DevInterfaceState::SetDevHWaddr(const std::vector &hwAddr) +{ + devHWaddr_ = hwAddr; +} + +void DevInterfaceState::SetNetCapabilities(uint64_t netCapabilities) +{ + netCapabilities_ = netCapabilities; +} + +void DevInterfaceState::SetLinkUp(bool up) +{ + linkUp_ = up; +} + +void DevInterfaceState::SetLowerUp(bool lowerUp) +{ + lowerUp_ = lowerUp; +} + +void DevInterfaceState::SetlinkInfo(sptr &linkInfo) +{ + linkInfo_ = linkInfo; +} + +void DevInterfaceState::SetIfcfg(sptr &ifcfg) +{ + ifcfg_ = ifcfg; + if (ifcfg_->mode_ == STATIC) { + UpdateLinkInfo(); + SetIpAddr(); + if (connLinkState_ == LINK_AVAILABLE) { + RemoteUpdateNetLinkInfo(); + } + } +} + +void DevInterfaceState::SetDhcpReqState(bool dhcpReqState) +{ + dhcpReqState_ = dhcpReqState; +} + +std::string DevInterfaceState::GetDevName() const +{ + return devName_; +} + +std::vector DevInterfaceState::GetHWaddr() const +{ + return devHWaddr_; +} + +uint64_t DevInterfaceState::GetNetCapabilities() const +{ + return netCapabilities_; +} + +bool DevInterfaceState::GetLinkUp() const +{ + return linkUp_; +} + +bool DevInterfaceState::GetLowerUp() const +{ + return lowerUp_; +} + +sptr DevInterfaceState::GetLinkInfo() const +{ + return linkInfo_; +} + +sptr DevInterfaceState::GetIfcfg() const +{ + return ifcfg_; +} + +IPSetMode DevInterfaceState::GetIPSetMode() const +{ + if (ifcfg_ == nullptr) { + return IPSetMode::STATIC; + } + return ifcfg_->mode_; +} + +bool DevInterfaceState::GetDhcpReqState() const +{ + return dhcpReqState_; +} + +int32_t DevInterfaceState::RemoteRegisterNetSupplier() +{ + if (connLinkState_ == UNREGISTERED) { + netSupplier_ = DelayedSingleton::GetInstance()->RegisterNetSupplier(networkType_, + devName_, netCapabilities_); + if (netSupplier_ > MINIMUM_SUPPLIER_ID) { + connLinkState_ = REGISTERED; + } + NETMGR_LOGI("DevInterfaceCfg RemoteRegisterNetSupplier netSupplier_[%{public}d]", netSupplier_); + } + return netSupplier_; +} + +int32_t DevInterfaceState::RemoteUnregisterNetSupplier() +{ + if (connLinkState_ == UNREGISTERED) { + return NETMANAGER_ERROR; + } + int ret = DelayedSingleton::GetInstance()->UnregisterNetSupplier(netSupplier_); + if (!ret) { + connLinkState_ = UNREGISTERED; + netSupplier_ = 0; + } + return ret; +} + +int32_t DevInterfaceState::RemoteUpdateNetLinkInfo() +{ + if (connLinkState_ == LINK_UNAVAILABLE) { + NETMGR_LOGE("DevInterfaceCfg RemoteUpdateNetLinkInfo regState_:LINK_UNAVAILABLE"); + return NETMANAGER_ERROR; + } + if (linkInfo_ == nullptr) { + NETMGR_LOGE("DevInterfaceCfg RemoteUpdateNetLinkInfo linkInfo_ is nullptr"); + return NETMANAGER_ERROR; + } + return DelayedSingleton::GetInstance()->UpdateNetLinkInfo(netSupplier_, linkInfo_); +} + +int32_t DevInterfaceState::RemoteUpdateNetSupplierInfo() +{ + if (connLinkState_ == UNREGISTERED) { + NETMGR_LOGE("DevInterfaceCfg RemoteUpdateNetSupplierInfo regState_:UNREGISTERED"); + return NETMANAGER_ERROR; + } + if (netSupplierInfo_ == nullptr) { + NETMGR_LOGE("DevInterfaceCfg RemoteUpdateNetSupplierInfo netSupplierInfo_ is nullptr"); + return NETMANAGER_ERROR; + } + UpdateSupplierAvailable(); + return DelayedSingleton::GetInstance()->UpdateNetSupplierInfo(netSupplier_, netSupplierInfo_); +} + +void DevInterfaceState::UpdateLinkInfo() +{ + if (!ifcfg_ && ifcfg_->mode_ != STATIC) { + return; + } + if (linkInfo_ == nullptr) { + linkInfo_ = std::make_unique().release(); + } + std::list().swap(linkInfo_->netAddrList_); + std::list().swap(linkInfo_->routeList_); + std::list().swap(linkInfo_->dnsList_); + linkInfo_->netAddrList_.push_back(ifcfg_->ipStatic_.ipAddr_); + struct Route route; + route.iface_ = devName_; + route.destination_ = ifcfg_->ipStatic_.route_; + route.gateway_ = ifcfg_->ipStatic_.gate_; + linkInfo_->routeList_.push_back(route); + for (auto it = ifcfg_->ipStatic_.dnsServers_.begin(); it != ifcfg_->ipStatic_.dnsServers_.end(); ++it) { + linkInfo_->dnsList_.push_back(*it); + } +} + +void DevInterfaceState::UpdateLinkInfo(const std::string &iface, const OHOS::Wifi::DhcpResult &result) +{ + NETMGR_LOGI("DevInterfaceCfg::UpdateLinkInfo"); + if (linkInfo_ == nullptr) { + linkInfo_ = std::make_unique().release(); + } + std::list().swap(linkInfo_->netAddrList_); + std::list().swap(linkInfo_->routeList_); + INetAddr ipAddr; + ipAddr.type_ = result.iptype; + ipAddr.address_ = result.strYourCli; + linkInfo_->netAddrList_.push_back(ipAddr); + struct Route route; + INetAddr gate; + INetAddr destination; + route.iface_ = iface; + if (result.strServer != result.strRouter1) { + gate.address_ = result.strServer; + if (result.strRouter1 == "*") { + destination.address_ = "0.0.0.0"; + } else { + destination.address_ = result.strRouter1; + } + route.destination_ = destination; + route.gateway_ = gate; + linkInfo_->routeList_.push_back(route); + } + if (result.strServer != result.strRouter2) { + gate.address_ = result.strServer; + if (result.strRouter2 == "*") { + destination.address_ = "0.0.0.0"; + } else { + destination.address_ = result.strRouter2; + } + route.destination_ = destination; + route.gateway_ = gate; + linkInfo_->routeList_.push_back(route); + } + ipAddr.address_ = result.strDns1; + linkInfo_->dnsList_.push_back(ipAddr); + ipAddr.address_ = result.strDns2; + linkInfo_->dnsList_.push_back(ipAddr); +} + +void DevInterfaceState::SetIpAddr() +{ + NetLinkRtnl::SetIpAddr(devName_, ifcfg_->ipStatic_.ipAddr_.address_); +} + +void DevInterfaceState::UpdateSupplierAvailable() +{ + bool isAvailable = linkUp_ & lowerUp_; + netSupplierInfo_->isAvailable_ = isAvailable; + if (isAvailable) { + connLinkState_ = LINK_AVAILABLE; + } else { + connLinkState_ = LINK_UNAVAILABLE; + } +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/ethernetmanager/src/ethernet_management.cpp b/services/ethernetmanager/src/ethernet_management.cpp new file mode 100755 index 0000000..c729a43 --- /dev/null +++ b/services/ethernetmanager/src/ethernet_management.cpp @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ethernet_management.h" + +#include "net_mgr_log_wrapper.h" +#include "ethernet_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +EthernetManagement::EthDhcpResultNotify::EthDhcpResultNotify(EthernetManagement ðernetManagement) + : ethernetManagement_(ethernetManagement) +{ +} + +EthernetManagement::EthDhcpResultNotify::~EthDhcpResultNotify() {} + +void EthernetManagement::EthDhcpResultNotify::OnSuccess(int status, const std::string &ifname, + OHOS::Wifi::DhcpResult &result) +{ + NETMGR_LOGI("Enter EthernetManagement::EthDhcpResultNotify::OnSuccess " + "ifname=[%{public}s], iptype=[%{public}d], strYourCli=[%{public}s], " + "strServer=[%{public}s], strSubnet=[%{public}s], strDns1=[%{public}s], " + "strDns2=[%{public}s] strRouter1=[%{public}s] strRouter2=[%{public}s]", + ifname.c_str(), result.iptype, result.strYourCli.c_str(), result.strServer.c_str(), result.strSubnet.c_str(), + result.strDns1.c_str(), result.strDns2.c_str(), result.strRouter1.c_str(), result.strRouter2.c_str()); + ethernetManagement_.UpdateDevInterfaceLinkInfo(ifname, result); + return; +} + +void EthernetManagement::EthDhcpResultNotify::OnFailed(int status, const std::string &ifname, const std::string &reason) +{ + NETMGR_LOGI("Enter EthernetManagement::EthDhcpResultNotify::OnFailed"); + return; +} + +void EthernetManagement::EthDhcpResultNotify::OnSerExitNotify(const std::string& ifname) +{ + NETMGR_LOGI("EthernetManagement::EthDhcpResultNotify::OnSerExitNotify"); + return; +} + +EthernetManagement::EthernetManagement() +{ + dhcpService_.reset(std::make_unique().release()); + dhcpResultNotify_.reset(std::make_unique(*this).release()); +} + +EthernetManagement::~EthernetManagement() {} + +void EthernetManagement::UpdateInterfaceState(const std::string &dev, bool up, bool lowerUp) +{ + NETMGR_LOGI("EthernetManagement UpdateInterfaceState dev[%{public}s] up[%{public}d] lowerUp[%{public}d]", + dev.c_str(), up, lowerUp); + std::unique_lock lock(mutex_); + auto fit = devs_.find(dev); + if (fit == devs_.end()) { + return; + } + sptr devState= fit->second; + devState->SetLinkUp(up); + devState->SetLowerUp(lowerUp); + IPSetMode mode = devState->GetIPSetMode(); + bool dhcpReqState = devState->GetDhcpReqState(); + NETMGR_LOGI("EthernetManagement UpdateInterfaceState mode[%{public}d] dhcpReqState[%{public}d]", + static_cast(mode), dhcpReqState); + if (lowerUp) { + devState->RemoteUpdateNetSupplierInfo(); + if (mode == DHCP && !dhcpReqState) { + NETMGR_LOGI("EthernetManagement StartDhcpClient[%{public}s]", dev.c_str()); + if (dhcpService_ == nullptr) { + NETMGR_LOGE("EthernetManagement::UpdateInterfaceState dhcpService_ is nullptr"); + return; + } + dhcpService_->StartDhcpClient(dev, false); + if (dhcpService_->GetDhcpResult(dev, dhcpResultNotify_.get(), DHCP_TIMEOUT) != 0) { + NETMGR_LOGE(" Dhcp connection failed.\n"); + } + devState->SetDhcpReqState(true); + } else { + devState->RemoteUpdateNetLinkInfo(); + } + } else { + if (mode == DHCP && dhcpReqState) { + NETMGR_LOGI("EthernetManagement StopDhcpClient[%{public}s]", dev.c_str()); + if (dhcpService_ == nullptr) { + NETMGR_LOGI("EthernetManagement::UpdateInterfaceState dhcpService_ is nullptr"); + return; + } + dhcpService_->StopDhcpClient(dev, false); + devState->SetDhcpReqState(false); + } + devState->RemoteUpdateNetSupplierInfo(); + } +} + +int32_t EthernetManagement::UpdateDevInterfaceState(const std::string &iface, sptr cfg) +{ + std::unique_lock lock(mutex_); + auto fit = devs_.find(iface); + if (fit == devs_.end() || fit->second == nullptr) { + NETMGR_LOGE("The iface[%{public}s] device or device information does not exist", iface.c_str()); + return ETHERNET_ERROR; + } + if (!fit->second->GetLinkUp()) { + return ETHERNET_ERROR; + } + fit->second->SetIfcfg(cfg); + return ETHERNET_SUCCESS; +} + +int32_t EthernetManagement::UpdateDevInterfaceLinkInfo(const std::string &iface, const OHOS::Wifi::DhcpResult &result) +{ + NETMGR_LOGI("EthernetManagement::UpdateDevInterfaceLinkInfo"); + std::unique_lock lock(mutex_); + auto fit = devs_.find(iface); + if (fit == devs_.end() || fit->second == nullptr) { + NETMGR_LOGE("The iface[%{public}s] device or device information does not exist", iface.c_str()); + return ETHERNET_ERROR; + } + if (!fit->second->GetLinkUp()) { + return ETHERNET_ERROR; + } + fit->second->UpdateLinkInfo(iface, result); + fit->second->RemoteUpdateNetLinkInfo(); + return ETHERNET_SUCCESS; +} + +sptr EthernetManagement::GetDevInterfaceCfg(const std::string &iface) +{ + std::unique_lock lock(mutex_); + auto fit = devs_.find(iface); + if (fit == devs_.end() || fit->second == nullptr) { + NETMGR_LOGE("The iface[%{public}s] device does not exist", iface.c_str()); + return nullptr; + } + return fit->second->GetIfcfg(); +} + +int32_t EthernetManagement::IsActivate(const std::string &iface) +{ + std::unique_lock lock(mutex_); + auto fit = devs_.find(iface); + if (fit == devs_.end() || fit->second == nullptr) { + NETMGR_LOGE("The iface[%{public}s] device does not exist", iface.c_str()); + return ETHERNET_ERROR; + } + return static_cast(fit->second->GetLinkUp()); +} + +std::vector EthernetManagement::GetActivateInterfaces() +{ + std::unique_lock lock(mutex_); + std::vector a; + for (auto it = devs_.begin(); it != devs_.end(); ++it) { + a.push_back(it->first); + } + return a; +} + +void EthernetManagement::RegisterNlk(NetLinkRtnl &nlk) +{ + nlk.RegisterHandle(this); +} + +void EthernetManagement::Handle(const struct NlkEventInfo &info) +{ + bool up = static_cast(info.ifiFlags_ & IFF_UP); + bool lowerUp = static_cast(info.ifiFlags_ & IFF_LOWER_UP); + NETMGR_LOGI("EthernetManagement Handle info dev[%{public}s] up[%{public}d] lowerUp[%{public}d]", + info.iface_.c_str(), up, lowerUp); + UpdateInterfaceState(info.iface_, up, lowerUp); +} + +void EthernetManagement::Init() +{ + std::vector linkInfos; + NetLinkRtnl::GetLinkInfo(linkInfos); + if (linkInfos.size() <= 0) { + NETMGR_LOGE("EthernetManagement link list is empty"); + return; + } + NETMGR_LOGI("EthernetManagement devs size[%{public}d]", linkInfos.size()); + for (auto it = linkInfos.begin(); it != linkInfos.end(); it++) { + std::string devName = it->iface_; + NETMGR_LOGI("EthernetManagement devName[%{public}s]", devName.c_str()); + if (devName.empty()) { + continue; + } + sptr devState = std::make_unique().release(); + devs_.insert(std::make_pair(devName, devState)); + sptr ifCfg = std::make_unique().release(); + ifCfg->mode_ = STATIC; + devState->SetIfcfg(ifCfg); + std::vector hwAddr = NetLinkRtnl::GetHWaddr(devName); + bool up = it->ifiFlags_ & IFF_UP; + bool lowerUp = it->ifiFlags_ & IFF_LOWER_UP; + devState->SetDevName(devName); + devState->SetDevHWaddr(hwAddr); + devState->SetLinkUp(up); + devState->SetLowerUp(lowerUp); + devState->RemoteRegisterNetSupplier(); + if (up && lowerUp) { + devState->RemoteUpdateNetSupplierInfo(); + } + } + NETMGR_LOGI("EthernetManagement devs_ size[%{public}d", devs_.size()); +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/ethernetmanager/src/ethernet_service.cpp b/services/ethernetmanager/src/ethernet_service.cpp new file mode 100755 index 0000000..21dae1e --- /dev/null +++ b/services/ethernetmanager/src/ethernet_service.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ethernet_service.h" + +#include "net_mgr_log_wrapper.h" +#include "ethernet_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +const bool REGISTER_LOCAL_RESULT_ETH = SystemAbility::MakeAndRegisterAbility( + DelayedSingleton::GetInstance().get()); + +EthernetService::EthernetService() + : SystemAbility(COMM_ETHERNET_MANAGER_SYS_ABILITY_ID, true) +{ + ethManagement_ = std::make_unique(); +} + +EthernetService::~EthernetService() {} + +void EthernetService::OnStart() +{ + NETMGR_LOGI("EthernetService::OnStart"); + if (state_ == STATE_RUNNING) { + NETMGR_LOGI("EthernetService the state is already running"); + return; + } + if (!Init()) { + NETMGR_LOGE("EthernetService init failed"); + return; + } + nlkRtnl_.Init(); + if (ethManagement_ != nullptr) { + ethManagement_->Init(); + ethManagement_->RegisterNlk(nlkRtnl_); + } + state_ = STATE_RUNNING; +} + +void EthernetService::OnStop() +{ + state_ = STATE_STOPPED; + registerToService_ = false; +} + +bool EthernetService::Init() +{ + if (!REGISTER_LOCAL_RESULT_ETH) { + NETMGR_LOGE("EthernetService Register to local sa manager failed"); + return false; + } + if (!registerToService_) { + if (!Publish(DelayedSingleton::GetInstance().get())) { + NETMGR_LOGE("EthernetService Register to sa manager failed"); + return false; + } + registerToService_ = true; + } + NETMGR_LOGI("GetEthernetServer suc"); + return true; +} + +int32_t EthernetService::SetIfaceConfig(const std::string &iface, sptr &ic) +{ + NETMGR_LOGI("EthernetService SetIfaceConfig processing"); + if (ethManagement_ != nullptr) { + return ethManagement_->UpdateDevInterfaceState(iface, ic); + } else { + return ETHERNET_ERROR; + } +} + +sptr EthernetService::GetIfaceConfig(const std::string &iface) +{ + NETMGR_LOGI("EthernetService GetIfaceConfig processing"); + if (ethManagement_ != nullptr) { + return ethManagement_->GetDevInterfaceCfg(iface); + } else { + return nullptr; + } +} + +int32_t EthernetService::IsActivate(const std::string &iface) +{ + if (ethManagement_ != nullptr) { + return ethManagement_->IsActivate(iface); + } else { + return ETHERNET_ERROR; + } +} + +std::vector EthernetService::GetActivateInterfaces() +{ + if (ethManagement_ != nullptr) { + return ethManagement_->GetActivateInterfaces(); + } else { + return {}; + } +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/ethernetmanager/src/ipc/ethernet_service_proxy.cpp b/services/ethernetmanager/src/ipc/ethernet_service_proxy.cpp new file mode 100755 index 0000000..f42fc2f --- /dev/null +++ b/services/ethernetmanager/src/ipc/ethernet_service_proxy.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ethernet_service_proxy.h" +#include "ipc_types.h" +#include "net_mgr_log_wrapper.h" +#include "ethernet_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +EthernetServiceProxy::EthernetServiceProxy(const sptr &impl) + :IRemoteProxy(impl) +{ +} + +EthernetServiceProxy::~EthernetServiceProxy() {} + +bool EthernetServiceProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(EthernetServiceProxy::GetDescriptor())) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return false; + } + return true; +} + +int32_t EthernetServiceProxy::SetIfaceConfig(const std::string &iface, sptr &ic) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteString(iface)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!ic->Marshalling(data)) { + NETMGR_LOGE("proxy Marshalling failed"); + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_SET_IF_CFG, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + return reply.ReadInt32(); +} + +sptr EthernetServiceProxy::GetIfaceConfig(const std::string &iface) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return nullptr; + } + if (!data.WriteString(iface)) { + return nullptr; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return nullptr; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_GET_IF_CFG, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return nullptr; + } + int32_t res = 0; + if (!reply.ReadInt32(res)) { + return nullptr; + } + if (res != GET_CFG_SUC) { + return nullptr; + } + return InterfaceConfiguration::Unmarshalling(reply); +} + +int32_t EthernetServiceProxy::IsActivate(const std::string &iface) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + if (!data.WriteString(iface)) { + return NETMANAGER_ERR_WRITE_DESCRIPTOR_TOKEN_FAIL; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_IS_ACTIVATE, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return NETMANAGER_ERR_IPC_CONNECT_STUB_FAIL; + } + + return reply.ReadInt32(); +} + +std::vector EthernetServiceProxy::GetActivateInterfaces() +{ + MessageParcel data; + std::vector ifaces; + if (!WriteInterfaceToken(data)) { + return ifaces; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return ifaces; + } + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(CMD_GET_ACTIVATE_INTERFACE, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", ret); + return ifaces; + } + + int32_t size = reply.ReadInt32(); + for (int i = 0; i < size; i++) { + ifaces.push_back(reply.ReadString()); + } + return ifaces; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/ethernetmanager/src/ipc/ethernet_service_stub.cpp b/services/ethernetmanager/src/ipc/ethernet_service_stub.cpp new file mode 100755 index 0000000..7568b5d --- /dev/null +++ b/services/ethernetmanager/src/ipc/ethernet_service_stub.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ethernet_service_stub.h" +#include "net_mgr_log_wrapper.h" +#include "ethernet_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +EthernetServiceStub::EthernetServiceStub() +{ + memberFuncMap_[CMD_SET_IF_CFG] = &EthernetServiceStub::OnSetIfaceConfig; + memberFuncMap_[CMD_GET_IF_CFG] = &EthernetServiceStub::OnGetIfaceConfig; + memberFuncMap_[CMD_IS_ACTIVATE] = &EthernetServiceStub::OnIsActivate; + memberFuncMap_[CMD_GET_ACTIVATE_INTERFACE] = &EthernetServiceStub::OnGetActivateInterfaces; +} + +EthernetServiceStub::~EthernetServiceStub() {} + +int32_t EthernetServiceStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + NETMGR_LOGI("stub call start, code = [%{public}d]", code); + + std::u16string myDescripter = EthernetServiceStub::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (myDescripter != remoteDescripter) { + NETMGR_LOGE("descriptor checked fail"); + return NETMANAGER_ERR_DESCRIPTOR_MISMATCH; + } + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + + NETMGR_LOGI("stub default case, need check"); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t EthernetServiceStub::OnSetIfaceConfig(MessageParcel &data, MessageParcel &reply) +{ + std::string iface; + if (!data.ReadString(iface)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + sptr ic = InterfaceConfiguration::Unmarshalling(data); + if (ic == nullptr) { + return NETMANAGER_ERR_LOCAL_PTR_NULL; + } + int32_t ret = SetIfaceConfig(iface, ic); + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t EthernetServiceStub::OnGetIfaceConfig(MessageParcel &data, MessageParcel &reply) +{ + std::string iface; + if (!data.ReadString(iface)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + sptr ic = GetIfaceConfig(iface); + if (ic != nullptr) { + if (!reply.WriteInt32(GET_CFG_SUC)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + if (!ic->Marshalling(reply)) { + NETMGR_LOGE("proxy Marshalling failed"); + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + } else { + if (!reply.WriteInt32(0)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + } + return NETMANAGER_SUCCESS; +} + +int32_t EthernetServiceStub::OnIsActivate(MessageParcel &data, MessageParcel &reply) +{ + std::string iface; + if (!data.ReadString(iface)) { + return NETMANAGER_ERR_READ_DATA_FAIL; + } + int32_t ret = IsActivate(iface); + if (!reply.WriteInt32(ret)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + return NETMANAGER_SUCCESS; +} + +int32_t EthernetServiceStub::OnGetActivateInterfaces(MessageParcel &data, MessageParcel &reply) +{ + std::vector ifaces = GetActivateInterfaces(); + if (!reply.WriteInt32(ifaces.size())) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + for (auto it = ifaces.begin(); it != ifaces.end(); ++it) { + if (!reply.WriteString(*it)) { + return NETMANAGER_ERR_WRITE_REPLY_FAIL; + } + } + return NETMANAGER_SUCCESS; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/ethernetmanager/src/netLink_rtnl.cpp b/services/ethernetmanager/src/netLink_rtnl.cpp new file mode 100755 index 0000000..8b60e2e --- /dev/null +++ b/services/ethernetmanager/src/netLink_rtnl.cpp @@ -0,0 +1,342 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "netLink_rtnl.h" + +#include + +#include "securec.h" +#include "net_mgr_log_wrapper.h" +#include "ethernet_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +int32_t NetLinkRtnl::seq_ = 0; +NetLinkRtnl::NetLinkRtnl() +{ +} + +NetLinkRtnl::~NetLinkRtnl() {} + +void NetLinkRtnl::NetLinkListenerThead() +{ + int32_t netLinkSocket = 0; + netLinkSocket = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); + if (netLinkSocket < 0) { + NETMGR_LOGE("NetLinkRtnl NetLinkListenerThead netLinkSocket create socket failed"); + return; + } + if (setsockopt(netLinkSocket, SOL_SOCKET, SO_RCVBUF, &NLK_SOCK_BUF_LEN, sizeof(NLK_SOCK_BUF_LEN)) != 0) { + NETMGR_LOGE("NetLinkRtnl NetLinkListenerThead setsockopt failed"); + return; + } + struct sockaddr_nl sa; + bzero(&sa, sizeof(sa)); + sa.nl_family = AF_NETLINK; + sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_ROUTE; + if (bind(netLinkSocket, (struct sockaddr *) &sa, sizeof(sa)) != 0) { + NETMGR_LOGE("NetLinkRtnl NetLinkListenerThead bind failed"); + return; + } + fd_set rdSet; + struct timeval timeout; + timeout.tv_sec = NLK_TV_SEC; + timeout.tv_usec = NLK_TV_USEC; + NETMGR_LOGI("NetLinkRtnl NetLinkListenerThead init suc, create netLinkSocket[%{public}d]", netLinkSocket); + while (true) { + FD_ZERO(&rdSet); + FD_SET(netLinkSocket, &rdSet); + NetLinkHandle(netLinkSocket, rdSet, timeout); + } +} + +void NetLinkRtnl::Init() +{ + NETMGR_LOGI("NetLinkRtnl Init thread start"); + std::thread nlk(&NetLinkRtnl::NetLinkListenerThead, this); + nlk.detach(); + return; +} + +void NetLinkRtnl::RegisterHandle(sptr h) +{ + nlkHandles_.push_back(h); + NETMGR_LOGI("NetLinkRtnl RegisterHandle nlkHandles_ size[%{public}d]", nlkHandles_.size()); +} + +void NetLinkRtnl::ProcessIfInfoMsg(const struct nlmsghdr &nh) +{ + NETMGR_LOGI("NetLinkRtnl ProcessIfInfoMsg process"); + int32_t len = 0; + struct rtattr *tb[IFLA_MAX + 1]; + struct ifinfomsg *ifInfo = nullptr; + bzero(tb, sizeof(tb)); + ifInfo = reinterpret_cast(NLMSG_DATA(&nh)); + if (ifInfo->ifi_type != ARPHRD_ETHER) { + NETMGR_LOGE("NetLinkRtnl ProcessIfInfoMsg ifi_type is not ARPHRD_ETHER"); + return; + } + len = nh.nlmsg_len - NLMSG_SPACE(sizeof(*ifInfo)); + auto attr = IFLA_RTA(ifInfo); + for (; RTA_OK(attr, len); attr = RTA_NEXT(attr, len)) { + if (attr->rta_type <= IFLA_MAX) { + tb[attr->rta_type] = attr; + } + } + NlkEventInfo info; + if (tb[IFLA_IFNAME]) { + info.iface_ = std::string(reinterpret_cast(RTA_DATA(tb[IFLA_IFNAME]))); + } + info.ifiFlags_ = ifInfo->ifi_flags; + for (auto it = nlkHandles_.begin(); it != nlkHandles_.end(); ++it) { + (*it)->Handle(info); + } +} + +void NetLinkRtnl::ProcessLinkEventMsg(std::unique_ptr &pBuff, int32_t len) +{ + struct nlmsghdr *nh = nullptr; + if (!pBuff) { + return; + } + for (nh = reinterpret_cast(pBuff.release()); NLMSG_OK(nh, len); + nh = NLMSG_NEXT(nh, len)) { + if (!nh) { + break; + } + NETMGR_LOGI("NetLinkRtnl ProcessLinkEventMsg nh nlmsg_type[%{public}d]", nh->nlmsg_type); + switch (nh->nlmsg_type) { + case RTM_NEWLINK: + case RTM_DELLINK: + ProcessIfInfoMsg(*nh); + break; + default: + break; + } // switch + } // for +} + +int NetLinkRtnl::NetLinkHandle(int32_t netLinkSocket, fd_set& rdSet, struct timeval& timeout) +{ + int32_t selectFd = select(netLinkSocket + 1, &rdSet, nullptr, nullptr, &timeout); + if (selectFd < 0) { + NETMGR_LOGE("NetLinkRtnl NetLinkHandle select failed"); + return ETHERNET_ERROR; + } else if (selectFd > 0) { + if (FD_ISSET(netLinkSocket, &rdSet)) { + int8_t buff[NLK_BUFF_LEN]; + bzero(buff, sizeof(buff)); + int readRet = read(netLinkSocket, buff, sizeof(buff)); + std::unique_ptr pBuff(buff); + ProcessLinkEventMsg(pBuff, readRet); + } // if + } // else if + return ETHERNET_SUCCESS; +} + +int32_t NetLinkRtnl::SetIpAddr(const std::string &ifName, const std::string &ip) +{ + int32_t fd = 0; + struct ifreq ifr; + fd = socket(AF_INET, SOCK_DGRAM, 0); + if (-1 == fd) { + return ETHERNET_ERROR; + } + strcpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifName.c_str()); + if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) { + close(fd); + return ETHERNET_ERROR; + } + struct sockaddr_in *sin_net_ip = nullptr; + bzero(&ifr, sizeof(ifr)); + strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifName.c_str(), sizeof(ifr.ifr_name)-1); + sin_net_ip = reinterpret_cast(&ifr.ifr_addr); + sin_net_ip->sin_family = AF_INET; + inet_pton(AF_INET, ip.c_str(), &sin_net_ip->sin_addr); + if (ioctl(fd, SIOCSIFADDR, &ifr) < 0) { + close(fd); + return ETHERNET_ERROR; + } + close(fd); + return ETHERNET_SUCCESS; +} + +std::vector NetLinkRtnl::GetHWaddr(const std::string &devName) +{ + int32_t sock = 0; + struct ifreq ifr; + uint8_t macaddr[NLK_HWADDR_BUF_LEN]; + bzero(macaddr, sizeof(macaddr)); + std::vector hwAddr; + sock=socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) { + NETMGR_LOGE("NetLinkRtnl GetHWaddr create socket error sock[%{public}d]", sock); + return hwAddr; + } + strcpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), devName.c_str()); + if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) { + NETMGR_LOGE("NetLinkRtnl GetHWaddr ioctl SIOCGIFHWADDR error"); + close(sock); + return hwAddr; + } + memcpy_s(macaddr, NLK_HWADDR_BUF_LEN, ifr.ifr_hwaddr.sa_data, NLK_HWADDR_LEN); + for (int32_t i = 0; i < NLK_HWADDR_LEN; i++) { + hwAddr.push_back(macaddr[i]); + } + close(sock); + return hwAddr; +} + +void NetLinkRtnl::GetLinkInfo(std::vector &infos) +{ + struct { + struct nlmsghdr nlh; + struct ifinfomsg ifm; + int8_t buf[NLK_BUFF_LEN]; + } req = { + .nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)), + .nlh.nlmsg_type = RTM_GETLINK, + .nlh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST, + .nlh.nlmsg_seq = ++seq_, + .ifm.ifi_family = AF_UNSPEC, + }; + int32_t fd = CreateNetLinkSocket(); + if (fd < 0) { + NETMGR_LOGE("NetLinkRtnl GetLinkInfo CreateNetLinkSocket failed"); + return; + } + int32_t ret = NetLinkSendMsg(fd, req.nlh); + if (ret < 0) { + NETMGR_LOGE("NetLinkRtnl GetLinkInfo NetLinkSendMsg failed"); + return; + } + int8_t buff[NLK_SOCK_BUF_LEN]; + bzero(buff, sizeof(buff)); + ret = read(fd, buff, sizeof(buff)); + if (ret < 0) { + NETMGR_LOGE("read failed"); + } + std::unique_ptr pBuff(buff); + ProcessReadMsg(pBuff, ret, infos); +} + +void NetLinkRtnl::ProcessReadMsg(std::unique_ptr &pBuff, int32_t len, std::vector &infos) +{ + struct nlmsghdr *nh = nullptr; + if (pBuff == nullptr) { + return; + } + for (nh = reinterpret_cast(pBuff.release()); NLMSG_OK(nh, len); + nh = NLMSG_NEXT(nh, len)) { + if (!nh) { + break; + } + NETMGR_LOGI("NetLinkRtnl ProcessReadMsg nh nlmsg_type[%{public}d]", nh->nlmsg_type); + switch (nh->nlmsg_type) { + case RTM_NEWLINK: + case RTM_DELLINK: + infos.push_back(ProcessLinkMsg(*nh)); + break; + default: + break; + } // switch + } // for +} + +NlkEventInfo NetLinkRtnl::ProcessLinkMsg(const struct nlmsghdr &nh) +{ + NETMGR_LOGI("NetLinkRtnl ProcessIfInfoMsg process"); + int32_t len = 0; + struct rtattr *tb[IFLA_MAX + 1]; + struct ifinfomsg *ifInfo = nullptr; + bzero(tb, sizeof(tb)); + NlkEventInfo info; + ifInfo = reinterpret_cast(NLMSG_DATA(&nh)); + if (ifInfo->ifi_type != ARPHRD_ETHER) { + NETMGR_LOGE("NetLinkRtnl ProcessLinkMsg ifi_type is not ARPHRD_ETHER"); + return info; + } + len = nh.nlmsg_len - NLMSG_SPACE(sizeof(*ifInfo)); + auto attr = IFLA_RTA(ifInfo); + for (; RTA_OK(attr, len); attr = RTA_NEXT(attr, len)) { + if (attr->rta_type <= IFLA_MAX) { + tb[attr->rta_type] = attr; + } + } + if (tb[IFLA_IFNAME]) { + info.iface_ = std::string(reinterpret_cast(RTA_DATA(tb[IFLA_IFNAME]))); + } + info.ifiFlags_ = ifInfo->ifi_flags; + return info; +} + +int32_t NetLinkRtnl::CreateNetLinkSocket() +{ + socklen_t addr_len = 0; + struct sockaddr_nl snl; + int32_t fd = -1; + fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); + if (fd < 0) { + NETMGR_LOGE("NetLinkRtnl CreateNetLinkSocket create socket error"); + return ETHERNET_ERROR; + } + int32_t ret = fcntl(fd, F_SETFL, O_NONBLOCK); + if (ret < 0) { + NETMGR_LOGE("NetLinkRtnl CreateNetLinkSocket fcntl error"); + close(fd); + return ETHERNET_ERROR; + } + bzero(&snl, sizeof(snl)); + snl.nl_family = AF_NETLINK; + snl.nl_groups = 0; + ret = bind(fd, reinterpret_cast(&snl), sizeof(snl)); + if (ret < 0) { + NETMGR_LOGE("NetLinkRtnl CreateNetLinkSocket bind error"); + close(fd); + return ETHERNET_ERROR; + } + addr_len = sizeof (snl); + ret = getsockname(fd, reinterpret_cast(&snl), &addr_len); + if (ret < 0 || addr_len != sizeof (snl)) { + NETMGR_LOGE("NetLinkRtnl CreateNetLinkSocket getsockname error"); + close(fd); + return ETHERNET_ERROR; + } + if (snl.nl_family != AF_NETLINK) { + NETMGR_LOGE("NetLinkRtnl CreateNetLinkSocket nl_family error"); + close(fd); + return ETHERNET_ERROR; + } + seq_ = time(NULL); + return fd; +} + +int32_t NetLinkRtnl::NetLinkSendMsg(int32_t fd, struct nlmsghdr &nlh) +{ + struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK }; + struct iovec iov = { + .iov_base = &nlh, + .iov_len = nlh.nlmsg_len + }; + struct msghdr msg = { + .msg_name = &nladdr, + .msg_namelen = sizeof(nladdr), + .msg_iov = &iov, + .msg_iovlen = 1, + }; + return sendmsg(fd, &msg, 0); +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/ethernetmanager/test/BUILD.gn b/services/ethernetmanager/test/BUILD.gn new file mode 100755 index 0000000..fb8d040 --- /dev/null +++ b/services/ethernetmanager/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +group("unittest") { + testonly = true + deps = [] + deps += [ "unittest/ethernet_manager_test:unittest" ] +} diff --git a/services/ethernetmanager/test/unittest/ethernet_manager_test/BUILD.gn b/services/ethernetmanager/test/unittest/ethernet_manager_test/BUILD.gn new file mode 100755 index 0000000..b1c2e44 --- /dev/null +++ b/services/ethernetmanager/test/unittest/ethernet_manager_test/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +ohos_unittest("ethernet_manager_test") { + module_out_path = "netmanager_base/ethernet_manager_test" + + sources = [ + "$NETMANAGER_PREBUILTS_DIR/src/ipc/ethernet_service_proxy.cpp", + "ethernet_manager_test.cpp", + ] + + include_dirs = [ + "$INNERKITS_ROOT/native/ethernetmanager/include", + "$INNERKITS_ROOT/native/ethernetmanager/include/ipc", + "$NETMANAGER_PREBUILTS_DIR/include/ipc", + "$NETMANAGER_PREBUILTS_DIR/include", + ] + + deps = [ + "$INNERKITS_ROOT/native/ethernetmanager:ethernet_manager_if", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "$NETMANAGER_PREBUILTS_DIR:ethernet_manager", + ] + + external_deps = [ "ipc:ipc_core" ] + + defines = [ + "NETMGR_LOG_TAG = \"EthernetManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":ethernet_manager_test" ] +} diff --git a/services/ethernetmanager/test/unittest/ethernet_manager_test/ethernet_manager_test.cpp b/services/ethernetmanager/test/unittest/ethernet_manager_test/ethernet_manager_test.cpp new file mode 100755 index 0000000..e87822d --- /dev/null +++ b/services/ethernetmanager/test/unittest/ethernet_manager_test/ethernet_manager_test.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "ethernet_client.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +using namespace testing::ext; +class EthernetManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + sptr GetIfaceConfig(); +}; + +void EthernetManagerTest::SetUpTestCase() {} + +void EthernetManagerTest::TearDownTestCase() {} + +void EthernetManagerTest::SetUp() {} + +void EthernetManagerTest::TearDown() {} + +sptr EthernetManagerTest::GetIfaceConfig() +{ + sptr ic = (std::make_unique()).release(); + if (!ic) { + return ic; + } + ic->ipStatic_.ipAddr_.type_ = INetAddr::IPV4; + ic->ipStatic_.ipAddr_.family_ = 0x01; + ic->ipStatic_.ipAddr_.prefixlen_ = 0x01; + ic->ipStatic_.ipAddr_.address_ = "172.17.5.234"; + ic->ipStatic_.ipAddr_.netMask_ = "255.255.254.0"; + ic->ipStatic_.ipAddr_.hostName_ = "netAddr"; + ic->ipStatic_.route_.type_ = INetAddr::IPV4; + ic->ipStatic_.route_.family_ = 0x01; + ic->ipStatic_.route_.prefixlen_ = 0x01; + ic->ipStatic_.route_.address_ = "0.0.0.0"; + ic->ipStatic_.route_.netMask_ = "0.0.0.0"; + ic->ipStatic_.route_.hostName_ = "netAddr"; + ic->ipStatic_.gate_.type_ = INetAddr::IPV4; + ic->ipStatic_.gate_.family_ = 0x01; + ic->ipStatic_.gate_.prefixlen_ = 0x01; + ic->ipStatic_.gate_.address_ = "172.17.4.1"; + ic->ipStatic_.gate_.netMask_ = "0.0.0.0"; + ic->ipStatic_.gate_.hostName_ = "netAddr"; + ic->ipStatic_.netMask_.type_ = INetAddr::IPV4; + ic->ipStatic_.netMask_.family_ = 0x01; + ic->ipStatic_.netMask_.netMask_ = "255.255.255.0"; + ic->ipStatic_.netMask_.hostName_ = "netAddr"; + INetAddr dns1; + dns1.type_ = INetAddr::IPV4; + dns1.family_ = 0x01; + dns1.address_ = "8.8.8.8"; + dns1.hostName_ = "netAddr"; + INetAddr dns2; + dns2.type_ = INetAddr::IPV4; + dns2.family_ = 0x01; + dns2.address_ = "114.114.114.114"; + dns2.hostName_ = "netAddr"; + ic->ipStatic_.dnsServers_.push_back(dns1); + ic->ipStatic_.dnsServers_.push_back(dns2); + return ic; +} + +/** + * @tc.name: EthernetManager001 + * @tc.desc: Test EthernetManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(EthernetManagerTest, EthernetManager001, TestSize.Level1) +{ + std::string iface = "eth0"; + sptr ic = GetIfaceConfig(); + int32_t result = DelayedSingleton::GetInstance()->SetIfaceConfig(iface, ic); + ASSERT_TRUE(result == 0); +} + +/** + * @tc.name: EthernetManager002 + * @tc.desc: Test EthernetManager SetIfaceConfig. + * @tc.type: FUNC + */ +HWTEST_F(EthernetManagerTest, EthernetManager002, TestSize.Level1) +{ + std::string iface = "eth0"; + sptr ic = + DelayedSingleton::GetInstance()->GetIfaceConfig(iface); + ASSERT_TRUE(result != nullptr); +} + +/** + * @tc.name: EthernetManager003 + * @tc.desc: Test EthernetManager Whether2Activate. + * @tc.type: FUNC + */ +HWTEST_F(EthernetManagerTest, EthernetManager003, TestSize.Level1) +{ + std::string iface = "eth0"; + int32_t result = DelayedSingleton::GetInstance()->IsActivate(iface); + ASSERT_TRUE(result == 0); +} + +/** + * @tc.name: EthernetManager004 + * @tc.desc: Test EthernetManager GetActivateInterfaces. + * @tc.type: FUNC + */ +HWTEST_F(EthernetManagerTest, EthernetManager004, TestSize.Level1) +{ + std::vector result = DelayedSingleton::GetInstance()->GetActivateInterfaces(); + for (std::string& s : result) { + std::cout << s << ","<< std::endl; + } +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/netconnmanager/BUILD.gn b/services/netconnmanager/BUILD.gn new file mode 100755 index 0000000..2b8b225 --- /dev/null +++ b/services/netconnmanager/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +ohos_shared_library("net_conn_manager") { + sources = [ + "$NETCONNMANAGER_COMMON_DIR/src/broadcast_manager.cpp", + "$NETCONNMANAGER_COMMON_DIR/src/netd_controller.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/ipc/net_conn_callback_proxy.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/ipc/net_conn_service_stub.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/net_conn_service.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/net_controller/net_controller_factory.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/net_controller/telephony_controller.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/net_id_manager.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/net_service.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/net_supplier.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/network.cpp", + ] + + include_dirs = [ + "$NETCONNMANAGER_SOURCE_DIR/include", + "$NETCONNMANAGER_SOURCE_DIR/include/ipc", + "$NETCONNMANAGER_SOURCE_DIR/include/net_controller", + "$INNERKITS_ROOT/native/netconnmanager/include", + "$NETCONNMANAGER_COMMON_DIR/include", + ] + + deps = [ + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "$NETMANAGER_PREBUILTS_DIR/librarys/netd:libnet_manager_native", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "core_service:tel_cellular_data_api", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + defines = [ + "NETMGR_LOG_TAG = \"NetConnManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + defines += [ "NATIVE_NETD_FEATURE" ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/services/netconnmanager/include/ipc/i_net_conn_service.h b/services/netconnmanager/include/ipc/i_net_conn_service.h new file mode 100755 index 0000000..feec806 --- /dev/null +++ b/services/netconnmanager/include/ipc/i_net_conn_service.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_NET_CONN_SERVICE_H +#define I_NET_CONN_SERVICE_H + +#include + +#include "iremote_broker.h" + +#include "net_link_info.h" +#include "net_specifier.h" +#include "net_supplier_info.h" +#include "i_net_conn_callback.h" + +namespace OHOS { +namespace NetManagerStandard { +class INetConnService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.NetManagerStandard.INetConnService"); + enum { + CMD_NM_START, + CMD_NM_REGISTER_NET_SUPPLIER, + CMD_NM_SYSTEM_READY, + CMD_NM_REGISTER_NET_CONN_CALLBACK, + CMD_NM_REGISTER_NET_CONN_CALLBACK_BY_SPECIFIER, + CMD_NM_UNREGISTER_NET_CONN_CALLBACK, + CMD_NM_UNREGISTER_NET_CONN_CALLBACK_BY_SPECIFIER, + CMD_NM_REG_NET_SUPPLIER, + CMD_NM_UNREG_NETWORK, + CMD_NM_SET_NET_SUPPLIER_INFO, + CMD_NM_SET_NET_CAPABILTITES, + CMD_NM_SET_NET_LINK_INFO, + CMD_NM_END, + }; + +public: + virtual int32_t SystemReady() = 0; + virtual int32_t RegisterNetSupplier(uint32_t netType, const std::string &ident, uint64_t netCapabilities) = 0; + virtual int32_t UnregisterNetSupplier(uint32_t supplierId) = 0; + virtual int32_t RegisterNetConnCallback(const sptr &callback) = 0; + virtual int32_t RegisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) = 0; + virtual int32_t UnregisterNetConnCallback(const sptr &callback) = 0; + virtual int32_t UnregisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) = 0; + virtual int32_t UpdateNetSupplierInfo(uint32_t supplierId, const sptr &netSupplierInfo) = 0; + virtual int32_t UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities) = 0; + virtual int32_t UpdateNetLinkInfo(uint32_t supplierId, const sptr &netLinkInfo) = 0; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // I_NET_CONN_SERVICE_H diff --git a/services/netconnmanager/include/ipc/net_conn_callback_proxy.h b/services/netconnmanager/include/ipc/net_conn_callback_proxy.h new file mode 100755 index 0000000..27c2d02 --- /dev/null +++ b/services/netconnmanager/include/ipc/net_conn_callback_proxy.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_CALLBACK_PROXY_H +#define NET_CONN_CALLBACK_PROXY_H + +#include "iremote_proxy.h" + +#include "i_net_conn_callback.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetConnCallbackProxy : public IRemoteProxy { +public: + explicit NetConnCallbackProxy(const sptr &impl); + virtual ~NetConnCallbackProxy(); + +public: + int32_t NetConnStateChanged(const sptr &info) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_CALLBACK_PROXY_H diff --git a/services/netconnmanager/include/ipc/net_conn_service_proxy.h b/services/netconnmanager/include/ipc/net_conn_service_proxy.h new file mode 100755 index 0000000..3c18c11 --- /dev/null +++ b/services/netconnmanager/include/ipc/net_conn_service_proxy.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_SERVICE_PROXY_H +#define NET_CONN_SERVICE_PROXY_H + +#include "iremote_proxy.h" + +#include "i_net_conn_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetConnServiceProxy : public IRemoteProxy { +public: + explicit NetConnServiceProxy(const sptr &impl); + virtual ~NetConnServiceProxy(); + int32_t SystemReady() override; + int32_t RegisterNetSupplier(uint32_t netType, const std::string &ident, uint64_t netCapabilities) override; + int32_t UnregisterNetSupplier(uint32_t supplierId) override; + int32_t RegisterNetConnCallback(const sptr &callback) override; + int32_t RegisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) override; + int32_t UnregisterNetConnCallback(const sptr &callback) override; + int32_t UnregisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) override; + int32_t UpdateNetSupplierInfo(uint32_t supplierId, const sptr &netSupplierInfo) override; + int32_t UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities) override; + int32_t UpdateNetLinkInfo(uint32_t supplierId, const sptr &netLinkInfo) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_SERVICE_PROXY_H diff --git a/services/netconnmanager/include/ipc/net_conn_service_stub.h b/services/netconnmanager/include/ipc/net_conn_service_stub.h new file mode 100755 index 0000000..cf623fb --- /dev/null +++ b/services/netconnmanager/include/ipc/net_conn_service_stub.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_SERVICE_STUB_H +#define NET_CONN_SERVICE_STUB_H + +#include + +#include "iremote_stub.h" + +#include "i_net_conn_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetConnServiceStub : public IRemoteStub { +public: + NetConnServiceStub(); + ~NetConnServiceStub(); + + int32_t OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + using NetConnServiceFunc = int32_t (NetConnServiceStub::*)(MessageParcel &, MessageParcel &); + +private: + int32_t OnSystemReady(MessageParcel &data, MessageParcel &reply); + int32_t OnRegisterNetSupplier(MessageParcel &data, MessageParcel &reply); + int32_t OnUnregisterNetSupplier(MessageParcel &data, MessageParcel &reply); + int32_t OnRegisterNetConnCallback(MessageParcel &data, MessageParcel &reply); + int32_t OnRegisterNetConnCallbackBySpecifier(MessageParcel &data, MessageParcel &reply); + int32_t OnUnregisterNetConnCallback(MessageParcel &data, MessageParcel &reply); + int32_t OnUnregisterNetConnCallbackBySpecifier(MessageParcel &data, MessageParcel &reply); + int32_t OnUpdateNetSupplierInfo(MessageParcel &data, MessageParcel &reply); + int32_t OnUpdateNetCapabilities(MessageParcel &data, MessageParcel &reply); + int32_t OnUpdateNetLinkInfo(MessageParcel &data, MessageParcel &reply); + +private: + int32_t ConvertCode(int32_t internalCode); + +private: + std::map memberFuncMap_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_SERVICE_STUB_H diff --git a/services/netconnmanager/include/net_conn_service.h b/services/netconnmanager/include/net_conn_service.h new file mode 100755 index 0000000..c33c467 --- /dev/null +++ b/services/netconnmanager/include/net_conn_service.h @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_SERVICE_H +#define NET_CONN_SERVICE_H + +#include +#include +#include +#include + +#include "singleton.h" +#include "system_ability.h" + +#include "ipc/net_conn_service_stub.h" +#include "net_service.h" +#include "net_supplier.h" +#include "network.h" +#include "timer.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr uint32_t CONNECT_SERVICE_WAIT_TIME = 6000; +class NetConnService : public SystemAbility, + public NetConnServiceStub, + public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(NetConnService) + DECLARE_SYSTEM_ABILITY(NetConnService) + + using NET_SERVICE_LIST = std::list>; + using NET_NETWORK_LIST = std::list>; + using NET_SUPPLIER_LIST = std::list>; + +public: + void OnStart() override; + void OnStop() override; + /** + * @brief The interface in NetConnService can be called when the system is ready + * + * @return Returns 0, the system is ready, otherwise the system is not ready + */ + int32_t SystemReady() override; + + /** + * @brief The interface is register the network + * + * @param netType Network Type + * @param ident Unique identification of mobile phone card + * @param netCapabilities Network capabilities registered by the network supplier + * + * @return The id of the network supplier + */ + int32_t RegisterNetSupplier(uint32_t netType, const std::string &ident, uint64_t netCapabilities) override; + + /** + * @brief The interface is unregister the network + * + * @param supplierId The id of the network supplier + * + * @return Returns 0, unregister the network successfully, otherwise it will fail + */ + int32_t UnregisterNetSupplier(uint32_t supplierId) override; + + /** + * @brief Register net connection callback + * + * @param netSpecifier specifier information + * @param callback The callback of INetConnCallback interface + * + * @return Returns 0, successfully register net connection callback, otherwise it will failed + */ + int32_t RegisterNetConnCallback(const sptr &callback) override; + + /** + * @brief Register net connection callback by NetSpecifier + * + * @param netSpecifier specifier information + * @param callback The callback of INetConnCallback interface + * + * @return Returns 0, successfully register net connection callback, otherwise it will failed + */ + int32_t RegisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) override; + + /** + * @brief Unregister net connection callback + * + * @return Returns 0, successfully unregister net connection callback, otherwise it will fail + */ + int32_t UnregisterNetConnCallback(const sptr &callback) override; + + /** + * @brief Unregister net connection callback by NetSpecifier + * + * @return Returns 0, successfully unregister net connection callback, otherwise it will fail + */ + int32_t UnregisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) override; + + /** + * @brief The interface is update network connection status information + * + * @param supplierId The id of the network supplier + * @param netSupplierInfo network connection status information + * + * @return Returns 0, successfully update the network connection status information, otherwise it will fail + */ + int32_t UpdateNetSupplierInfo(uint32_t supplierId, const sptr &netSupplierInfo) override; + + /** + * @brief The interface is Create or delete network services based on the supplierId and the netCapabilities + * + * @param supplierId The id of the network supplier + * @param netCapabilities Network capabilities registered by the network supplier + * + * @return Returns 0, successfully create network service or delete network service, otherwise fail + */ + int32_t UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities) override; + + /** + * @brief The interface is update network link attribute information + * + * @param supplierId The id of the network supplier + * @param netLinkInfo network link attribute information + * + * @return Returns 0, successfully update the network link attribute information, otherwise it will fail + */ + int32_t UpdateNetLinkInfo(uint32_t supplierId, const sptr &netLinkInfo) override; + static void ReConnectServiceTask(); + +private: + bool Init(); + sptr GetNetSupplierFromList( + uint32_t netType, const std::string &ident); + sptr GetNetSupplierFromListById(uint32_t supplierId); + sptr GetNetworkFromListBySupplierId(uint32_t supplierId); + void DeleteSupplierFromListById(uint32_t supplierId); + void DeleteNetworkFromListBySupplierId(uint32_t supplierId); + bool DeleteServiceFromListByCap(int32_t netId, const NetCapabilities &netCapability); + void DeleteServiceFromListByNet(const Network &network); + bool IsServiceInList(int32_t netId, const NetCapabilities &netCapability) const; + int32_t ReConnectService(); + void ThreadExitTask(); + int32_t NotifyNetConnStateChanged(const sptr &info); + +private: + enum ServiceRunningState { + STATE_STOPPED = 0, + STATE_RUNNING, + }; + + bool registerToService_; + ServiceRunningState state_; + sptr defaultNetService_ = nullptr; + + NET_SERVICE_LIST netServices_; + NET_NETWORK_LIST networks_; + NET_SUPPLIER_LIST netSupplier_; + + Timer reConnectTimer_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_SERVICE_H diff --git a/services/netconnmanager/include/net_conn_types.h b/services/netconnmanager/include/net_conn_types.h new file mode 100755 index 0000000..5578a72 --- /dev/null +++ b/services/netconnmanager/include/net_conn_types.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_TYPES_H +#define NET_CONN_TYPES_H + +namespace OHOS { +namespace NetManagerStandard { +enum ResultCode { + ERR_NONE = 0, + ERR_SERVICE_REQUEST_SUCCESS = (-1), + ERR_SERVICE_REQUEST_CONNECT_FAIL = (-2), + ERR_SERVICE_UPDATE_NET_LINK_INFO_FAIL = (-3), + ERR_SERVICE_CONNECTING = (-4), + ERR_SERVICE_CONNECTED = (-5), + ERR_SERVICE_DISCONNECTED_FAIL = (-6), + ERR_SERVICE_DISCONNECTING = (-7), + ERR_SERVICE_DISCONNECTED_SUCCESS = (-8), + ERR_SERVICE_NULL_PTR = (-9), + ERR_NO_SUPPLIER = (-10), + ERR_NO_NETWORK = (-11), + ERR_INVALID_PARAMS = (-12), + ERR_INVALID_NETORK_TYPE = (-13), + ERR_SERVICE_UPDATE_NET_LINK_INFO_SUCCES = (-14), + ERR_NET_MONITOR_OPT_SUCCESS = (-15), + ERR_NET_MONITOR_OPT_FAILED = (-16), + ERR_NET_SUPPLIER_NO_API = (-17), + ERR_NET_TYPE_NOT_FOUND = (-18), + ERR_NO_ANY_NET_TYPE = (-19), + ERR_NO_REGISTERED = (-20), +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_TYPES_H diff --git a/services/netconnmanager/include/net_controller/i_net_controller.h b/services/netconnmanager/include/net_controller/i_net_controller.h new file mode 100755 index 0000000..a079463 --- /dev/null +++ b/services/netconnmanager/include/net_controller/i_net_controller.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef I_NET_CONTROLLER_H +#define I_NET_CONTROLLER_H + +#include "net_specifier.h" +#include "net_supplier_info.h" + +namespace OHOS { +namespace NetManagerStandard { +class INetController : public virtual RefBase { +public: + virtual ~INetController() = default; + virtual int32_t RequestNetwork(const std::string &ident, NetCapabilities netCapabilitiy) = 0; + virtual int32_t ReleaseNetwork(const std::string &ident, NetCapabilities netCapabilitiy) = 0; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // I_NET_CONTROLLER_H \ No newline at end of file diff --git a/services/netconnmanager/include/net_controller/net_controller_factory.h b/services/netconnmanager/include/net_controller/net_controller_factory.h new file mode 100755 index 0000000..20bab0e --- /dev/null +++ b/services/netconnmanager/include/net_controller/net_controller_factory.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NET_CONTROLLER_FACTORY_H +#define NET_CONTROLLER_FACTORY_H + +#include +#include +#include "i_net_controller.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetControllerFactory { + DECLARE_DELAYED_SINGLETON(NetControllerFactory) +public: + sptr MakeNetController(uint32_t netType); + +private: + sptr GetNetControllerFromMap(uint32_t netType); + std::map> netControllers; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONTROLLER_FACTORY_H \ No newline at end of file diff --git a/services/netconnmanager/include/net_controller/telephony_controller.h b/services/netconnmanager/include/net_controller/telephony_controller.h new file mode 100755 index 0000000..ac9b77c --- /dev/null +++ b/services/netconnmanager/include/net_controller/telephony_controller.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TELEPHONY_CONTROLLER_H +#define TELEPHONY_CONTROLLER_H + +#include + +#include "i_net_controller.h" + +namespace OHOS { +namespace NetManagerStandard { +class TelephonyController : public INetController { +public: + TelephonyController(); + ~TelephonyController() = default; + + /** + * @brief When a network request is initiated, the cellular data activation data interface will be called + * + * @param ident_ Unique identification of mobile phone card + * @param netCapabilitiy Network capabilities registered by Cellular Data + * + * @return Return the return value of the cellular data interface call + */ + int32_t RequestNetwork(const std::string &ident, NetCapabilities netCapabilitiy) override; + + /** + * @brief When the network is disconnected, the cellular data deactivation interface will be called + * + * @param ident_ Unique identification of mobile phone card + * @param netCapabilitiy Network capabilities registered by Cellular Data + * + * @return Return the return value of the cellular data interface call + */ + int32_t ReleaseNetwork(const std::string &ident, NetCapabilities netCapabilitiy) override; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // TELEPHONY_CONTROLLER_H diff --git a/services/netconnmanager/include/net_id_manager.h b/services/netconnmanager/include/net_id_manager.h new file mode 100755 index 0000000..d6bd027 --- /dev/null +++ b/services/netconnmanager/include/net_id_manager.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_ID_MANAGER_H +#define NET_ID_MANAGER_H + +#include +#include +#include + +#include + +namespace OHOS { +namespace NetManagerStandard { +// Class used to reserve and release net IDs. +class NetIdManager { + DECLARE_DELAYED_SINGLETON(NetIdManager) +public: + int32_t ReserveNetId(); + void ReleaseNetId(int32_t netId); + +public: + static constexpr int32_t TUN_IF_RANGE = 0x0400; + static constexpr int32_t MAX_NET_ID = 65535 - TUN_IF_RANGE; + static constexpr int32_t MIN_NET_ID = 100; +private: + std::atomic lastNetId_ = -1; + std::atomic maxNetId_ = MAX_NET_ID; + std::map netIdInUse_; + std::mutex mtx_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_ID_MANAGER_H \ No newline at end of file diff --git a/services/netconnmanager/include/net_service.h b/services/netconnmanager/include/net_service.h new file mode 100755 index 0000000..5b757eb --- /dev/null +++ b/services/netconnmanager/include/net_service.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_SERVICE_H +#define NET_SERVICE_H + +#include +#include +#include + +#include "network.h" +#include "i_net_conn_callback.h" + +namespace OHOS { +namespace NetManagerStandard { +enum ServiceState { + SERVICE_STATE_UNKNOWN = 0, + SERVICE_STATE_IDLE = 1, + SERVICE_STATE_CONNECTING = 2, + SERVICE_STATE_READY = 3, + SERVICE_STATE_CONNECTED = 4, + SERVICE_STATE_DISCONNECTING = 5, + SERVICE_STATE_DISCONNECTED = 6, + SERVICE_STATE_FAILURE = 7, +}; + +class NetService : public virtual RefBase { +public: + NetService(const std::string &ident, NetworkType networkType, + NetCapabilities netCapability, sptr &network); + ~NetService() = default; + void SetIdent(const std::string &ident); + void SetNetworkType(const NetworkType &networkType); + void SetNetCapability(const NetCapabilities &netCapability); + void SetServiceState(const ServiceState &serviceState); + std::string GetIdent() const; + NetworkType GetNetworkType() const; + NetCapabilities GetNetCapability() const; + ServiceState GetServiceState() const; + sptr GetNetwork() const; + + /** + * @brief Initiate a network connection request to the network service of the network supplier + * + * @return Return ERR_SERVICE_REQUEST_SUCCESS, Succeed + */ + int32_t ServiceConnect(); + + /** + * @brief Initiate a disconnect request to the network service of the network supplier + * + * @return Return ERR_SERVICE_DISCONNECTED_SUCCESS, Succeed + */ + int32_t ServiceDisConnect(); + + /** + * @brief Automatically initiate a network connection request to the network service of the network supplier + * + * @return Return ERR_SERVICE_REQUEST_SUCCESS, Succeed + */ + int32_t ServiceAutoConnect(); + + /** + * @brief Register net connection callback + * + * @return Return ERR_NONE, Succeed + */ + void RegisterNetConnCallback(const sptr &callback); + + /** + * @brief Unregister net connection callback + * + * @return Return ERR_NONE, Succeed + */ + int32_t UnregisterNetConnCallback(const sptr &callback); + + bool IsConnecting() const; + bool IsConnected() const; + +private: + int32_t NetworkConnect(); + int32_t NetworkDisConnect(); + void UpdateServiceState(ServiceState serviceState); + int32_t NotifyNetConnStateChanged(const sptr &info); + +private: + std::string ident_; + NetworkType networkType_ = NET_TYPE_UNKNOWN; + ServiceState state_ = SERVICE_STATE_IDLE; + + NetCapabilities netCapability_ = NET_CAPABILITIES_NONE; + sptr network_; + + std::vector> netConnCallback_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_SERVICE_H \ No newline at end of file diff --git a/services/netconnmanager/include/net_supplier.h b/services/netconnmanager/include/net_supplier.h new file mode 100755 index 0000000..d3115d1 --- /dev/null +++ b/services/netconnmanager/include/net_supplier.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_SUPPLIER_H +#define NET_SUPPLIER_H + +#include + +#include "i_net_controller.h" + +namespace OHOS { +namespace NetManagerStandard { +class Network; +class NetService; +class NetSupplier : public virtual RefBase { +public: + NetSupplier(); + NetSupplier(NetworkType netSupplierType, const std::string &netSupplierIdent); + ~NetSupplier() = default; + bool operator==(const NetSupplier &netSupplier) const; + NetworkType GetNetSupplierType() const; + std::string GetNetSupplierIdent() const; + bool SupplierConnection(NetCapabilities netCapabilities); + bool SupplierDisconnection(NetCapabilities netCapabilities); + void UpdateNetSupplierInfo(const NetSupplierInfo &netSupplierInfo); + uint32_t GetSupplierId() const; + bool GetConnected() const; + bool GetAvailable() const; + bool GetRoaming() const; + bool GetStrength() const; + bool GetFrequency() const; + +private: + sptr netController_; + NetworkType netSupplierType_; + std::string netSupplierIdent_; + uint32_t supplierId_ = 0; + uint16_t frequency_ = 0x00; + uint8_t strength_ = 0x00; + bool connected_ = false; + bool isAvailable_ = false; // whether the network is available + bool isRoaming_ = false; + const int32_t REG_OK = 1; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_SUPPLIER_H diff --git a/services/netconnmanager/include/network.h b/services/netconnmanager/include/network.h new file mode 100755 index 0000000..03a5f8e --- /dev/null +++ b/services/netconnmanager/include/network.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_H +#define NETWORK_H + +#include "inet_addr.h" +#include "net_link_info.h" +#include "net_supplier.h" +#include "route.h" + +namespace OHOS { +namespace NetManagerStandard { +class Network : public virtual RefBase { +public: + Network(sptr &supplier); + ~Network(); + bool operator==(const Network &network) const; + + bool NetworkConnect(const NetCapabilities &netCapability); + bool NetworkDisconnect(const NetCapabilities &netCapability); + bool UpdateNetLinkInfo(const NetLinkInfo &netLinkInfo); + void SetIpAdress(const INetAddr &ipAdress); + void SetDns(const INetAddr &dns); + void SetRoute(const Route &route); + INetAddr GetIpAdress() const; + INetAddr GetDns() const; + Route GetRoute() const; + NetLinkInfo GetNetLinkInfo() const; + int32_t GetNetId() const; + sptr GetNetSupplier() const; + bool UpdateNetSupplierInfo(const NetSupplierInfo &netSupplierInfo); + bool IsNetworkConnecting() const; + void SetConnected(bool connected); + void SetConnecting(bool connecting); + void UpdateInterfaces(const NetLinkInfo &netLinkInfo); + void UpdateRoutes(const NetLinkInfo &netLinkInfo); + void UpdateDnses(const NetLinkInfo &netLinkInfo); + void updateMtu(const NetLinkInfo &netLinkInfo); + +private: + NetLinkInfo netLinkInfo_; + INetAddr ipAddr_; + INetAddr dns_; + Route route_; + + // netd network param + bool isPhyNetCreated_ = false; + bool isConnecting_ = false; + bool isConnected_ = false; + + sptr supplier_; + int32_t netId_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NETWORK_H diff --git a/services/netconnmanager/src/ipc/net_conn_callback_proxy.cpp b/services/netconnmanager/src/ipc/net_conn_callback_proxy.cpp new file mode 100755 index 0000000..e7615e1 --- /dev/null +++ b/services/netconnmanager/src/ipc/net_conn_callback_proxy.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_conn_callback_proxy.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetConnCallbackProxy::NetConnCallbackProxy(const sptr &impl) + : IRemoteProxy(impl) +{} + +NetConnCallbackProxy::~NetConnCallbackProxy() {} + +int32_t NetConnCallbackProxy::NetConnStateChanged(const sptr &info) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return ERR_FLATTEN_OBJECT; + } + + if (!info->Marshalling(data)) { + NETMGR_LOGE("Proxy Marshalling failed"); + return ERR_FLATTEN_OBJECT; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return ERR_NULL_OBJECT; + } + + MessageParcel reply; + MessageOption option; + int32_t ret = remote->SendRequest(NET_CONN_STATE_CHANGED, data, reply, option); + if (ret != ERR_NONE) { + NETMGR_LOGE("Proxy SendRequest failed, ret code:[%{public}d]", ret); + } + return ret; +} + +bool NetConnCallbackProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(NetConnCallbackProxy::GetDescriptor())) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return false; + } + return true; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/src/ipc/net_conn_service_proxy.cpp b/services/netconnmanager/src/ipc/net_conn_service_proxy.cpp new file mode 100755 index 0000000..c3f927f --- /dev/null +++ b/services/netconnmanager/src/ipc/net_conn_service_proxy.cpp @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_conn_service_proxy.h" + +#include "net_conn_constants.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetConnServiceProxy::NetConnServiceProxy(const sptr &impl) + : IRemoteProxy(impl) +{} + +NetConnServiceProxy::~NetConnServiceProxy() {} + +int32_t NetConnServiceProxy::SystemReady() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return ERR_FLATTEN_OBJECT; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return ERR_NULL_OBJECT; + } + int32_t error = remote->SendRequest(CMD_NM_SYSTEM_READY, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + } + return error; +} + +int32_t NetConnServiceProxy::RegisterNetSupplier( + uint32_t netType, const std::string &ident, uint64_t netCapabilities) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return NET_CONN_ERR_INVALID_SUPPLIER_ID; + } + + NETMGR_LOGI("proxy netType[%{public}d], ident[%{public}s], netCapabilities[%{public}lld]", + netType, ident.c_str(), netCapabilities); + if (!data.WriteUint32(netType)) { + return NET_CONN_ERR_INVALID_SUPPLIER_ID; + } + if (!data.WriteString(ident)) { + return NET_CONN_ERR_INVALID_SUPPLIER_ID; + } + if (!data.WriteUint64(netCapabilities)) { + return NET_CONN_ERR_INVALID_SUPPLIER_ID; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NET_CONN_ERR_INVALID_SUPPLIER_ID; + } + int32_t error = remote->SendRequest(CMD_NM_REG_NET_SUPPLIER, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return NET_CONN_ERR_INVALID_SUPPLIER_ID; + } + + return reply.ReadInt32(); +} + +int32_t NetConnServiceProxy::UnregisterNetSupplier(uint32_t supplierId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return ERR_FLATTEN_OBJECT; + } + + NETMGR_LOGI("proxy supplierId[%{public}d]", supplierId); + if (!data.WriteUint32(supplierId)) { + return ERR_FLATTEN_OBJECT; + } + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return ERR_NULL_OBJECT; + } + int32_t error = remote->SendRequest(CMD_NM_UNREG_NETWORK, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return error; + } + + return reply.ReadInt32(); +} + +int32_t NetConnServiceProxy::RegisterNetConnCallback(const sptr &callback) +{ + if (callback == nullptr) { + NETMGR_LOGE("The parameter of callback is nullptr"); + return NET_CONN_ERR_INPUT_NULL_PTR; + } + + MessageParcel dataParcel; + if (!WriteInterfaceToken(dataParcel)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return NET_CONN_ERR_INVALID_PARAMETER; + } + dataParcel.WriteRemoteObject(callback->AsObject().GetRefPtr()); + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NET_CONN_ERR_GET_REMOTE_OBJECT_FAILED; + } + + MessageOption option; + MessageParcel replyParcel; + int32_t retCode = remote->SendRequest(CMD_NM_REGISTER_NET_CONN_CALLBACK, dataParcel, replyParcel, option); + NETMGR_LOGI("SendRequest retCode:[%{public}d]", retCode); + if (retCode != NET_CONN_SUCCESS) { + return retCode; + } + return replyParcel.ReadInt32(); +} + +int32_t NetConnServiceProxy::RegisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) +{ + if (netSpecifier == nullptr || callback == nullptr) { + NETMGR_LOGE("The parameter of netSpecifier or callback is nullptr"); + return NET_CONN_ERR_INPUT_NULL_PTR; + } + + MessageParcel dataParcel; + if (!WriteInterfaceToken(dataParcel)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return NET_CONN_ERR_INVALID_PARAMETER; + } + netSpecifier->Marshalling(dataParcel); + dataParcel.WriteRemoteObject(callback->AsObject().GetRefPtr()); + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NET_CONN_ERR_GET_REMOTE_OBJECT_FAILED; + } + + MessageOption option; + MessageParcel replyParcel; + int32_t retCode = remote->SendRequest( + CMD_NM_REGISTER_NET_CONN_CALLBACK_BY_SPECIFIER, dataParcel, replyParcel, option); + NETMGR_LOGI("SendRequest retCode:[%{public}d]", retCode); + if (retCode != NET_CONN_SUCCESS) { + return retCode; + } + return replyParcel.ReadInt32(); +} + +int32_t NetConnServiceProxy::UnregisterNetConnCallback(const sptr &callback) +{ + if (callback == nullptr) { + NETMGR_LOGE("The parameter of callback is nullptr"); + return NET_CONN_ERR_INPUT_NULL_PTR; + } + + MessageParcel dataParcel; + if (!WriteInterfaceToken(dataParcel)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return NET_CONN_ERR_INVALID_PARAMETER; + } + dataParcel.WriteRemoteObject(callback->AsObject().GetRefPtr()); + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NET_CONN_ERR_GET_REMOTE_OBJECT_FAILED; + } + + MessageOption option; + MessageParcel replyParcel; + int32_t retCode = remote->SendRequest(CMD_NM_UNREGISTER_NET_CONN_CALLBACK, dataParcel, replyParcel, option); + NETMGR_LOGI("SendRequest retCode:[%{public}d]", retCode); + if (retCode != NET_CONN_SUCCESS) { + return retCode; + } + return replyParcel.ReadInt32(); +} + +int32_t NetConnServiceProxy::UnregisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) +{ + if (netSpecifier == nullptr || callback == nullptr) { + NETMGR_LOGE("The parameter of netSpecifier or callback is nullptr"); + return NET_CONN_ERR_INPUT_NULL_PTR; + } + + MessageParcel dataParcel; + if (!WriteInterfaceToken(dataParcel)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return NET_CONN_ERR_INVALID_PARAMETER; + } + netSpecifier->Marshalling(dataParcel); + dataParcel.WriteRemoteObject(callback->AsObject().GetRefPtr()); + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NET_CONN_ERR_GET_REMOTE_OBJECT_FAILED; + } + + MessageOption option; + MessageParcel replyParcel; + int32_t retCode = remote->SendRequest( + CMD_NM_UNREGISTER_NET_CONN_CALLBACK_BY_SPECIFIER, dataParcel, replyParcel, option); + NETMGR_LOGI("SendRequest retCode:[%{public}d]", retCode); + if (retCode != NET_CONN_SUCCESS) { + return retCode; + } + return replyParcel.ReadInt32(); +} + +int32_t NetConnServiceProxy::UpdateNetSupplierInfo(uint32_t supplierId, + const sptr &netSupplierInfo) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return ERR_FLATTEN_OBJECT; + } + + NETMGR_LOGI("proxy supplierId[%{public}d]", supplierId); + if (!data.WriteUint32(supplierId)) { + return ERR_FLATTEN_OBJECT; + } + NETMGR_LOGI("proxy supplierId[%{public}d] Marshalling success", supplierId); + if (!netSupplierInfo->Marshalling(data)) { + NETMGR_LOGE("proxy Marshalling failed"); + return ERR_FLATTEN_OBJECT; + } + NETMGR_LOGI("proxy Marshalling success"); + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return ERR_NULL_OBJECT; + } + int32_t error = remote->SendRequest(CMD_NM_SET_NET_SUPPLIER_INFO, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return error; + } + + return reply.ReadInt32(); +} + +int32_t NetConnServiceProxy::UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return IPC_PROXY_ERR; + } + + NETMGR_LOGI("proxy supplierId[%{public}d], netCapabilities[%{public}lld]", supplierId, netCapabilities); + if (!data.WriteUint32(supplierId)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteUint64(netCapabilities)) { + return ERR_FLATTEN_OBJECT; + } + NETMGR_LOGI("proxy Marshalling success"); + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return ERR_NULL_OBJECT; + } + int32_t error = remote->SendRequest(CMD_NM_SET_NET_CAPABILTITES, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return error; + } + + return reply.ReadInt32(); +} + +int32_t NetConnServiceProxy::UpdateNetLinkInfo(uint32_t supplierId, const sptr &netLinkInfo) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return IPC_PROXY_ERR; + } + + if (!data.WriteUint32(supplierId)) { + return IPC_PROXY_ERR; + } + + if (!netLinkInfo->Marshalling(data)) { + NETMGR_LOGE("proxy Marshalling failed"); + return IPC_PROXY_ERR; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return ERR_NULL_OBJECT; + } + int32_t error = remote->SendRequest(CMD_NM_SET_NET_LINK_INFO, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return error; + } + + return reply.ReadInt32(); +} + +bool NetConnServiceProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(NetConnServiceProxy::GetDescriptor())) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return false; + } + return true; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/src/ipc/net_conn_service_stub.cpp b/services/netconnmanager/src/ipc/net_conn_service_stub.cpp new file mode 100755 index 0000000..d07f326 --- /dev/null +++ b/services/netconnmanager/src/ipc/net_conn_service_stub.cpp @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_conn_service_stub.h" + +#include "net_conn_types.h" +#include "net_conn_constants.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetConnServiceStub::NetConnServiceStub() +{ + memberFuncMap_[CMD_NM_SYSTEM_READY] = &NetConnServiceStub::OnSystemReady; + memberFuncMap_[CMD_NM_REGISTER_NET_CONN_CALLBACK] = &NetConnServiceStub::OnRegisterNetConnCallback; + memberFuncMap_[CMD_NM_REGISTER_NET_CONN_CALLBACK_BY_SPECIFIER] = + &NetConnServiceStub::OnRegisterNetConnCallbackBySpecifier; + memberFuncMap_[CMD_NM_UNREGISTER_NET_CONN_CALLBACK] = &NetConnServiceStub::OnUnregisterNetConnCallback; + memberFuncMap_[CMD_NM_UNREGISTER_NET_CONN_CALLBACK_BY_SPECIFIER] = + &NetConnServiceStub::OnUnregisterNetConnCallbackBySpecifier; + memberFuncMap_[CMD_NM_REG_NET_SUPPLIER] = &NetConnServiceStub::OnRegisterNetSupplier; + memberFuncMap_[CMD_NM_UNREG_NETWORK] = &NetConnServiceStub::OnUnregisterNetSupplier; + memberFuncMap_[CMD_NM_SET_NET_SUPPLIER_INFO] = &NetConnServiceStub::OnUpdateNetSupplierInfo; + memberFuncMap_[CMD_NM_SET_NET_CAPABILTITES] = &NetConnServiceStub::OnUpdateNetCapabilities; + memberFuncMap_[CMD_NM_SET_NET_LINK_INFO] = &NetConnServiceStub::OnUpdateNetLinkInfo; +} + +NetConnServiceStub::~NetConnServiceStub() {} + +int32_t NetConnServiceStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + NETMGR_LOGI("stub call start, code = [%{public}d]", code); + + std::u16string myDescripter = NetConnServiceStub::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (myDescripter != remoteDescripter) { + NETMGR_LOGE("descriptor checked fail"); + return ERR_FLATTEN_OBJECT; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + + NETMGR_LOGI("stub default case, need check"); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t NetConnServiceStub::OnSystemReady(MessageParcel &data, MessageParcel &reply) +{ + SystemReady(); + return ERR_NONE; +} + +int32_t NetConnServiceStub::OnRegisterNetSupplier(MessageParcel &data, MessageParcel &reply) +{ + NETMGR_LOGI("stub processing"); + uint32_t netType; + std::string ident; + uint64_t netCapabilities; + if (!data.ReadUint32(netType)) { + return ERR_FLATTEN_OBJECT; + } + + if (!data.ReadString(ident)) { + return ERR_FLATTEN_OBJECT; + } + + if (!data.ReadUint64(netCapabilities)) { + return ERR_FLATTEN_OBJECT; + } + + int32_t ret = RegisterNetSupplier(netType, ident, netCapabilities); + if (ret == ERR_NO_NETWORK || ret == ERR_NO_SUPPLIER) { + NETMGR_LOGE("Register network supplier failed, error code:[%{public}d].", ret); + ret = NET_CONN_ERR_INVALID_SUPPLIER_ID; + } + if (!reply.WriteInt32(ret)) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetConnServiceStub::OnUnregisterNetSupplier(MessageParcel &data, MessageParcel &reply) +{ + uint32_t supplierId; + if (!data.ReadUint32(supplierId)) { + return ERR_FLATTEN_OBJECT; + } + + int32_t ret = UnregisterNetSupplier(supplierId); + if (!reply.WriteInt32(ret)) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetConnServiceStub::OnRegisterNetConnCallback(MessageParcel &data, MessageParcel &reply) +{ + int32_t result = NET_CONN_SUCCESS; + sptr remote = data.ReadRemoteObject(); + if (remote == nullptr) { + NETMGR_LOGE("Callback ptr is nullptr."); + result = NET_CONN_ERR_GET_REMOTE_OBJECT_FAILED; + reply.WriteInt32(result); + return result; + } + + sptr callback = iface_cast(remote); + if (callback == nullptr) { + result = NET_CONN_ERR_INPUT_NULL_PTR; + reply.WriteInt32(result); + return result; + } + + result = ConvertCode(RegisterNetConnCallback(callback)); + reply.WriteInt32(result); + return result; +} + +int32_t NetConnServiceStub::OnRegisterNetConnCallbackBySpecifier(MessageParcel &data, MessageParcel &reply) +{ + sptr netSpecifier = NetSpecifier::Unmarshalling(data); + + int32_t result = ERR_FLATTEN_OBJECT; + sptr remote = data.ReadRemoteObject(); + if (remote == nullptr) { + NETMGR_LOGE("callback ptr is nullptr."); + reply.WriteInt32(result); + return result; + } + + sptr callback = iface_cast(remote); + if (callback == nullptr) { + result = NET_CONN_ERR_INPUT_NULL_PTR; + reply.WriteInt32(result); + return result; + } + + result = ConvertCode(RegisterNetConnCallback(netSpecifier, callback)); + reply.WriteInt32(result); + return result; +} + +int32_t NetConnServiceStub::OnUnregisterNetConnCallback(MessageParcel &data, MessageParcel &reply) +{ + int32_t result = ERR_FLATTEN_OBJECT; + sptr remote = data.ReadRemoteObject(); + if (remote == nullptr) { + NETMGR_LOGE("callback ptr is nullptr."); + reply.WriteInt32(result); + return result; + } + + sptr callback = iface_cast(remote); + if (callback == nullptr) { + result = NET_CONN_ERR_INPUT_NULL_PTR; + reply.WriteInt32(result); + return result; + } + + result = ConvertCode(UnregisterNetConnCallback(callback)); + reply.WriteInt32(result); + return result; +} + +int32_t NetConnServiceStub::OnUnregisterNetConnCallbackBySpecifier(MessageParcel &data, MessageParcel &reply) +{ + sptr netSpecifier = NetSpecifier::Unmarshalling(data); + + int32_t result = ERR_FLATTEN_OBJECT; + sptr remote = data.ReadRemoteObject(); + if (remote == nullptr) { + NETMGR_LOGE("callback ptr is nullptr."); + reply.WriteInt32(result); + return result; + } + + sptr callback = iface_cast(remote); + if (callback == nullptr) { + result = NET_CONN_ERR_INPUT_NULL_PTR; + reply.WriteInt32(result); + return result; + } + + result = ConvertCode(UnregisterNetConnCallback(netSpecifier, callback)); + reply.WriteInt32(result); + return result; +} + +int32_t NetConnServiceStub::OnUpdateNetSupplierInfo(MessageParcel &data, MessageParcel &reply) +{ + uint32_t supplierId; + if (!data.ReadUint32(supplierId)) { + return ERR_FLATTEN_OBJECT; + } + + sptr netSupplierInfo = NetSupplierInfo::Unmarshalling(data); + int32_t ret = UpdateNetSupplierInfo(supplierId, netSupplierInfo); + if (!reply.WriteInt32(ret)) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetConnServiceStub::OnUpdateNetCapabilities(MessageParcel &data, MessageParcel &reply) +{ + uint32_t supplierId; + uint64_t netCapabilities; + + if (!data.ReadUint32(supplierId)) { + return ERR_FLATTEN_OBJECT; + } + + if (!data.ReadUint64(netCapabilities)) { + return ERR_FLATTEN_OBJECT; + } + + NETMGR_LOGI("stub execute UpdateNetCapabilities"); + int32_t ret = UpdateNetCapabilities(supplierId, netCapabilities); + if (!reply.WriteInt32(ret)) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetConnServiceStub::OnUpdateNetLinkInfo(MessageParcel &data, MessageParcel &reply) +{ + uint32_t supplierId; + + if (!data.ReadUint32(supplierId)) { + return ERR_FLATTEN_OBJECT; + } + + sptr netLinkInfo = NetLinkInfo::Unmarshalling(data); + + int32_t ret = UpdateNetLinkInfo(supplierId, netLinkInfo); + if (!reply.WriteInt32(ret)) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetConnServiceStub::ConvertCode(int32_t internalCode) +{ + switch (internalCode) { + case static_cast(ERR_NONE): + return static_cast(NET_CONN_SUCCESS); + case static_cast(ERR_SERVICE_NULL_PTR): + return static_cast(NET_CONN_ERR_INPUT_NULL_PTR); + case static_cast(ERR_NET_TYPE_NOT_FOUND): + return static_cast(NET_CONN_ERR_NET_TYPE_NOT_FOUND); + case static_cast(ERR_NO_ANY_NET_TYPE): + return static_cast(NET_CONN_ERR_NO_ANY_NET_TYPE); + case static_cast(ERR_NO_REGISTERED): + return static_cast(NET_CONN_ERR_NO_REGISTERED); + default: + break; + } + + return static_cast(NET_CONN_ERR_INTERNAL_ERROR); +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/src/net_conn_service.cpp b/services/netconnmanager/src/net_conn_service.cpp new file mode 100755 index 0000000..78cb2a8 --- /dev/null +++ b/services/netconnmanager/src/net_conn_service.cpp @@ -0,0 +1,494 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_conn_service.h" + +#include "system_ability_definition.h" + +#include "net_conn_types.h" +#include "net_service.h" +#include "net_supplier.h" +#include "netd_controller.h" +#include "net_mgr_log_wrapper.h" +#include "broadcast_manager.h" + +namespace OHOS { +namespace NetManagerStandard { +const bool REGISTER_LOCAL_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +NetConnService::NetConnService() + : SystemAbility(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID, true), registerToService_(false), + state_(STATE_STOPPED) +{ +} + +NetConnService::~NetConnService() {} + +void NetConnService::OnStart() +{ + if (state_ == STATE_RUNNING) { + NETMGR_LOGI("the state is already running"); + return; + } + if (!Init()) { + NETMGR_LOGE("init failed"); + return; + } + state_ = STATE_RUNNING; +} + +void NetConnService::OnStop() +{ + state_ = STATE_STOPPED; + registerToService_ = false; +} + +bool NetConnService::Init() +{ + if (!REGISTER_LOCAL_RESULT) { + NETMGR_LOGE("Register to local sa manager failed"); + registerToService_ = false; + return false; + } + if (!registerToService_) { + if (!Publish(DelayedSingleton::GetInstance().get())) { + NETMGR_LOGE("Register to sa manager failed"); + return false; + } + registerToService_ = true; + } + return true; +} + +int32_t NetConnService::SystemReady() +{ + NETMGR_LOGI("System ready."); + return 0; +} + +int32_t NetConnService::RegisterNetSupplier(uint32_t netType, const std::string &ident, uint64_t netCapabilities) +{ + NETMGR_LOGI("register supplier, netType[%{public}d] ident[%{public}s] netCapabilities[%{public}lld]", + netType, ident.c_str(), netCapabilities); + + // According to netType, ident, get the supplier from the list and save the supplierId in the list + if (netType >= NET_TYPE_MAX || netType <= NET_TYPE_UNKNOWN) { + NETMGR_LOGE("netType parameter invalid"); + return ERR_INVALID_NETORK_TYPE; + } + + sptr supplier = GetNetSupplierFromList(netType, ident); + if (supplier != nullptr) { + NETMGR_LOGI("supplier already exists."); + return supplier->GetSupplierId(); + } + + // If there is no supplier in the list, create a supplier + supplier = (std::make_unique(static_cast(netType), ident)).release(); + if (supplier == nullptr) { + NETMGR_LOGE("supplier is nullptr"); + return ERR_NO_SUPPLIER; + } + + // create network + sptr network = (std::make_unique(supplier)).release(); + if (network == nullptr) { + NETMGR_LOGE("network is nullptr"); + return ERR_NO_NETWORK; + } + + // create service by netCapabilities + NetworkType type = static_cast(netType); + if (netCapabilities & NET_CAPABILITIES_INTERNET) { + auto service = std::make_unique(ident, type, NET_CAPABILITIES_INTERNET, network).release(); + if (service != nullptr) { + netServices_.push_back(service); + defaultNetService_ = service; + } + } + + if (netCapabilities & NET_CAPABILITIES_MMS) { + auto service = std::make_unique(ident, type, NET_CAPABILITIES_MMS, network).release(); + if (service != nullptr) { + netServices_.push_back(service); + } + } + + // save supplier, network to list + netSupplier_.push_back(supplier); + networks_.push_back(network); + NETMGR_LOGI("netSupplier_ size[%{public}d] networks_ size[%{public}d] netServices_ size[%{public}d]", + netSupplier_.size(), networks_.size(), netServices_.size()); + + // connect service + if (defaultNetService_ != nullptr) { + NETMGR_LOGI("service is connecting..."); + int32_t result = defaultNetService_->ServiceConnect(); + if (result != ERR_SERVICE_REQUEST_SUCCESS) { + NETMGR_LOGE("connect service failed, errCode: %{public}X", result); + reConnectTimer_.StartOnce(CONNECT_SERVICE_WAIT_TIME, NetConnService::ReConnectServiceTask); + } + } + + return supplier->GetSupplierId(); +} + +void NetConnService::ReConnectServiceTask() +{ + NETMGR_LOGI("defaultNetService reConnectService start"); + int32_t result = DelayedSingleton::GetInstance()->ReConnectService(); + if (result != ERR_SERVICE_REQUEST_SUCCESS) { + NETMGR_LOGE("service reconnection failed! errCode:%{public}d", result); + return; + } + + NETMGR_LOGI("defaultNetService reConnectService successfully!"); +} + +int32_t NetConnService::ReConnectService() +{ + if (defaultNetService_ == nullptr) { + NETMGR_LOGE("default service is nullptr"); + return ERR_SERVICE_NULL_PTR; + } + if (defaultNetService_->IsConnected() || defaultNetService_->IsConnecting()) { + defaultNetService_->ServiceDisConnect(); + } + NETMGR_LOGI("service is connecting..."); + return defaultNetService_->ServiceConnect(); +} + +int32_t NetConnService::UnregisterNetSupplier(uint32_t supplierId) +{ + NETMGR_LOGI("UnregisterNetSupplier supplierId[%{public}d]", supplierId); + // Remove supplier from the list based on supplierId + sptr supplier = GetNetSupplierFromListById(supplierId); + if (supplier == nullptr) { + NETMGR_LOGE("supplier doesn't exist."); + return ERR_NO_SUPPLIER; + } + + sptr network = GetNetworkFromListBySupplierId(supplierId); + if (network == nullptr) { + NETMGR_LOGE("GetNetworkFromListBySupplierId get error, network is nullptr"); + DeleteSupplierFromListById(supplierId); + return ERR_NO_NETWORK; + } + + DeleteServiceFromListByNet(*network); + DeleteNetworkFromListBySupplierId(supplierId); + DeleteSupplierFromListById(supplierId); + NETMGR_LOGI("netSupplier_ size[%{public}d], networks_ size[%{public}d], netServices_ size[%{public}d]", + netSupplier_.size(), networks_.size(), netServices_.size()); + + return ERR_NONE; +} + +int32_t NetConnService::RegisterNetConnCallback(const sptr &callback) +{ + if (callback == nullptr) { + NETMGR_LOGE("The parameter callback is null"); + return ERR_SERVICE_NULL_PTR; + } + + if (netServices_.empty()) { + NETMGR_LOGE("netServices_ is empty"); + return ERR_NO_ANY_NET_TYPE; + } + + for (auto &netService : netServices_) { + netService->RegisterNetConnCallback(callback); + } + + return ERR_NONE; +} + +int32_t NetConnService::RegisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) +{ + if (netSpecifier == nullptr || callback == nullptr) { + NETMGR_LOGE("The parameter of netSpecifier or callback is null"); + return ERR_SERVICE_NULL_PTR; + } + + if (netServices_.empty()) { + NETMGR_LOGE("netServices_ is empty"); + return ERR_NO_ANY_NET_TYPE; + } + + for (auto it = netServices_.begin(); it != netServices_.end(); ++it) { + NetCapabilities netCapabilit = (*it)->GetNetCapability(); + if ((*it)->GetNetworkType() == netSpecifier->netType_ + && (netCapabilit & netSpecifier->netCapabilities_) == netCapabilit) { + (*it)->RegisterNetConnCallback(callback); + return ERR_NONE; + } + } + + return ERR_NET_TYPE_NOT_FOUND; +} + +int32_t NetConnService::UnregisterNetConnCallback(const sptr &callback) +{ + if (callback == nullptr) { + NETMGR_LOGE("callback is null"); + return ERR_SERVICE_NULL_PTR; + } + + if (netServices_.empty()) { + NETMGR_LOGE("netServices_ is empty"); + return ERR_NO_ANY_NET_TYPE; + } + + for (auto &netService : netServices_) { + netService->UnregisterNetConnCallback(callback); + } + + return ERR_NONE; +} + +int32_t NetConnService::UnregisterNetConnCallback(const sptr &netSpecifier, + const sptr &callback) +{ + if (netSpecifier == nullptr || callback == nullptr) { + NETMGR_LOGE("The parameter of netSpecifier or callback is null"); + return ERR_SERVICE_NULL_PTR; + } + + if (netServices_.empty()) { + NETMGR_LOGE("netServices_ is empty"); + return ERR_NO_ANY_NET_TYPE; + } + + for (auto it = netServices_.begin(); it != netServices_.end(); ++it) { + NetCapabilities netCapabilit = (*it)->GetNetCapability(); + if ((*it)->GetNetworkType() == netSpecifier->netType_ + && (netCapabilit & netSpecifier->netCapabilities_) == netCapabilit) { + return (*it)->UnregisterNetConnCallback(callback); + } + } + + return ERR_NET_TYPE_NOT_FOUND; +} + +int32_t NetConnService::UpdateNetSupplierInfo(uint32_t supplierId, const sptr &netSupplierInfo) +{ + NETMGR_LOGI("Update supplier info: supplierId[%{public}d]", supplierId); + if (netSupplierInfo == nullptr) { + NETMGR_LOGE("netSupplierInfo is nullptr"); + return ERR_INVALID_PARAMS; + } + + NETMGR_LOGI("Update supplier info: netSupplierInfo[%{public}s]", netSupplierInfo->ToString("").c_str()); + + // According to supplierId, get the supplier from the list + sptr supplier = GetNetSupplierFromListById(supplierId); + if (supplier == nullptr) { + NETMGR_LOGE("supplier is nullptr"); + return ERR_NO_SUPPLIER; + } + + // Call NetSupplier class to update network connection status information + sptr network = GetNetworkFromListBySupplierId(supplier->GetSupplierId()); + if (network == nullptr) { + NETMGR_LOGE("network is nullptr"); + return ERR_NO_NETWORK; + } + network->UpdateNetSupplierInfo(*netSupplierInfo); + + return ERR_NONE; +} + +int32_t NetConnService::UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities) +{ + NETMGR_LOGI("supplierId[%{public}d] netCapabilities[%{public}lld]", supplierId, netCapabilities); + // According to supplierId, get the supplier from the list + sptr supplier = GetNetSupplierFromListById(supplierId); + if (supplier == nullptr) { + NETMGR_LOGE("supplier is nullptr"); + return ERR_NO_SUPPLIER; + } + + // According to netId, get network from the list + sptr network = GetNetworkFromListBySupplierId(supplier->GetSupplierId()); + if (network == nullptr) { + NETMGR_LOGE("network is nullptr"); + return ERR_NO_NETWORK; + } + auto type = supplier->GetNetSupplierType(); + auto ident = supplier->GetNetSupplierIdent(); + // Create or delete network services based on the netCapabilities + if (netCapabilities & NET_CAPABILITIES_INTERNET) { + if (!IsServiceInList(network->GetNetId(), NET_CAPABILITIES_INTERNET)) { + auto service = std::make_unique(ident, type, NET_CAPABILITIES_INTERNET, network).release(); + netServices_.push_back(service); + } + } else { + if (IsServiceInList(network->GetNetId(), NET_CAPABILITIES_INTERNET)) { + DeleteServiceFromListByCap(network->GetNetId(), NET_CAPABILITIES_INTERNET); + } + } + + if (netCapabilities & NET_CAPABILITIES_MMS) { + if (!IsServiceInList(network->GetNetId(), NET_CAPABILITIES_MMS)) { + auto service = std::make_unique(ident, type, NET_CAPABILITIES_MMS, network).release(); + netServices_.push_back(service); + } + } else { + if (IsServiceInList(network->GetNetId(), NET_CAPABILITIES_MMS)) { + DeleteServiceFromListByCap(network->GetNetId(), NET_CAPABILITIES_MMS); + } + } + NETMGR_LOGI("netSupplier_ size[%{public}d], networks_ size[%{public}d], netServices_ size[%{public}d]", + netSupplier_.size(), networks_.size(), netServices_.size()); + return ERR_NONE; +} + +int32_t NetConnService::UpdateNetLinkInfo(uint32_t supplierId, const sptr &netLinkInfo) +{ + NETMGR_LOGI("supplierId[%{public}d]", supplierId); + if (netLinkInfo == nullptr) { + NETMGR_LOGE("netLinkInfo is nullptr"); + return ERR_INVALID_PARAMS; + } + + NETMGR_LOGI("Update netlink info: netLinkInfo[%{public}s]", netLinkInfo->ToString("").c_str()); + // According to supplierId, get the supplier from the list + sptr supplier = GetNetSupplierFromListById(supplierId); + if (supplier == nullptr) { + NETMGR_LOGE("supplier is nullptr"); + return ERR_NO_SUPPLIER; + } + // According to supplier id, get network from the list + sptr network = GetNetworkFromListBySupplierId(supplier->GetSupplierId()); + if (network == nullptr) { + NETMGR_LOGE("network is nullptr"); + return ERR_NO_NETWORK; + } + // Call Network class to update network link attribute information + network->UpdateNetLinkInfo(*netLinkInfo); + return ERR_NONE; +} + +sptr NetConnService::GetNetSupplierFromList( + uint32_t netType, const std::string &ident) +{ + for (auto it = netSupplier_.begin(); it != netSupplier_.end(); ++it) { + auto supplierType = (*it)->GetNetSupplierType(); + auto supplierIdent = (*it)->GetNetSupplierIdent(); + if ((netType == supplierType) && (ident.compare(supplierIdent) == 0)) { + return *it; + } + } + + NETMGR_LOGE("net supplier is nullptr"); + return nullptr; +} + +sptr NetConnService::GetNetSupplierFromListById(uint32_t supplierId) +{ + for (auto it = netSupplier_.begin(); it != netSupplier_.end(); ++it) { + auto id = (*it)->GetSupplierId(); + if (supplierId == id) { + return *it; + } + } + + NETMGR_LOGE("net supplier is nullptr"); + return nullptr; +} + +void NetConnService::DeleteSupplierFromListById(uint32_t supplierId) +{ + for (auto it = netSupplier_.begin(); it != netSupplier_.end(); ++it) { + auto id = (*it)->GetSupplierId(); + if (supplierId == id) { + netSupplier_.erase(it); + return; + } + } +} + +void NetConnService::DeleteNetworkFromListBySupplierId(uint32_t supplierId) +{ + for (auto it = networks_.begin(); it != networks_.end(); ++it) { + sptr netSupplier = (*it)->GetNetSupplier(); + if ((netSupplier != nullptr) && (netSupplier->GetSupplierId() == supplierId)) { + networks_.erase(it); + return; + } + } +} + +sptr NetConnService::GetNetworkFromListBySupplierId(uint32_t supplierId) +{ + for (auto it = networks_.begin(); it != networks_.end(); ++it) { + sptr netSupplier = (*it)->GetNetSupplier(); + if ((netSupplier != nullptr) && (netSupplier->GetSupplierId() == supplierId)) { + return *it; + } + } + + NETMGR_LOGE("network is nullptr"); + return nullptr; +} + +void NetConnService::DeleteServiceFromListByNet(const Network &network) +{ + sptr currNetwork = nullptr; + for (auto it = netServices_.begin(); it != netServices_.end();) { + currNetwork = (*it)->GetNetwork(); + if (currNetwork != nullptr && *currNetwork == network) { + netServices_.erase(it++); + } else { + ++it; + } + } +} + +bool NetConnService::DeleteServiceFromListByCap(int32_t netId, const NetCapabilities &netCapability) +{ + sptr network = nullptr; + for (auto it = netServices_.begin(); it != netServices_.end(); ++it) { + network = (*it)->GetNetwork(); + if (network == nullptr) { + continue; + } + if ((network->GetNetId() == netId) && (netCapability == (*it)->GetNetCapability())) { + netServices_.erase(it); + return true; + } + } + + return false; +} + +bool NetConnService::IsServiceInList(int32_t netId, const NetCapabilities &netCapability) const +{ + sptr network = nullptr; + for (auto it = netServices_.begin(); it != netServices_.end(); ++it) { + network = (*it)->GetNetwork(); + if (network == nullptr) { + continue; + } + if ((network->GetNetId() == netId) && (netCapability == (*it)->GetNetCapability())) { + return true; + } + } + + return false; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/src/net_controller/net_controller_factory.cpp b/services/netconnmanager/src/net_controller/net_controller_factory.cpp new file mode 100755 index 0000000..28bc387 --- /dev/null +++ b/services/netconnmanager/src/net_controller/net_controller_factory.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_controller_factory.h" + +#include "net_mgr_log_wrapper.h" +#include "telephony_controller.h" + +namespace OHOS { +namespace NetManagerStandard { +NetControllerFactory::NetControllerFactory() {} +NetControllerFactory::~NetControllerFactory() {} + +sptr NetControllerFactory::MakeNetController(uint32_t netType) +{ + NETMGR_LOGI("make controller netType[%{public}d]", netType); + sptr netController = GetNetControllerFromMap(netType); + if (netController != nullptr) { + return netController; + } + NETMGR_LOGI("factory need create netController"); + + switch (netType) { + case NET_TYPE_CELLULAR: + NETMGR_LOGI("factory create TelephonyController"); + netController = (std::make_unique()).release(); + netControllers.insert(std::make_pair(NET_TYPE_CELLULAR, netController)); + break; + default: + break; + } + + return netController; +} + +sptr NetControllerFactory::GetNetControllerFromMap(uint32_t netType) +{ + auto it = netControllers.find(netType); + if (it != netControllers.end()) { + return it->second; + } + NETMGR_LOGI("INetController* is not found, return null"); + return nullptr; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/netconnmanager/src/net_controller/telephony_controller.cpp b/services/netconnmanager/src/net_controller/telephony_controller.cpp new file mode 100755 index 0000000..74e10b5 --- /dev/null +++ b/services/netconnmanager/src/net_controller/telephony_controller.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "telephony_controller.h" + +#include "cellular_data_client.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +TelephonyController::TelephonyController() {}; + +int32_t TelephonyController::RequestNetwork(const std::string &ident, NetCapabilities netCapabilitiy) +{ + NETMGR_LOGI("Request telephony network."); + return Telephony::CellularDataClient::GetInstance().RequestNet(ident, static_cast(netCapabilitiy)); +} + +int32_t TelephonyController::ReleaseNetwork(const std::string &ident, NetCapabilities netCapabilitiy) +{ + NETMGR_LOGI("Release telephony network."); + return Telephony::CellularDataClient::GetInstance().ReleaseNet(ident, static_cast(netCapabilitiy)); +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/src/net_id_manager.cpp b/services/netconnmanager/src/net_id_manager.cpp new file mode 100755 index 0000000..2fbd55b --- /dev/null +++ b/services/netconnmanager/src/net_id_manager.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_id_manager.h" + +namespace OHOS { +namespace NetManagerStandard { +NetIdManager::NetIdManager() {} + +NetIdManager::~NetIdManager() {} + +int32_t NetIdManager::ReserveNetId() +{ + std::lock_guard lck(mtx_); + for (int32_t i = MIN_NET_ID; i <= maxNetId_; ++i) { + if (lastNetId_ < maxNetId_) { + ++lastNetId_; + } else { + lastNetId_ = MIN_NET_ID; + } + if (netIdInUse_.find(lastNetId_) == netIdInUse_.end()) { + netIdInUse_.insert(std::pair(lastNetId_, true)); + break; + } + } + + return lastNetId_; +} + +void NetIdManager::ReleaseNetId(int32_t netId) +{ + std::lock_guard lck(mtx_); + auto it = netIdInUse_.find(netId); + if (it != netIdInUse_.end()) { + netIdInUse_.erase(it); + } +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/netconnmanager/src/net_service.cpp b/services/netconnmanager/src/net_service.cpp new file mode 100755 index 0000000..f88836d --- /dev/null +++ b/services/netconnmanager/src/net_service.cpp @@ -0,0 +1,301 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_service.h" + +#include "net_conn_types.h" +#include "broadcast_manager.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetService::NetService( + const std::string &ident, NetworkType networkType, NetCapabilities netCapability, sptr &network) + : ident_(ident), networkType_(networkType), netCapability_(netCapability), network_(network) +{} + +void NetService::SetIdent(const std::string &ident) +{ + ident_ = ident; +} + +void NetService::SetNetworkType(const NetworkType &networkType) +{ + networkType_ = networkType; +} + +void NetService::SetNetCapability(const NetCapabilities &netCapability) +{ + netCapability_ = netCapability; +} + +void NetService::SetServiceState(const ServiceState &serviceState) +{ + state_ = serviceState; +} + +std::string NetService::GetIdent() const +{ + return ident_; +} + +NetworkType NetService::GetNetworkType() const +{ + return networkType_; +} + +NetCapabilities NetService::GetNetCapability() const +{ + return netCapability_; +} + +ServiceState NetService::GetServiceState() const +{ + return state_; +} + +sptr NetService::GetNetwork() const +{ + return network_; +} + +int32_t NetService::ServiceConnect() +{ + NETMGR_LOGI("service connect"); + if (IsConnecting()) { + NETMGR_LOGI("this service is connecting"); + return ERR_SERVICE_CONNECTING; + } + if (IsConnected()) { + NETMGR_LOGI("this service is already connected"); + return ERR_SERVICE_CONNECTED; + } + + // Filtering is not a custom network service type + switch (networkType_) { + case NET_TYPE_CELLULAR: + break; + case NET_TYPE_UNKNOWN: + default: + NETMGR_LOGE("thWe parameter networkType_[%{public}d] passed in is invalid", networkType_); + return ERR_INVALID_NETORK_TYPE; + } + UpdateServiceState(SERVICE_STATE_IDLE); + + // Call network class to activate the network + if (NetworkConnect() < 0) { + NETMGR_LOGE("this service request network failed"); + + UpdateServiceState(SERVICE_STATE_FAILURE); + NetworkDisConnect(); + UpdateServiceState(SERVICE_STATE_DISCONNECTED); + UpdateServiceState(SERVICE_STATE_IDLE); + return ERR_SERVICE_REQUEST_CONNECT_FAIL; + } + // Update the network status after activating the network successfully + UpdateServiceState(SERVICE_STATE_READY); + NETMGR_LOGI("this service request network is successful"); + + return ERR_SERVICE_REQUEST_SUCCESS; +} + +int32_t NetService::ServiceDisConnect() +{ + NETMGR_LOGI("service disconnect"); + if (state_ == SERVICE_STATE_DISCONNECTING) { + NETMGR_LOGI("this service is disconnecting"); + return ERR_SERVICE_DISCONNECTING; + } + if (state_ == SERVICE_STATE_DISCONNECTED) { + NETMGR_LOGI("this service has been disconnected"); + return ERR_SERVICE_DISCONNECTED_SUCCESS; + } + + UpdateServiceState(SERVICE_STATE_DISCONNECTING); + NETMGR_LOGI("NetworkDisConnect start"); + // Call network class to deactivate the network + if (NetworkDisConnect() < 0) { + NETMGR_LOGE("this service failed to disconnect"); + UpdateServiceState(SERVICE_STATE_FAILURE); + return ERR_SERVICE_DISCONNECTED_FAIL; + } + // Update the network status after deactivating the network successfully + UpdateServiceState(SERVICE_STATE_DISCONNECTED); + UpdateServiceState(SERVICE_STATE_IDLE); + NETMGR_LOGI("this service successfully disconnected"); + + return ERR_SERVICE_DISCONNECTED_SUCCESS; +} + +int32_t NetService::ServiceAutoConnect() +{ + NETMGR_LOGI("service auto connect"); + return ServiceConnect(); +} + +int32_t NetService::NetworkConnect() +{ + int32_t retCode = -1; + + UpdateServiceState(SERVICE_STATE_CONNECTING); + NETMGR_LOGI("execute NetworkConnect()"); + // Call Network class activate the network + if (network_->NetworkConnect(netCapability_)) { + retCode = 0; + } + NETMGR_LOGI("connect is [%{public}s]", (retCode > -1) ? "successfull" : "failed"); + return retCode; +} + +int32_t NetService::NetworkDisConnect() +{ + int32_t retCode = -1; + // Call Network class deactivate the network + if (network_->NetworkDisconnect(netCapability_)) { + retCode = 0; + } + NETMGR_LOGI("disconnect is [%{public}s]", (retCode > -1) ? "successfull" : "failed"); + return retCode; +} + +void NetService::UpdateServiceState(ServiceState serviceState) +{ + switch (serviceState) { + case SERVICE_STATE_IDLE: + case SERVICE_STATE_CONNECTING: + case SERVICE_STATE_READY: + case SERVICE_STATE_CONNECTED: + case SERVICE_STATE_DISCONNECTING: + case SERVICE_STATE_DISCONNECTED: + case SERVICE_STATE_FAILURE: + state_ = serviceState; + break; + case SERVICE_STATE_UNKNOWN: + default: + state_ = SERVICE_STATE_FAILURE; + break; + } + + BroadcastInfo info; + // EventFwk::CommonEventSupport::COMMON_EVENT_NETMANAGER_CONNECTION_STATE_CHANGED + info.action = "usual.event.netmanager.NETMANAGER_CONNECTION_STATE_CHANGED"; + info.data = "Net Manager Connection State Changed"; + info.code = static_cast(serviceState); + info.ordered = true; + std::string netTypeName = std::to_string(static_cast(networkType_)); + std::map param = {{"NetType", netTypeName}}; + DelayedSingleton::GetInstance()->SendBroadcast(info, param); + + sptr netConnCallback = (std::make_unique()).release(); + if (netConnCallback == nullptr) { + NETMGR_LOGE("make_unique() failed"); + return; + } + netConnCallback->netState_ = static_cast(serviceState); + netConnCallback->netType_ = static_cast(networkType_); + NotifyNetConnStateChanged(netConnCallback); + + NETMGR_LOGI("serviceState is [%{public}d]", state_); +} + +bool NetService::IsConnecting() const +{ + bool isConnecting = false; + + switch (state_) { + case SERVICE_STATE_UNKNOWN: + case SERVICE_STATE_FAILURE: + case SERVICE_STATE_IDLE: + isConnecting = network_->IsNetworkConnecting(); + break; + case SERVICE_STATE_CONNECTING: + isConnecting = true; + break; + case SERVICE_STATE_READY: + case SERVICE_STATE_CONNECTED: + case SERVICE_STATE_DISCONNECTING: + case SERVICE_STATE_DISCONNECTED: + default: + break; + } + + NETMGR_LOGI("isConnecting is [%{public}d]", isConnecting); + return isConnecting; +} + +bool NetService::IsConnected() const +{ + bool isConnected = false; + switch (state_) { + case SERVICE_STATE_UNKNOWN: + case SERVICE_STATE_FAILURE: + case SERVICE_STATE_IDLE: + case SERVICE_STATE_CONNECTING: + case SERVICE_STATE_DISCONNECTING: + case SERVICE_STATE_DISCONNECTED: + break; + case SERVICE_STATE_READY: + case SERVICE_STATE_CONNECTED: + isConnected = true; + break; + default: + break; + } + NETMGR_LOGI("isConnected is [%{public}d]", isConnected); + return isConnected; +} + +void NetService::RegisterNetConnCallback(const sptr &callback) +{ + if (callback == nullptr) { + NETMGR_LOGE("The parameter callback is null"); + return; + } + + for (auto iter = netConnCallback_.begin(); iter != netConnCallback_.end(); ++iter) { + if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) { + NETMGR_LOGI("netConnCallback_ had this callback"); + return; + } + } + netConnCallback_.emplace_back(callback); +} + +int32_t NetService::UnregisterNetConnCallback(const sptr &callback) +{ + if (callback == nullptr) { + NETMGR_LOGE("The parameter of callback is null"); + return ERR_SERVICE_NULL_PTR; + } + + for (auto iter = netConnCallback_.begin(); iter != netConnCallback_.end(); ++iter) { + if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) { + netConnCallback_.erase(iter); + return ERR_NONE; + } + } + + return ERR_NO_REGISTERED; +} + +int32_t NetService::NotifyNetConnStateChanged(const sptr &info) +{ + for (const auto &callback : netConnCallback_) { + callback->NetConnStateChanged(info); + } + + return ERR_NONE; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/src/net_supplier.cpp b/services/netconnmanager/src/net_supplier.cpp new file mode 100755 index 0000000..1c7d9bb --- /dev/null +++ b/services/netconnmanager/src/net_supplier.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_supplier.h" + +#include + +#include "net_controller_factory.h" +#include "net_service.h" +#include "net_mgr_log_wrapper.h" +#include "telephony_controller.h" + +namespace OHOS { +namespace NetManagerStandard { +static std::atomic g_nextNetSupplierId = 0x03EB; + +NetSupplier::NetSupplier(NetworkType netSupplierType, const std::string &netSupplierIdent) +{ + sptr netController = + DelayedSingleton::GetInstance().get()->MakeNetController(netSupplierType); + if (netController != nullptr) { + netController_ = netController; + } + netSupplierType_ = netSupplierType; + netSupplierIdent_ = netSupplierIdent; + supplierId_ = g_nextNetSupplierId++; +} + +bool NetSupplier::operator==(const NetSupplier &netSupplier) const +{ + return supplierId_ == netSupplier.supplierId_ && + netSupplierType_ == netSupplier.netSupplierType_ && + netSupplierIdent_ == netSupplier.netSupplierIdent_; +} + +NetworkType NetSupplier::GetNetSupplierType() const +{ + return netSupplierType_; +} + +std::string NetSupplier::GetNetSupplierIdent() const +{ + return netSupplierIdent_; +} + +bool NetSupplier::SupplierConnection(NetCapabilities netCapabilities) +{ + NETMGR_LOGI("param ident[%{public}s] netCapabilities[%{public}lld]", netSupplierIdent_.c_str(), + static_cast(netCapabilities)); + if (netController_ == nullptr) { + NETMGR_LOGE("netController_ is nullptr"); + return false; + } + NETMGR_LOGI("execute RequestNetwork"); + int32_t errCode = netController_->RequestNetwork(netSupplierIdent_, netCapabilities); + NETMGR_LOGI("RequestNetwork errCode[%{public}d]", errCode); + if (errCode == REG_OK) { + connected_ = true; + return true; + } + + return false; +} + +bool NetSupplier::SupplierDisconnection(NetCapabilities netCapabilities) +{ + NETMGR_LOGI("param ident_[%{public}s] netCapabilities[%{public}lld]", netSupplierIdent_.c_str(), + static_cast(netCapabilities)); + if (netController_ == nullptr) { + NETMGR_LOGE("netController_ is nullptr"); + return false; + } + NETMGR_LOGI("execute ReleaseNetwork"); + int32_t errCode = netController_->ReleaseNetwork(netSupplierIdent_, netCapabilities); + NETMGR_LOGI("ReleaseNetwork errCode[%{public}d]", errCode); + if (errCode == REG_OK) { + connected_ = false; + return true; + } + return false; +} + +void NetSupplier::UpdateNetSupplierInfo(const NetSupplierInfo &netSupplierInfo) +{ + isAvailable_ = netSupplierInfo.isAvailable_; + isRoaming_ = netSupplierInfo.isRoaming_; + strength_ = netSupplierInfo.strength_; + frequency_ = netSupplierInfo.frequency_; + NETMGR_LOGI( + "isAvailable_[%{public}d] isRoaming_[%{public}d] strength_[%{public}d] " + "frequency_[%{public}d]", + isAvailable_, isRoaming_, strength_, frequency_); +} + +uint32_t NetSupplier::GetSupplierId() const +{ + return supplierId_; +} + +bool NetSupplier::GetConnected() const +{ + return connected_; +} + +bool NetSupplier::GetAvailable() const +{ + return isAvailable_; +} + +bool NetSupplier::GetRoaming() const +{ + return isRoaming_; +} + +bool NetSupplier::GetStrength() const +{ + return strength_; +} + +bool NetSupplier::GetFrequency() const +{ + return frequency_; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/netconnmanager/src/network.cpp b/services/netconnmanager/src/network.cpp new file mode 100755 index 0000000..a908604 --- /dev/null +++ b/services/netconnmanager/src/network.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "network.h" + +#include "net_id_manager.h" +#include "netd_controller.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +Network::Network(sptr &supplier) : supplier_(supplier) +{ + netId_ = DelayedSingleton::GetInstance()->ReserveNetId(); + NetdController::GetInstance()->CreateNetworkCache(netId_); +} + +Network::~Network() +{ + NetdController::GetInstance()->DestoryNetworkCache(netId_); +} + +bool Network::operator==(const Network &network) const +{ + return (supplier_ != nullptr && network.supplier_ != nullptr) && + *supplier_ == *(network.supplier_) && + netId_ == network.netId_; +} + +bool Network::NetworkConnect(const NetCapabilities &netCapability) +{ + NETMGR_LOGI("supplier is connecting"); + if (isConnected_) { + NETMGR_LOGI("supplier is connected"); + return true; + } + + // Call NetSupplier class to activate the network + NETMGR_LOGI("SupplierDisconnection processing"); + bool ret = supplier_->SupplierDisconnection(netCapability); + if (!ret) { + NETMGR_LOGE("connect failed"); + return ret; + } + + isConnecting_ = true; + isConnected_ = true; + return ret; +} + +bool Network::NetworkDisconnect(const NetCapabilities &netCapability) +{ + NETMGR_LOGI("supplier is disConnecting"); + if (!isConnecting_ && !isConnected_) { + NETMGR_LOGI("no connecting or connected"); + return false; + } + + // Call NetSupplier class to deactivate the network + NETMGR_LOGI("SupplierDisconnection processing"); + bool ret = supplier_->SupplierDisconnection(netCapability); + if (!ret) { + NETMGR_LOGE("disconnect failed"); + } + + return ret; +} + +bool Network::UpdateNetLinkInfo(const NetLinkInfo &netLinkInfo) +{ + NETMGR_LOGI("update net link information process"); + UpdateInterfaces(netLinkInfo); + UpdateRoutes(netLinkInfo); + UpdateDnses(netLinkInfo); + updateMtu(netLinkInfo); + netLinkInfo_ = netLinkInfo; + return true; +} + +int32_t Network::GetNetId() const +{ + return netId_; +} + +void Network::SetIpAdress(const INetAddr &ipAdress) +{ + ipAddr_ = ipAdress; +} + +void Network::SetDns(const INetAddr &dns) +{ + dns_ = dns; +} + +void Network::SetRoute(const Route &route) +{ + route_ = route; +} + +NetLinkInfo Network::GetNetLinkInfo() const +{ + return netLinkInfo_; +} + +INetAddr Network::GetIpAdress() const +{ + return ipAddr_; +} + +INetAddr Network::GetDns() const +{ + return dns_; +} + +Route Network::GetRoute() const +{ + return route_; +} + +sptr Network::GetNetSupplier() const +{ + return supplier_; +} + +bool Network::UpdateNetSupplierInfo(const NetSupplierInfo &netSupplierInfo) +{ + NETMGR_LOGI("process strart"); + supplier_->UpdateNetSupplierInfo(netSupplierInfo); + + if (!isPhyNetCreated_) { + std::string permission; + // Create a physical network + NetdController::GetInstance()->NetworkCreatePhysical(netId_, 0); + isPhyNetCreated_ = true; + } + return true; +} + +bool Network::IsNetworkConnecting() const +{ + return isConnecting_; +} + +void Network::SetConnected(bool connected) +{ + isConnected_ = connected; +} + +void Network::SetConnecting(bool connecting) +{ + isConnecting_ = connecting; +} + +void Network::UpdateInterfaces(const NetLinkInfo &netLinkInfo) +{ + if (netLinkInfo.ifaceName_ == netLinkInfo_.ifaceName_) { + return; + } + + // Call netd to add and remove interface + if (!netLinkInfo.ifaceName_.empty()) { + NetdController::GetInstance()->NetworkAddInterface(netId_, netLinkInfo.ifaceName_); + } + if (!netLinkInfo_.ifaceName_.empty()) { + NetdController::GetInstance()->NetworkRemoveInterface(netId_, netLinkInfo_.ifaceName_); + } +} + +void Network::UpdateRoutes(const NetLinkInfo &netLinkInfo) +{ + for (auto it = netLinkInfo.routeList_.begin(); it != netLinkInfo.routeList_.end(); ++it) { + const struct Route &route = *it; + if (std::find(netLinkInfo_.routeList_.begin(), netLinkInfo_.routeList_.end(), *it) == + netLinkInfo_.routeList_.end()) { + NetdController::GetInstance()->NetworkAddRoute( + netId_, route.iface_, route.destination_.address_, route.gateway_.address_); + } + } + + for (auto it = netLinkInfo_.routeList_.begin(); it != netLinkInfo_.routeList_.end(); ++it) { + const struct Route &route = *it; + if (std::find(netLinkInfo.routeList_.begin(), netLinkInfo.routeList_.end(), *it) == + netLinkInfo.routeList_.end()) { + NetdController::GetInstance()->NetworkRemoveRoute( + netId_, route.iface_, route.destination_.address_, route.gateway_.address_); + } + } +} + +void Network::UpdateDnses(const NetLinkInfo &netLinkInfo) +{ + std::vector servers; + std::vector doamains; + for (auto it = netLinkInfo.dnsList_.begin(); it != netLinkInfo.dnsList_.end(); ++it) { + auto dns = *it; + servers.push_back(dns.address_); + doamains.push_back(dns.hostName_); + } + // Call netd to set dns + NetdController::GetInstance()->SetResolverConfig(netId_, 0, 1, servers, doamains); +} + +void Network::updateMtu(const NetLinkInfo &netLinkInfo) +{ + if (netLinkInfo.mtu_ == netLinkInfo_.mtu_) { + return; + } + + NetdController::GetInstance()->InterfaceSetMtu(netLinkInfo.ifaceName_, netLinkInfo.mtu_); +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/test/BUILD.gn b/services/netconnmanager/test/BUILD.gn new file mode 100755 index 0000000..3ec7832 --- /dev/null +++ b/services/netconnmanager/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +group("unittest") { + testonly = true + deps = [] + deps += [ "unittest/net_conn_manager_test:unittest" ] +} diff --git a/services/netconnmanager/test/mock/BUILD.gn b/services/netconnmanager/test/mock/BUILD.gn new file mode 100755 index 0000000..801a9b0 --- /dev/null +++ b/services/netconnmanager/test/mock/BUILD.gn @@ -0,0 +1,13 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + diff --git a/services/netconnmanager/test/unittest/net_conn_manager_test/BUILD.gn b/services/netconnmanager/test/unittest/net_conn_manager_test/BUILD.gn new file mode 100755 index 0000000..4e39299 --- /dev/null +++ b/services/netconnmanager/test/unittest/net_conn_manager_test/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +SUBSYSTEM_DIR = "//foundation/communication" +NETMANAGER_BASE_ROOT = "$SUBSYSTEM_DIR/netmanager_standard" +INNERKITS_ROOT = "$NETMANAGER_BASE_ROOT/interfaces/innerkits" +NETCONNMANAGER_SOURCE_DIR = "$NETMANAGER_BASE_ROOT/services/netconnmanager" + +ohos_unittest("net_conn_manager_test") { + module_out_path = "netmanager_base/net_conn_manager_test" + + sources = [ + "$NETCONNMANAGER_INNERKITS_SOURCE_DIR/src/ipc/net_conn_callback_stub.cpp", + "$NETCONNMANAGER_SOURCE_DIR/src/ipc/net_conn_service_proxy.cpp", + "net_conn_callback_test.cpp", + "net_conn_manager_test.cpp", + ] + + include_dirs = [ + "$INNERKITS_ROOT/native/netconnmanager/include", + "$INNERKITS_ROOT/native/netconnmanager/include/ipc", + "$NETCONNMANAGER_SOURCE_DIR/include/ipc", + "$NETCONNMANAGER_SOURCE_DIR/include", + ] + + deps = [ + "$INNERKITS_ROOT/native/netconnmanager:net_conn_manager_if", + "$NETCONNMANAGER_SOURCE_DIR:net_conn_manager", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + ] + + external_deps = [ "ipc:ipc_core" ] + + defines = [ + "NETMGR_LOG_TAG = \"NetConnManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":net_conn_manager_test" ] +} diff --git a/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_callback_test.cpp b/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_callback_test.cpp new file mode 100755 index 0000000..10f6d66 --- /dev/null +++ b/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_callback_test.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_conn_callback_test.h" + +#include + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetConnCallbackTest::NetConnCallbackTest() {} + +NetConnCallbackTest::~NetConnCallbackTest() {} + +void NetConnCallbackTest::NotifyAll() +{ + std::unique_lock callbackLock(callbackMutex_); + cv_.notify_all(); +} + +void NetConnCallbackTest::WaitFor(int timeoutSecond) +{ + std::unique_lock callbackLock(callbackMutex_); + cv_.wait_for(callbackLock, std::chrono::seconds(timeoutSecond)); +} + +int32_t NetConnCallbackTest::NetConnStateChanged(const sptr &info) +{ + if (info == nullptr) { + NETMGR_LOGI("NetConnCallbackTest::NetConnStateChanged(), info is nullptr"); + return -1; + } + + NETMGR_LOGI("NetConnCallbackTest::NetConnStateChanged(), netState_:[%{public}d], netType_:[%{public}d]", + info->netState_, info->netType_); + + netState_ = info->netState_; + NotifyAll(); + + return 0; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_callback_test.h b/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_callback_test.h new file mode 100755 index 0000000..98da266 --- /dev/null +++ b/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_callback_test.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_CONN_CALLBACK_TEST_H +#define NET_CONN_CALLBACK_TEST_H + +#include +#include + +#include "net_conn_callback_stub.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetConnCallbackTest : public NetConnCallbackStub { +public: + NetConnCallbackTest(); + virtual ~NetConnCallbackTest() override; + int32_t NetConnStateChanged(const sptr &info) override; + + void WaitFor(int timeoutSecond); + + int GetNetState() const + { + return netState_; + } + +private: + void NotifyAll(); + int32_t netState_ = 0; + std::mutex callbackMutex_; + std::condition_variable cv_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_CONN_CALLBACK_TEST_H diff --git a/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_manager_test.cpp b/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_manager_test.cpp new file mode 100755 index 0000000..0aa631e --- /dev/null +++ b/services/netconnmanager/test/unittest/net_conn_manager_test/net_conn_manager_test.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "net_conn_client.h" +#include "net_conn_types.h" +#include "net_conn_callback_test.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +constexpr int WAIT_TIME_SECOND_LONG = 60; +using namespace testing::ext; +class NetConnManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + sptr GetUpdateLinkInfoSample() const; + + sptr GetINetConnCallbackSample() const; +}; + +void NetConnManagerTest::SetUpTestCase() {} + +void NetConnManagerTest::TearDownTestCase() {} + +void NetConnManagerTest::SetUp() {} + +void NetConnManagerTest::TearDown() {} + +sptr NetConnManagerTest::GetUpdateLinkInfoSample() const +{ + sptr netLinkInfo = (std::make_unique()).release(); + netLinkInfo->ifaceName_ = "test"; + netLinkInfo->domain_ = "test"; + + sptr netAddr = (std::make_unique()).release(); + netAddr->type_ = INetAddr::IPV4; + netAddr->family_ = 0x10; + netAddr->prefixlen_ = 0x17; + netAddr->address_ = "192.168.2.0"; + netAddr->netMask_ = "192.255.255.255"; + netAddr->hostName_ = "netAddr"; + netLinkInfo->netAddrList_.push_back(*netAddr); + + sptr dns = (std::make_unique()).release(); + dns->type_ = INetAddr::IPV4; + dns->family_ = 0x10; + dns->prefixlen_ = 0x17; + dns->address_ = "192.168.2.0"; + dns->netMask_ = "192.255.255.255"; + dns->hostName_ = "netAddr"; + netLinkInfo->dnsList_.push_back(*dns); + + sptr route = (std::make_unique()).release(); + route->iface_ = "iface0"; + route->destination_.type_ = INetAddr::IPV4; + route->destination_.family_ = 0x10; + route->destination_.prefixlen_ = 0x17; + route->destination_.address_ = "192.168.2.0"; + route->destination_.netMask_ = "192.255.255.255"; + route->destination_.hostName_ = "netAddr"; + route->gateway_.type_ = INetAddr::IPV4; + route->gateway_.family_ = 0x10; + route->gateway_.prefixlen_ = 0x17; + route->gateway_.address_ = "192.168.2.0"; + route->gateway_.netMask_ = "192.255.255.255"; + route->gateway_.hostName_ = "netAddr"; + netLinkInfo->routeList_.push_back(*route); + + netLinkInfo->mtu_ = 0x5DC; + + return netLinkInfo; +} + +sptr NetConnManagerTest::GetINetConnCallbackSample() const +{ + sptr callback = (std::make_unique()).release(); + return callback; +} + +/** + * @tc.name: NetConnManager001 + * @tc.desc: Test NetConnManager SystemReady. + * @tc.type: FUNC + */ +HWTEST_F(NetConnManagerTest, NetConnManager001, TestSize.Level1) +{ + int32_t result = DelayedSingleton::GetInstance()->SystemReady(); + ASSERT_TRUE(result == 0); +} + +/** + * @tc.name: NetConnManager002 + * @tc.desc: Test NetConnManager RegisterNetSupplier. + * @tc.type: FUNC + */ +HWTEST_F(NetConnManagerTest, NetConnManager002, TestSize.Level1) +{ + uint64_t netCapabilities = 0x00; + netCapabilities |= NET_CAPABILITIES_INTERNET; + netCapabilities |= NET_CAPABILITIES_MMS; + + std::string ident = "ident01"; + int32_t result = DelayedSingleton::GetInstance()->RegisterNetSupplier(NET_TYPE_CELLULAR, ident, + netCapabilities); + ASSERT_TRUE(result >= ERR_NONE); +} + +/** + * @tc.name: NetConnManager003 + * @tc.desc: Test NetConnManager UnregisterNetSupplier. + * @tc.type: FUNC + */ +HWTEST_F(NetConnManagerTest, NetConnManager003, TestSize.Level1) +{ + uint64_t netCapabilities = 0x01; + netCapabilities |= NET_CAPABILITIES_INTERNET; + netCapabilities |= NET_CAPABILITIES_MMS; + + std::string ident = "ident02"; + int32_t resSupplierId = DelayedSingleton::GetInstance()->RegisterNetSupplier(NET_TYPE_CELLULAR, + ident, netCapabilities); + ASSERT_TRUE(resSupplierId >= ERR_NONE); + + int32_t result = DelayedSingleton::GetInstance()->UnregisterNetSupplier(resSupplierId); + ASSERT_TRUE(result == ERR_NONE); +} + +/** + * @tc.name: NetConnManager004 + * @tc.desc: Test NetConnManager UpdateNetSupplierInfo. + * @tc.type: FUNC + */ + +HWTEST_F(NetConnManagerTest, NetConnManager004, TestSize.Level1) +{ + uint64_t netCapabilities = 0x02; + netCapabilities |= NET_CAPABILITIES_INTERNET; + netCapabilities |= NET_CAPABILITIES_MMS; + + std::string ident = "ident03"; + int32_t resSupplierId = DelayedSingleton::GetInstance()->RegisterNetSupplier(NET_TYPE_CELLULAR, + ident, netCapabilities); + ASSERT_TRUE(resSupplierId >= ERR_NONE); + + sptr netSupplierInfo = new NetSupplierInfo; + netSupplierInfo->isAvailable_ = true; + netSupplierInfo->isRoaming_ = true; + netSupplierInfo->strength_ = 0x64; + netSupplierInfo->frequency_ = 0x10; + int32_t result = DelayedSingleton::GetInstance()->UpdateNetSupplierInfo(resSupplierId, + netSupplierInfo); + ASSERT_TRUE(result == ERR_NONE); +} + +/** + * @tc.name: NetConnManager005 + * @tc.desc: Test NetConnManager UpdateNetLinkInfo. + * @tc.type: FUNC + */ +HWTEST_F(NetConnManagerTest, NetConnManager005, TestSize.Level1) +{ + uint64_t netCapabilities = 0x03; + netCapabilities |= NET_CAPABILITIES_INTERNET; + netCapabilities |= NET_CAPABILITIES_MMS; + + std::string ident = "ident04"; + int32_t resSupplierId = DelayedSingleton::GetInstance()->RegisterNetSupplier(NET_TYPE_CELLULAR, + ident, netCapabilities); + ASSERT_TRUE(resSupplierId >= ERR_NONE); + + sptr netLinkInfo = GetUpdateLinkInfoSample(); + int32_t result = DelayedSingleton::GetInstance()->UpdateNetLinkInfo(resSupplierId, netLinkInfo); + ASSERT_TRUE(result == ERR_NONE); +} + +/** + * @tc.name: NetConnManager006 + * @tc.desc: Test NetConnManager RegisterNetConnCallback. + * @tc.type: FUNC + */ +HWTEST_F(NetConnManagerTest, NetConnManager006, TestSize.Level1) +{ + uint64_t netCapabilities = 0x02; + netCapabilities |= NET_CAPABILITIES_INTERNET; + + std::string ident = "ident"; + int32_t resSupplierId = DelayedSingleton::GetInstance()->RegisterNetSupplier(NET_TYPE_CELLULAR, + ident, netCapabilities); + ASSERT_TRUE(resSupplierId >= ERR_NONE); + + sptr callback = GetINetConnCallbackSample(); + int32_t result = DelayedSingleton::GetInstance()->RegisterNetConnCallback(callback); + if (result == ERR_NONE) { + callback->WaitFor(WAIT_TIME_SECOND_LONG); + int32_t netState = callback->GetNetState(); + std::cout << "NetConnManager006 RegisterNetConnCallback netState:" << netState << std::endl; + ASSERT_GT(netState, 0); // > + } else { + std::cout << "NetConnManager006 RegisterNetConnCallback return fail" << std::endl; + } + + result = DelayedSingleton::GetInstance()->UnregisterNetConnCallback(callback); + ASSERT_TRUE(result == ERR_NONE); +} + +/** + * @tc.name: NetConnManager007 + * @tc.desc: Test NetConnManager RegisterNetConnCallback. + * @tc.type: FUNC + */ +HWTEST_F(NetConnManagerTest, NetConnManager007, TestSize.Level1) +{ + uint64_t netCapabilities = 0x02; + netCapabilities |= NET_CAPABILITIES_INTERNET; + + std::string ident = "ident"; + int32_t resSupplierId = DelayedSingleton::GetInstance()->RegisterNetSupplier(NET_TYPE_CELLULAR, + ident, netCapabilities); + ASSERT_TRUE(resSupplierId >= ERR_NONE); + + sptr netSpecifier = (std::make_unique()).release(); + netSpecifier->ident_ = "ident"; + netSpecifier->netType_ = NET_TYPE_CELLULAR; + netSpecifier->netCapabilities_ = NET_CAPABILITIES_INTERNET; + + sptr callback = GetINetConnCallbackSample(); + int32_t result = DelayedSingleton::GetInstance()->RegisterNetConnCallback(netSpecifier, callback); + if (result == ERR_NONE) { + callback->WaitFor(WAIT_TIME_SECOND_LONG); + int32_t netState = callback->GetNetState(); + std::cout << "NetConnManager007 RegisterNetConnCallback netState:" << netState << std::endl; + ASSERT_GT(netState, 0); // > + } else { + std::cout << "NetConnManager007 RegisterNetConnCallback return fail" << std::endl; + } + + result = DelayedSingleton::GetInstance()->UnregisterNetConnCallback(netSpecifier, callback); + ASSERT_TRUE(result == ERR_NONE); +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netpolicymanager/BUILD.gn b/services/netpolicymanager/BUILD.gn new file mode 100755 index 0000000..5654d2a --- /dev/null +++ b/services/netpolicymanager/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +ohos_shared_library("net_policy_manager") { + sources = [ + "$NETCONNMANAGER_COMMON_DIR/src/netd_controller.cpp", + "$NETPOLICYMANAGER_SOURCE_DIR/src/ipc/net_policy_service_stub.cpp", + "$NETPOLICYMANAGER_SOURCE_DIR/src/net_policy_file.cpp", + "$NETPOLICYMANAGER_SOURCE_DIR/src/net_policy_service.cpp", + "$NETPOLICYMANAGER_SOURCE_DIR/src/net_policy_traffic.cpp", + ] + + include_dirs = [ + "$NETPOLICYMANAGER_SOURCE_DIR/include", + "$NETPOLICYMANAGER_SOURCE_DIR/include/ipc", + "$NETCONNMANAGER_SOURCE_DIR/include/net_controller", + "$INNERKITS_ROOT/native/netpolicymanager/include", + "$INNERKITS_ROOT/native/netconnmanager/include", + "$NETCONNMANAGER_COMMON_DIR/include", + "$NETCONNMANAGER_SOURCE_DIR/include", + ] + + deps = [ + "$NETCONNMANAGER_SOURCE_DIR:net_conn_manager", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + "$NETMANAGER_PREBUILTS_DIR/librarys/netd:libnet_manager_native", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] + + defines = [ + "NETMGR_LOG_TAG = \"NetPolicyManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + defines += [ "NATIVE_NETD_FEATURE" ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/services/netpolicymanager/include/ipc/i_net_policy_service.h b/services/netpolicymanager/include/ipc/i_net_policy_service.h new file mode 100755 index 0000000..43213b7 --- /dev/null +++ b/services/netpolicymanager/include/ipc/i_net_policy_service.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_NET_POLICY_SERVICE_H +#define I_NET_POLICY_SERVICE_H + +#include "iremote_broker.h" +#include "net_policy_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +class INetPolicyService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.NetManagerStandard.INetPolicyService"); + enum { + CMD_NSM_START = 0, + CMD_NSM_SET_UID_POLICY = 1, + CMD_NSM_GET_UID_POLICY = 2, + CMD_NSM_GET_UIDS = 3, + CMD_NSM_IS_NET_ACCESS_METERED = 4, + CMD_NSM_IS_NET_ACCESS_IFACENAME = 5, + CMD_NSM_END = 100, + }; + +public: + virtual NetPolicyResultCode SetUidPolicy(uint32_t uid, NetUidPolicy policy) = 0; + virtual NetUidPolicy GetUidPolicy(uint32_t uid) = 0; + virtual std::vector GetUids(NetUidPolicy policy) = 0; + virtual bool IsUidNetAccess(uint32_t uid, bool metered) = 0; + virtual bool IsUidNetAccess(uint32_t uid, const std::string &ifaceName) = 0; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // I_NET_POLICY_SERVICE_H diff --git a/services/netpolicymanager/include/ipc/net_policy_service_proxy.h b/services/netpolicymanager/include/ipc/net_policy_service_proxy.h new file mode 100755 index 0000000..55b5785 --- /dev/null +++ b/services/netpolicymanager/include/ipc/net_policy_service_proxy.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_SERVICE_PROXY_H +#define NET_POLICY_SERVICE_PROXY_H + +#include "iremote_proxy.h" + +#include "i_net_policy_service.h" +#include "net_policy_constants.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetPolicyServiceProxy : public IRemoteProxy { +public: + explicit NetPolicyServiceProxy(const sptr &impl); + virtual ~NetPolicyServiceProxy(); + NetPolicyResultCode SetUidPolicy(uint32_t uid, NetUidPolicy policy) override; + NetUidPolicy GetUidPolicy(uint32_t uid) override; + std::vector GetUids(NetUidPolicy policy) override; + bool IsUidNetAccess(uint32_t uid, bool metered) override; + bool IsUidNetAccess(uint32_t uid, const std::string &ifaceName) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_SERVICE_PROXY_H diff --git a/services/netpolicymanager/include/ipc/net_policy_service_stub.h b/services/netpolicymanager/include/ipc/net_policy_service_stub.h new file mode 100755 index 0000000..7e3f246 --- /dev/null +++ b/services/netpolicymanager/include/ipc/net_policy_service_stub.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_SERVICE_STUB_H +#define NET_POLICY_SERVICE_STUB_H + +#include + +#include "iremote_stub.h" + +#include "i_net_policy_service.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetPolicyServiceStub : public IRemoteStub { +public: + NetPolicyServiceStub(); + ~NetPolicyServiceStub(); + + int32_t OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + using NetPolicyServiceFunc = int32_t (NetPolicyServiceStub::*)(MessageParcel &, MessageParcel &); + +private: + int32_t OnSetUidPolicy(MessageParcel &data, MessageParcel &reply); + int32_t OnGetUidPolicy(MessageParcel &data, MessageParcel &reply); + int32_t OnGetUids(MessageParcel &data, MessageParcel &reply); + int32_t OnIsUidNetAccessMetered(MessageParcel &data, MessageParcel &reply); + int32_t OnIsUidNetAccessIfaceName(MessageParcel &data, MessageParcel &reply); + +private: + std::map memberFuncMap_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_SERVICE_STUB_H diff --git a/services/netpolicymanager/include/net_policy_define.h b/services/netpolicymanager/include/net_policy_define.h new file mode 100755 index 0000000..1882f29 --- /dev/null +++ b/services/netpolicymanager/include/net_policy_define.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_DEFINE_H +#define NET_POLICY_DEFINE_H + +namespace OHOS { +namespace NetManagerStandard { +const mode_t CHOWN_RWX_USR_GRP = 0770; +const char POLICY_FILE_NAME[] = "/data/system/net_policy.json"; +const char CONFIG_HOS_VERSION[] = "hosVersion"; +const char CONFIG_UID_POLICY[] = "uidPolicy"; +const char CONFIG_UID[] = "uid"; +const char CONFIG_POLICY[] = "policy"; +const char HOS_VERSION[] = "1.0"; +const int32_t CONVERT_LENGTH_TEN = 10; + +/* network allow policy mask */ +const uint32_t NET_POLICY_ALLOW_MASK = 0b00100011; + +struct UidPolicy { + std::string uid; + std::string policy; +}; + +struct NetPolicy { + std::vector uidPolicys; + std::string hosVersion; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_DEFINE_H \ No newline at end of file diff --git a/services/netpolicymanager/include/net_policy_file.h b/services/netpolicymanager/include/net_policy_file.h new file mode 100755 index 0000000..03e222a --- /dev/null +++ b/services/netpolicymanager/include/net_policy_file.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_FILE_H +#define NET_POLICY_FILE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "refbase.h" + +#include "net_policy_constants.h" +#include "net_policy_define.h" + +namespace OHOS { +namespace NetManagerStandard { +enum class NetUidPolicyOpType { + NET_POLICY_UID_OP_TYPE_ADD = 1, + NET_POLICY_UID_OP_TYPE_DELETE = 2, + NET_POLICY_UID_OP_TYPE_UPDATE = 3, +}; + +class NetPolicyFile : public virtual RefBase { +public: + bool InitPolicy(); + bool IsUidPolicyExist(uint32_t uid); + bool ReadFile(const std::string& fileName, std::string& content); + bool Json2Obj(const std::string& content, NetPolicy& netPolicy); + bool WriteFile(const std::string& fileName); + bool WriteFile(const NetUidPolicyOpType netUidPolicyOpType, uint32_t uid, NetUidPolicy policy); + NetUidPolicy GetUidPolicy(uint32_t uid); + bool GetUids(NetUidPolicy policy, std::vector &uids); + +private: + bool FileExists(const std::string& fileName); + bool CreateFile(const std::string& fileName); + +private: + NetPolicy netPolicy_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_FILE_H + diff --git a/services/netpolicymanager/include/net_policy_service.h b/services/netpolicymanager/include/net_policy_service.h new file mode 100755 index 0000000..45a6505 --- /dev/null +++ b/services/netpolicymanager/include/net_policy_service.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_SERVICE_H +#define NET_POLICY_SERVICE_H + +#include +#include "singleton.h" +#include "system_ability.h" + +#include "net_policy_traffic.h" + +#include "ipc/net_policy_service_stub.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetPolicyService : public SystemAbility, + public NetPolicyServiceStub, + public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(NetPolicyService) + DECLARE_SYSTEM_ABILITY(NetPolicyService) + +public: + void OnStart() override; + void OnStop() override; + /** + * @brief The interface is set uid policy + * + * @param uid uid + * @param policy policy + * + * @return Returns 0 success, otherwise fail + */ + NetPolicyResultCode SetUidPolicy(uint32_t uid, NetUidPolicy policy) override; + NetUidPolicy GetUidPolicy(uint32_t uid) override; + std::vector GetUids(NetUidPolicy policy) override; + bool IsUidNetAccess(uint32_t uid, bool metered) override; + bool IsUidNetAccess(uint32_t uid, const std::string &ifaceName) override; + +private: + bool Init(); + +private: + enum ServiceRunningState { + STATE_STOPPED = 0, + STATE_RUNNING, + }; + + sptr netPolicyTraffic_; + sptr netPolicyFile_; + bool registerToService_; + ServiceRunningState state_; + std::mutex mutex_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_SERVICE_H diff --git a/services/netpolicymanager/include/net_policy_traffic.h b/services/netpolicymanager/include/net_policy_traffic.h new file mode 100755 index 0000000..5cf28c1 --- /dev/null +++ b/services/netpolicymanager/include/net_policy_traffic.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_POLICY_TRAFFIC_H +#define NET_POLICY_TRAFFIC_H + +#include "singleton.h" +#include "system_ability.h" + +#include "ipc/net_policy_service_stub.h" +#include "net_policy_file.h" + +namespace OHOS { +namespace NetManagerStandard { +class NetPolicyTraffic : public virtual RefBase { +public: + NetPolicyTraffic(sptr netPolicyFile); + bool IsUidPolicyExist(uint32_t uid); + NetPolicyResultCode AddUidPolicy(uint32_t uid, NetUidPolicy policy); + NetPolicyResultCode SetUidPolicy(uint32_t uid, NetUidPolicy policy); + NetPolicyResultCode DeleteUidPolicy(uint32_t uid, NetUidPolicy policy); + bool IsPolicyValid(NetUidPolicy &policy); + +private: + sptr netPolicyFile_; +}; +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_POLICY_TRAFFIC_H diff --git a/services/netpolicymanager/src/ipc/net_policy_service_proxy.cpp b/services/netpolicymanager/src/ipc/net_policy_service_proxy.cpp new file mode 100755 index 0000000..de12d42 --- /dev/null +++ b/services/netpolicymanager/src/ipc/net_policy_service_proxy.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_policy_service_proxy.h" + +#include "net_policy_constants.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetPolicyServiceProxy::NetPolicyServiceProxy(const sptr &impl) + : IRemoteProxy(impl) +{} + +NetPolicyServiceProxy::~NetPolicyServiceProxy() {} + +NetPolicyResultCode NetPolicyServiceProxy::SetUidPolicy(uint32_t uid, NetUidPolicy policy) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + if (!data.WriteUint32(uid)) { + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + if (!data.WriteUint32(static_cast(policy))) { + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + int32_t error = remote->SendRequest(CMD_NSM_SET_UID_POLICY, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + return static_cast(reply.ReadInt32()); +} + +NetUidPolicy NetPolicyServiceProxy::GetUidPolicy(uint32_t uid) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return NetUidPolicy::NET_POLICY_NONE; + } + + if (!data.WriteUint32(uid)) { + return NetUidPolicy::NET_POLICY_NONE; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return NetUidPolicy::NET_POLICY_NONE; + } + + int32_t error = remote->SendRequest(CMD_NSM_GET_UID_POLICY, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return NetUidPolicy::NET_POLICY_NONE; + } + + return static_cast(reply.ReadInt32()); +} + +std::vector NetPolicyServiceProxy::GetUids(NetUidPolicy policy) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + std::vector uids; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return uids; + } + + if (!data.WriteUint32(static_cast(policy))) { + return uids; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return uids; + } + + int32_t error = remote->SendRequest(CMD_NSM_GET_UIDS, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return uids; + } + + bool errorRet = reply.ReadUInt32Vector(&uids); + if (errorRet == false) { + NETMGR_LOGE("proxy SendRequest Readuint32Vector failed"); + } + + return uids; +} + +bool NetPolicyServiceProxy::IsUidNetAccess(uint32_t uid, bool metered) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + std::vector uids; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return false; + } + + if (!data.WriteUint32(uid)) { + return false; + } + + if (!data.WriteBool(metered)) { + return false; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return false; + } + + int32_t error = remote->SendRequest(CMD_NSM_IS_NET_ACCESS_METERED, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return false; + } + + return reply.ReadBool(); +} + +bool NetPolicyServiceProxy::IsUidNetAccess(uint32_t uid, const std::string &ifaceName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + std::vector uids; + if (!WriteInterfaceToken(data)) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return false; + } + + if (!data.WriteUint32(uid)) { + return false; + } + + if (!data.WriteString(ifaceName)) { + return false; + } + + sptr remote = Remote(); + if (remote == nullptr) { + NETMGR_LOGE("Remote is null"); + return false; + } + + int32_t error = remote->SendRequest(CMD_NSM_IS_NET_ACCESS_IFACENAME, data, reply, option); + if (error != ERR_NONE) { + NETMGR_LOGE("proxy SendRequest failed, error code: [%{public}d]", error); + return false; + } + + return reply.ReadBool(); +} + +bool NetPolicyServiceProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(NetPolicyServiceProxy::GetDescriptor())) { + NETMGR_LOGE("WriteInterfaceToken failed"); + return false; + } + return true; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netpolicymanager/src/ipc/net_policy_service_stub.cpp b/services/netpolicymanager/src/ipc/net_policy_service_stub.cpp new file mode 100755 index 0000000..21d330c --- /dev/null +++ b/services/netpolicymanager/src/ipc/net_policy_service_stub.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_policy_service_stub.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +NetPolicyServiceStub::NetPolicyServiceStub() +{ + memberFuncMap_[CMD_NSM_SET_UID_POLICY] = &NetPolicyServiceStub::OnSetUidPolicy; + memberFuncMap_[CMD_NSM_GET_UID_POLICY] = &NetPolicyServiceStub::OnGetUidPolicy; + memberFuncMap_[CMD_NSM_GET_UIDS] = &NetPolicyServiceStub::OnGetUids; + memberFuncMap_[CMD_NSM_IS_NET_ACCESS_METERED] = &NetPolicyServiceStub::OnIsUidNetAccessMetered; + memberFuncMap_[CMD_NSM_IS_NET_ACCESS_IFACENAME] = &NetPolicyServiceStub::OnIsUidNetAccessIfaceName; +} + +NetPolicyServiceStub::~NetPolicyServiceStub() {} + +int32_t NetPolicyServiceStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::u16string myDescripter = NetPolicyServiceStub::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (myDescripter != remoteDescripter) { + NETMGR_LOGE("descriptor checked fail"); + return ERR_FLATTEN_OBJECT; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t NetPolicyServiceStub::OnSetUidPolicy(MessageParcel &data, MessageParcel &reply) +{ + uint32_t uid; + if (!data.ReadUint32(uid)) { + return ERR_FLATTEN_OBJECT; + } + + uint32_t netPolicy; + if (!data.ReadUint32(netPolicy)) { + return ERR_FLATTEN_OBJECT; + } + + if (!reply.WriteInt32(static_cast(SetUidPolicy(uid, static_cast(netPolicy))))) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetPolicyServiceStub::OnGetUidPolicy(MessageParcel &data, MessageParcel &reply) +{ + uint32_t uid; + if (!data.ReadUint32(uid)) { + return ERR_FLATTEN_OBJECT; + } + + if (!reply.WriteInt32(static_cast(GetUidPolicy(uid)))) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetPolicyServiceStub::OnGetUids(MessageParcel &data, MessageParcel &reply) +{ + uint32_t policy; + if (!data.ReadUint32(policy)) { + return ERR_FLATTEN_OBJECT; + } + + if (!reply.WriteUInt32Vector(GetUids(static_cast(policy)))) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetPolicyServiceStub::OnIsUidNetAccessMetered(MessageParcel &data, MessageParcel &reply) +{ + uint32_t uid = 0; + bool metered = false; + if (!data.ReadUint32(uid)) { + return ERR_FLATTEN_OBJECT; + } + + if (!data.ReadBool(metered)) { + return ERR_FLATTEN_OBJECT; + } + + bool ret = IsUidNetAccess(uid, metered); + if (!reply.WriteBool(ret)) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} + +int32_t NetPolicyServiceStub::OnIsUidNetAccessIfaceName(MessageParcel &data, MessageParcel &reply) +{ + uint32_t uid = 0; + std::string ifaceName; + if (!data.ReadUint32(uid)) { + return ERR_FLATTEN_OBJECT; + } + + if (!data.ReadString(ifaceName)) { + return ERR_FLATTEN_OBJECT; + } + + bool ret = IsUidNetAccess(uid, ifaceName); + if (!reply.WriteBool(ret)) { + return ERR_FLATTEN_OBJECT; + } + + return ERR_NONE; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netpolicymanager/src/net_policy_file.cpp b/services/netpolicymanager/src/net_policy_file.cpp new file mode 100755 index 0000000..6036f34 --- /dev/null +++ b/services/netpolicymanager/src/net_policy_file.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_policy_file.h" + +#include +#include + +#include "net_policy_define.h" +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +bool NetPolicyFile::FileExists(const std::string &fileName) +{ + struct stat buffer; + return (stat(fileName.c_str(), &buffer) == static_cast(NetPolicyResultCode::ERR_NONE)); +} + +bool NetPolicyFile::CreateFile(const std::string& fileName) +{ + if (fileName.empty() || FileExists(fileName)) { + NETMGR_LOGE("fileName empty or file not exists."); + return false; + } + + int32_t fd = open(fileName.c_str(), O_CREAT | O_WRONLY, CHOWN_RWX_USR_GRP); + if (fd < 0) { + NETMGR_LOGE("open file error."); + return false; + } + close(fd); + + return true; +} + +bool NetPolicyFile::Json2Obj(const std::string &content, NetPolicy &netPolicy) +{ + if (content.empty()) { + return false; + } + + Json::Value root; + Json::CharReaderBuilder buidler; + std::unique_ptr reader(buidler.newCharReader()); + JSONCPP_STRING errs; + + bool isSuccess = reader->parse(content.c_str(), content.c_str() + content.length(), &root, &errs); + if (isSuccess && errs.size() == 0) { + netPolicy.hosVersion = root[CONFIG_HOS_VERSION].asString(); + if (netPolicy.hosVersion.empty()) { + netPolicy.hosVersion = HOS_VERSION; + } + const Json::Value arrayUidPolicy = root[CONFIG_UID_POLICY]; + uint32_t size = arrayUidPolicy.size(); + UidPolicy uidPolicy; + for (uint32_t i = 0; i < size; i++) { + uidPolicy.uid= arrayUidPolicy[i][CONFIG_UID].asString(); + uidPolicy.policy = arrayUidPolicy[i][CONFIG_POLICY].asString(); + netPolicy.uidPolicys.push_back(uidPolicy); + } + } + + return true; +} + +bool NetPolicyFile::ReadFile(const std::string &fileName, std::string &fileContent) +{ + if (fileName.empty()) { + NETMGR_LOGE("fileName empty."); + return false; + } + + if (!FileExists(fileName)) { + NETMGR_LOGE("[%{public}s] not exist.", fileName.c_str()); + return false; + } + + std::fstream file(fileName.c_str(), std::fstream::in); + if (file.is_open() == false) { + NETMGR_LOGE("fstream failed."); + return false; + } + + std::stringstream buffer; + buffer << file.rdbuf(); + fileContent = buffer.str(); + file.close(); + + return true; +} + +bool NetPolicyFile::WriteFile(const std::string &fileName) +{ + if (fileName.empty()) { + NETMGR_LOGE("fileName is empty."); + return false; + } + + Json::Value root; + Json::StreamWriterBuilder builder; + std::unique_ptr streamWriter(builder.newStreamWriter()); + std::fstream file(fileName.c_str(), std::fstream::out); + if (file.is_open() == false) { + NETMGR_LOGE("fstream failed."); + return false; + } + + root[CONFIG_HOS_VERSION] = Json::Value(netPolicy_.hosVersion); + uint32_t size = netPolicy_.uidPolicys.size(); + for (uint32_t i = 0; i < size; i++) { + Json::Value uidPolicy; + uidPolicy[CONFIG_UID] = netPolicy_.uidPolicys[i].uid; + uidPolicy[CONFIG_POLICY] = netPolicy_.uidPolicys[i].policy; + std::string policy = std::to_string(static_cast(NetUidPolicy::NET_POLICY_TEMPORARY_ALLOW_METERED)); + /* Temporary permission, no need to write files */ + if (netPolicy_.uidPolicys[i].policy == policy) { + continue; + } + root[CONFIG_UID_POLICY].append(uidPolicy); + } + std::ostringstream out; + streamWriter->write(root, &out); + file << out.str().c_str(); + file.close(); + + return true; +} + +bool NetPolicyFile::WriteFile(const NetUidPolicyOpType netUidPolicyOpType, uint32_t uid, NetUidPolicy policy) +{ + if (netUidPolicyOpType == NetUidPolicyOpType::NET_POLICY_UID_OP_TYPE_UPDATE) { + for (auto &uidPolicy : netPolicy_.uidPolicys) { + if (uidPolicy.uid == std::to_string(uid)) { + uidPolicy.policy = std::to_string(static_cast(policy)); + break; + } + } + } else if (netUidPolicyOpType == NetUidPolicyOpType::NET_POLICY_UID_OP_TYPE_DELETE) { + for (auto iter = netPolicy_.uidPolicys.begin(); iter != netPolicy_.uidPolicys.end(); ++iter) { + if (iter->uid == std::to_string(uid)) { + netPolicy_.uidPolicys.erase(iter); + break; + } + } + } else { + UidPolicy uidPolicy; + uidPolicy.uid = std::to_string(uid); + uidPolicy.policy = std::to_string(static_cast(policy)); + netPolicy_.uidPolicys.push_back(uidPolicy); + } + + if (!WriteFile(POLICY_FILE_NAME)) { + NETMGR_LOGE("WriteFile failed"); + return false; + } + + return true; +} + +bool NetPolicyFile::IsUidPolicyExist(uint32_t uid) +{ + uint32_t size = netPolicy_.uidPolicys.size(); + for (uint32_t i = 0; i < size; i++) { + if (static_cast(std::stol(netPolicy_.uidPolicys[i].uid)) == uid) { + return true; + } + } + + return false; +} + +NetUidPolicy NetPolicyFile::GetUidPolicy(uint32_t uid) +{ + for (auto &uidPolicy : netPolicy_.uidPolicys) { + if (uidPolicy.uid == std::to_string(uid)) { + return static_cast(std::stol(uidPolicy.policy)); + } + } + + return NetUidPolicy::NET_POLICY_NONE; +} + +bool NetPolicyFile::GetUids(NetUidPolicy policy, std::vector &uids) +{ + for (auto &uidPolicy : netPolicy_.uidPolicys) { + if (uidPolicy.policy == std::to_string(static_cast(policy))) { + uint32_t uid = static_cast(std::stol(uidPolicy.uid)); + uids.push_back(uid); + } + } + + return true; +} + +bool NetPolicyFile::InitPolicy() +{ + std::string content; + if (!ReadFile(POLICY_FILE_NAME, content)) { + if (!CreateFile(POLICY_FILE_NAME)) { + NETMGR_LOGE("CreateFile [%{public}s] failed", POLICY_FILE_NAME); + return false; + } + } + if (!content.empty() && !Json2Obj(content, netPolicy_)) { + NETMGR_LOGE("Analysis fileconfig failed"); + return false; + } + return true; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/netpolicymanager/src/net_policy_service.cpp b/services/netpolicymanager/src/net_policy_service.cpp new file mode 100755 index 0000000..cb5e641 --- /dev/null +++ b/services/netpolicymanager/src/net_policy_service.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_policy_service.h" + +#include "system_ability_definition.h" + +#include "net_policy_constants.h" +#include "net_policy_define.h" +#include "net_policy_file.h" +#include "net_policy_traffic.h" + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +const bool REGISTER_LOCAL_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +NetPolicyService::NetPolicyService() + : SystemAbility(COMM_NET_POLICY_MANAGER_SYS_ABILITY_ID, true), registerToService_(false), state_(STATE_STOPPED) +{ + netPolicyFile_ = (std::make_unique()).release(); + netPolicyTraffic_ = (std::make_unique(netPolicyFile_)).release(); +} + +NetPolicyService::~NetPolicyService() {} + +void NetPolicyService::OnStart() +{ + if (state_ == STATE_RUNNING) { + return; + } + if (!Init()) { + NETMGR_LOGE("init failed"); + return; + } + state_ = STATE_RUNNING; +} + +void NetPolicyService::OnStop() +{ + state_ = STATE_STOPPED; + registerToService_ = false; +} + +bool NetPolicyService::Init() +{ + if (!REGISTER_LOCAL_RESULT) { + NETMGR_LOGE("Register to local sa manager failed"); + registerToService_ = false; + return false; + } + if (!registerToService_) { + if (!Publish(DelayedSingleton::GetInstance().get())) { + NETMGR_LOGE("Register to sa manager failed"); + return false; + } + registerToService_ = true; + } + + bool error = netPolicyFile_->InitPolicy(); + if (!error) { + NETMGR_LOGE("InitPolicyTraffic failed"); + return false; + } + + return true; +} + +NetPolicyResultCode NetPolicyService::SetUidPolicy(uint32_t uid, NetUidPolicy policy) +{ + std::unique_lock lock(mutex_); + NETMGR_LOGI("SetUidPolicy info: uid[%{public}d] policy[%{public}d]", uid, static_cast(policy)); + /* delete uid policy */ + if (policy == NetUidPolicy::NET_POLICY_NONE) { + return netPolicyTraffic_->DeleteUidPolicy(uid, policy); + } + + /* update policy */ + if (!netPolicyFile_->IsUidPolicyExist(uid)) { + return netPolicyTraffic_->AddUidPolicy(uid, policy); + } else { + return netPolicyTraffic_->SetUidPolicy(uid, policy); + } +} + +NetUidPolicy NetPolicyService::GetUidPolicy(uint32_t uid) +{ + NETMGR_LOGI("GetUidPolicy info: uid[%{public}d]", uid); + return netPolicyFile_->GetUidPolicy(uid); +} + +std::vector NetPolicyService::GetUids(NetUidPolicy policy) +{ + NETMGR_LOGI("GetUids info: policy[%{public}d]", static_cast(policy)); + std::vector uids; + if (!netPolicyFile_->GetUids(policy, uids)) { + NETMGR_LOGE("GetUids failed"); + }; + return uids; +} + +bool NetPolicyService::IsUidNetAccess(uint32_t uid, bool metered) +{ + NETMGR_LOGI("IsUidNetAccess info: uid[%{public}d]", uid); + NetUidPolicy uidPolicy = netPolicyFile_->GetUidPolicy(uid); + if (uidPolicy == NetUidPolicy::NET_POLICY_NONE) { + return true; + } + + NETMGR_LOGI("IsUidNetAccess info: policy[%{public}d]", static_cast(uidPolicy)); + if (static_cast(uidPolicy) & NET_POLICY_ALLOW_MASK) { + return true; + } + + return false; +} + +bool NetPolicyService::IsUidNetAccess(uint32_t uid, const std::string &ifaceName) +{ + NETMGR_LOGI("IsUidNetAccess info: uid[%{public}d] ifaceName[%{public}s]", uid, ifaceName.c_str()); + NetUidPolicy uidPolicy = netPolicyFile_->GetUidPolicy(uid); + if (uidPolicy == NetUidPolicy::NET_POLICY_NONE) { + return true; + } + + if (static_cast(uidPolicy) & NET_POLICY_ALLOW_MASK) { + return true; + } + + return false; +} +} // namespace NetManagerStandard +} // namespace OHOS diff --git a/services/netpolicymanager/src/net_policy_traffic.cpp b/services/netpolicymanager/src/net_policy_traffic.cpp new file mode 100755 index 0000000..86e24a6 --- /dev/null +++ b/services/netpolicymanager/src/net_policy_traffic.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "net_policy_traffic.h" + +#include +#include + +#include "net_mgr_log_wrapper.h" +#include "net_policy_constants.h" +#include "net_policy_define.h" +#include "net_policy_file.h" + +namespace OHOS { +namespace NetManagerStandard { +NetPolicyTraffic::NetPolicyTraffic(sptr netPolicyFile) : netPolicyFile_(netPolicyFile) +{ +} + +bool NetPolicyTraffic::IsPolicyValid(NetUidPolicy &policy) +{ + switch (policy) { + case NetUidPolicy::NET_POLICY_NONE: + case NetUidPolicy::NET_POLICY_ALLOW_METERED_BACKGROUND: + case NetUidPolicy::NET_POLICY_TEMPORARY_ALLOW_METERED: + case NetUidPolicy::NET_POLICY_REJECT_METERED_BACKGROUND: + case NetUidPolicy::NET_POLICY_ALLOW_ALL: + case NetUidPolicy::NET_POLICY_REJECT_ALL: { + return true; + } + default: { + NETMGR_LOGE("Invalid policy [%{public}d]", static_cast(policy)); + return false; + } + } +} + +NetPolicyResultCode NetPolicyTraffic::AddUidPolicy(uint32_t uid, NetUidPolicy policy) +{ + NETMGR_LOGI("AddUidPolicy info:uid[%{public}d] policy[%{public}d]", uid, static_cast(policy)); + if (netPolicyFile_ == nullptr) { + NETMGR_LOGE("AddUidPolicy netPolicyFile is null"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + if (!IsPolicyValid(policy)) { + return NetPolicyResultCode::ERR_INVALID_POLICY; + } + + if (!netPolicyFile_->WriteFile(NetUidPolicyOpType::NET_POLICY_UID_OP_TYPE_ADD, uid, policy)) { + NETMGR_LOGE("AddUidPolicy WriteFile failed"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + return NetPolicyResultCode::ERR_NONE; +} + +NetPolicyResultCode NetPolicyTraffic::SetUidPolicy(uint32_t uid, NetUidPolicy policy) +{ + NETMGR_LOGI("SetUidPolicy info:uid[%{public}d] policy[%{public}d]", uid, static_cast(policy)); + if (netPolicyFile_ == nullptr) { + NETMGR_LOGE("SetUidPolicy netPolicyFile is null"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + if (!IsPolicyValid(policy)) { + return NetPolicyResultCode::ERR_INVALID_POLICY; + } + + if (!netPolicyFile_->WriteFile(NetUidPolicyOpType::NET_POLICY_UID_OP_TYPE_UPDATE, uid, policy)) { + NETMGR_LOGE("SetUidPolicy WriteFile failed"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + return NetPolicyResultCode::ERR_NONE; +} + +NetPolicyResultCode NetPolicyTraffic::DeleteUidPolicy(uint32_t uid, NetUidPolicy policy) +{ + NETMGR_LOGI("DeleteUidPolicy info:uid[%{public}d] policy[%{public}d]", uid, static_cast(policy)); + if (netPolicyFile_ == nullptr) { + NETMGR_LOGE("DeleteUidPolicy netPolicyFile is null"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + if (!IsPolicyValid(policy)) { + return NetPolicyResultCode::ERR_INVALID_POLICY; + } + + if (!netPolicyFile_->WriteFile(NetUidPolicyOpType::NET_POLICY_UID_OP_TYPE_DELETE, uid, policy)) { + NETMGR_LOGE("DeleteUidPolicy WriteFile failed"); + return NetPolicyResultCode::ERR_INTERNAL_ERROR; + } + + return NetPolicyResultCode::ERR_NONE; +} +} // namespace NetManagerStandard +} // namespace OHOS \ No newline at end of file diff --git a/services/netpolicymanager/test/BUILD.gn b/services/netpolicymanager/test/BUILD.gn new file mode 100755 index 0000000..dd18445 --- /dev/null +++ b/services/netpolicymanager/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +group("unittest") { + testonly = true + deps = [] + deps += [ "unittest/net_policy_manager_test:unittest" ] +} diff --git a/services/netpolicymanager/test/unittest/net_policy_manager_test/BUILD.gn b/services/netpolicymanager/test/unittest/net_policy_manager_test/BUILD.gn new file mode 100755 index 0000000..a287112 --- /dev/null +++ b/services/netpolicymanager/test/unittest/net_policy_manager_test/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import( + "//foundation/communication/netmanager_standard/netmanager_base_config.gni") + +ohos_unittest("net_policy_manager_test") { + module_out_path = "netmanager_base/net_policy_manager_test" + + sources = [ + "//foundation/communication/netmanager_standard/services/netpolicymanager/src/ipc/net_policy_service_proxy.cpp", + "net_policy_manager_test.cpp", + ] + + include_dirs = [ + "$INNERKITS_ROOT/native/netpolicymanager/include", + "$NETPOLICYMANAGER_SOURCE_DIR/include/ipc", + "$NETPOLICYMANAGER_SOURCE_DIR/include", + ] + + deps = [ + "$INNERKITS_ROOT/native/netpolicymanager:net_policy_manager_if", + "$NETMANAGER_BASE_ROOT/utils:net_manager_common", + ] + + external_deps = [ + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] + + defines = [ + "NETMGR_LOG_TAG = \"NetPolicyManager\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (enable_netmgr_debug) { + defines += [ "NETMGR_DEBUG" ] + } + + if (is_standard_system) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps += [ "hilog:libhilog" ] + } + + part_name = "netmanager_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":net_policy_manager_test" ] +} diff --git a/services/netpolicymanager/test/unittest/net_policy_manager_test/net_policy_manager_test.cpp b/services/netpolicymanager/test/unittest/net_policy_manager_test/net_policy_manager_test.cpp new file mode 100755 index 0000000..5f61727 --- /dev/null +++ b/services/netpolicymanager/test/unittest/net_policy_manager_test/net_policy_manager_test.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "net_mgr_log_wrapper.h" +#include "net_policy_define.h" +#include "net_policy_file.h" +#include "net_policy_traffic.h" +#include "net_policy_constants.h" +#include "net_policy_client.h" +#include "net_policy_service.h" + +namespace OHOS { +namespace NetManagerStandard { +using namespace testing::ext; +class NetPolicyManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void NetPolicyManagerTest::SetUpTestCase() {} + +void NetPolicyManagerTest::TearDownTestCase() {} + +void NetPolicyManagerTest::SetUp() {} + +void NetPolicyManagerTest::TearDown() {} + +/** + * @tc.name: NetPolicyManager001 + * @tc.desc: Test NetPolicyManager SetUidPolicy. + * @tc.type: FUNC + */ +HWTEST_F(NetPolicyManagerTest, NetPolicyManager001, TestSize.Level1) +{ + NetPolicyResultCode result = DelayedSingleton::GetInstance()->SetUidPolicy(1, + NetUidPolicy::NET_POLICY_ALLOW_METERED_BACKGROUND); + ASSERT_TRUE(result != NetPolicyResultCode::ERR_INVALID_UID); +} + +/** + * @tc.name: NetPolicyManager002 + * @tc.desc: Test NetPolicyManager GetUidPolicy. + * @tc.type: FUNC + */ +HWTEST_F(NetPolicyManagerTest, NetPolicyManager002, TestSize.Level1) +{ + NetUidPolicy result = DelayedSingleton::GetInstance()->GetUidPolicy(1); + ASSERT_TRUE(result == NetUidPolicy::NET_POLICY_ALLOW_METERED_BACKGROUND); +} + +/** + * @tc.name: NetPolicyManager003 + * @tc.desc: Test NetPolicyManager GetUids. + * @tc.type: FUNC + */ +HWTEST_F(NetPolicyManagerTest, NetPolicyManager003, TestSize.Level1) +{ + std::vector result; + NetUidPolicy policy = NetUidPolicy::NET_POLICY_ALLOW_METERED_BACKGROUND; + result = DelayedSingleton::GetInstance()->GetUids(policy); + ASSERT_TRUE(result.size() != 0); +} + +/** + * @tc.name: NetPolicyManager004 + * @tc.desc: Test NetPolicyManager IsUidNetAccess. + * @tc.type: FUNC + */ +HWTEST_F(NetPolicyManagerTest, NetPolicyManager004, TestSize.Level1) +{ + bool result = DelayedSingleton::GetInstance()->IsUidNetAccess(1, false); + ASSERT_TRUE(result == true); +} + +/** + * @tc.name: NetPolicyManager005 + * @tc.desc: Test NetPolicyManager IsUidNetAccess. + * @tc.type: FUNC + */ +HWTEST_F(NetPolicyManagerTest, NetPolicyManager005, TestSize.Level1) +{ + bool result = DelayedSingleton::GetInstance()->IsUidNetAccess(1, std::string("test")); + ASSERT_TRUE(result == true); +} +} +} diff --git a/utils/BUILD.gn b/utils/BUILD.gn new file mode 100755 index 0000000..4ccccfc --- /dev/null +++ b/utils/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("common_target") { + deps = [ ":net_manager_common" ] +} + +config("netmgr_common_config") { + include_dirs = [ "log/include" ] +} + +ohos_shared_library("net_manager_common") { + sources = [ "log/src/net_mgr_log_wrapper.cpp" ] + + defines = [ + "NETMGR_LOG_TAG = \"NetMgrCommon\"", + "LOG_DOMAIN = 0xD0015B0", + ] + + if (is_standard_system) { + defines += [ "STANDARD_SYSTEM_ENABLE" ] + } + + public_configs = [ + ":netmgr_common_config", + "//utils/native/base:utils_config", + ] + + public_deps = [ "//utils/native/base:utils" ] + + if (is_double_framework) { + cflags_cc = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } + + external_deps += [ + "appexecfwk_standard:libeventhandler", + "native_appdatamgr:native_preferences", + ] + + part_name = "netmanager_standard" + subsystem_name = "communication" +} diff --git a/utils/log/include/net_mgr_log_wrapper.h b/utils/log/include/net_mgr_log_wrapper.h new file mode 100755 index 0000000..194a178 --- /dev/null +++ b/utils/log/include/net_mgr_log_wrapper.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NET_MGR_LOG_WRAPPER_H +#define NET_MGR_LOG_WRAPPER_H + +#include +#include "hilog/log.h" + +namespace OHOS { +namespace NetManagerStandard { +enum class NetMgrLogLevel { + DEBUG = 0, + INFO, + WARN, + ERROR, + FATAL, +}; + +class NetMgrLogWrapper { +public: + static bool JudgeLevel(const NetMgrLogLevel &level); + + static void SetLogLevel(const NetMgrLogLevel &level) + { + level_ = level; + } + + static const NetMgrLogLevel &GetLogLevel() + { + return level_; + } + + static std::string GetBriefFileName(const std::string &file); + +private: + static NetMgrLogLevel level_; +}; + +#ifndef NETMGR_LOG_TAG +#define NETMGR_LOG_TAG "NetMgrSubsystem" +#endif + +static constexpr OHOS::HiviewDFX::HiLogLabel NET_MGR_LABEL = {LOG_CORE, LOG_DOMAIN, NETMGR_LOG_TAG}; + +#ifdef NETMGR_DEBUG +#define PRINT_LOG(op, fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::op(NET_MGR_LABEL, "[%{public}s-(%{public}s:%{public}d)]" fmt, __FUNCTION__, \ + __FILE_NAME__, __LINE__, ##__VA_ARGS__) +#else +#define PRINT_LOG(op, fmt, ...) +#endif + +#define NETMGR_LOGD(fmt, ...) PRINT_LOG(Debug, fmt, ##__VA_ARGS__) +#define NETMGR_LOGE(fmt, ...) PRINT_LOG(Error, fmt, ##__VA_ARGS__) +#define NETMGR_LOGW(fmt, ...) PRINT_LOG(Warn, fmt, ##__VA_ARGS__) +#define NETMGR_LOGI(fmt, ...) PRINT_LOG(Info, fmt, ##__VA_ARGS__) +#define NETMGR_LOGF(fmt, ...) PRINT_LOG(Fatal, fmt, ##__VA_ARGS__) +} // namespace NetManagerStandard +} // namespace OHOS +#endif // NET_MGR_LOG_WRAPPER_H \ No newline at end of file diff --git a/utils/log/src/net_mgr_log_wrapper.cpp b/utils/log/src/net_mgr_log_wrapper.cpp new file mode 100755 index 0000000..ffba66e --- /dev/null +++ b/utils/log/src/net_mgr_log_wrapper.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "net_mgr_log_wrapper.h" + +namespace OHOS { +namespace NetManagerStandard { +// initial static member object +NetMgrLogLevel NetMgrLogWrapper::level_ = NetMgrLogLevel::DEBUG; + +bool NetMgrLogWrapper::JudgeLevel(const NetMgrLogLevel &level) +{ + const NetMgrLogLevel &curLevel = NetMgrLogWrapper::GetLogLevel(); + if (level < curLevel) { + return false; + } + return true; +} + +std::string NetMgrLogWrapper::GetBriefFileName(const std::string &file) +{ + auto pos = file.find_last_of("/"); + if (pos != std::string::npos) { + return file.substr(pos + 1); + } + + pos = file.find_last_of("\\"); + if (pos != std::string::npos) { + return file.substr(pos + 1); + } + + return file; +} +} // namespace Telephony +} // namespace OHOS \ No newline at end of file