Signed-off-by: zhf <zhanghaifeng11@huawei.com>
This commit is contained in:
zhf
2021-12-18 10:58:48 +08:00
parent e42a4d5808
commit 357c686306
179 changed files with 16571 additions and 29 deletions
Executable
+177
View File
@@ -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
Regular → Executable
+1 -1
View File
@@ -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**}
Regular → Executable
+84 -28
View File
@@ -1,39 +1,95 @@
# communication_netmanager_standard
# Net Manager<a name="EN-US_TOPIC_0000001105058232"></a>
#### 介绍
{**以下是 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/)
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

@@ -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> DnsAddrInfo::Unmarshalling(Parcel &parcel)
{
sptr<DnsAddrInfo> ptr = (std::make_unique<DnsAddrInfo>()).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
@@ -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<INetAddr> &addrInfo)
{
sptr<IDnsResolverService> 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<DnsAddrInfo> &hints, std::vector<sptr<DnsAddrInfo>> &dnsAddrInfo)
{
sptr<IDnsResolverService> 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<IDnsResolverService> 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<IDnsResolverService> 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<IDnsResolverService> 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<std::string> &servers, const std::vector<std::string> &domains)
{
sptr<IDnsResolverService> 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<std::string> &servers,
std::vector<std::string> &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount)
{
sptr<IDnsResolverService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return IPC_PROXY_ERR;
}
return proxy->GetResolverInfo(netId, servers, domains, baseTimeoutMsec, retryCount);
}
sptr<IDnsResolverService> DnsResolverClient::GetProxy()
{
std::lock_guard lock(mutex_);
if (dnsResolverService_) {
NETMGR_LOGI("get proxy is ok");
return dnsResolverService_;
}
NETMGR_LOGI("execute GetSystemAbilityManager");
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
NETMGR_LOGE("GetProxy, get SystemAbilityManager failed");
return nullptr;
}
sptr<IRemoteObject> remote = sam->CheckSystemAbility(COMM_DNS_MANAGER_SYS_ABILITY_ID);
if (remote == nullptr) {
NETMGR_LOGE("get Remote service failed");
return nullptr;
}
deathRecipient_ = (std::make_unique<DnsResolverDeathRecipient>(*this)).release();
if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) {
NETMGR_LOGE("add death recipient failed");
return nullptr;
}
dnsResolverService_ = iface_cast<IDnsResolverService>(remote);
if (dnsResolverService_ == nullptr) {
NETMGR_LOGE("get Remote service proxy failed");
return nullptr;
}
return dnsResolverService_;
}
void DnsResolverClient::OnRemoteDied(const wptr<IRemoteObject> &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<IRemoteObject> 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
@@ -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<InterfaceConfiguration> &ic)
{
sptr<IEthernetService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return IPC_PROXY_ERR;
}
return proxy->SetIfaceConfig(iface, ic);
}
sptr<InterfaceConfiguration> EthernetClient::GetIfaceConfig(const std::string &iface)
{
sptr<IEthernetService> 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<IEthernetService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return IPC_PROXY_ERR;
}
return proxy->IsActivate(iface);
}
std::vector<std::string> EthernetClient::GetActivateInterfaces()
{
sptr<IEthernetService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return {};
}
return proxy->GetActivateInterfaces();
}
sptr<IEthernetService> EthernetClient::GetProxy()
{
std::lock_guard lock(mutex_);
if (ethernetService_) {
NETMGR_LOGI("get proxy is ok");
return ethernetService_;
}
NETMGR_LOGI("execute GetSystemAbilityManager");
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
NETMGR_LOGE("GetProxy, get SystemAbilityManager failed");
return nullptr;
}
sptr<IRemoteObject> remote = sam->CheckSystemAbility(COMM_ETHERNET_MANAGER_SYS_ABILITY_ID);
if (remote == nullptr) {
NETMGR_LOGE("get Remote service failed");
return nullptr;
}
deathRecipient_ = (std::make_unique<EthernetDeathRecipient>(*this)).release();
if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) {
NETMGR_LOGE("add death recipient failed");
return nullptr;
}
ethernetService_ = iface_cast<IEthernetService>(remote);
if (ethernetService_ == nullptr) {
NETMGR_LOGE("get Remote service proxy failed");
return nullptr;
}
return ethernetService_;
}
void EthernetClient::OnRemoteDied(const wptr<IRemoteObject> &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<IRemoteObject> 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
@@ -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<int32_t>(mode_))) {
return false;
}
if (!ipStatic_.Marshalling(parcel)) {
NETMGR_LOGE("write ipStatic_ to parcel failed");
return false;
}
return true;
}
sptr<InterfaceConfiguration> InterfaceConfiguration::Unmarshalling(Parcel &parcel)
{
sptr<InterfaceConfiguration> ptr = (std::make_unique<InterfaceConfiguration>()).release();
if (ptr == nullptr) {
return nullptr;
}
int32_t mode = 0;
if (!parcel.ReadInt32(mode)) {
return nullptr;
}
ptr->mode_ = static_cast<IPSetMode>(mode);
sptr<StaticConfiguration> sc = StaticConfiguration::Unmarshalling(parcel);
if (sc == nullptr) {
NETMGR_LOGE("sc is null");
return nullptr;
}
ptr->ipStatic_ = *sc;
return ptr;
}
} // namespace NetManagerStandard
} // namespace OHOS
@@ -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> StaticConfiguration::Unmarshalling(Parcel &parcel)
{
sptr<StaticConfiguration> ptr = (std::make_unique<StaticConfiguration>()).release();
if (ptr == nullptr) {
return nullptr;
}
sptr<INetAddr> ipAddr = INetAddr::Unmarshalling(parcel);
if (ipAddr == nullptr) {
NETMGR_LOGE("ipAddr_ is null");
return nullptr;
}
ptr->ipAddr_ = *ipAddr;
sptr<INetAddr> route = INetAddr::Unmarshalling(parcel);
if (route == nullptr) {
NETMGR_LOGE("route_ is null");
return nullptr;
}
ptr->route_ = *route;
sptr<INetAddr> gate = INetAddr::Unmarshalling(parcel);
if (gate == nullptr) {
NETMGR_LOGE("gate_ is null");
return nullptr;
}
ptr->gate_ = *gate;
sptr<INetAddr> 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<INetAddr> 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
+136
View File
@@ -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> INetAddr::Unmarshalling(Parcel &parcel)
{
sptr<INetAddr> ptr = (std::make_unique<INetAddr>()).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<INetAddr> &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
@@ -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<NetConnCallbackInfo> 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
@@ -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> NetConnCallbackInfo::Unmarshalling(Parcel &parcel)
{
sptr<NetConnCallbackInfo> ptr = (std::make_unique<NetConnCallbackInfo>()).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<NetConnCallbackInfo> &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
@@ -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<INetConnService> 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<INetConnService> 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<INetConnService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return IPC_PROXY_ERR;
}
return proxy->UnregisterNetSupplier(supplierId);
}
int32_t NetConnClient::RegisterNetConnCallback(const sptr<INetConnCallback> &callback)
{
sptr<INetConnService> 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> &netSpecifier,
const sptr<INetConnCallback> &callback)
{
sptr<INetConnService> 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<INetConnCallback> &callback)
{
sptr<INetConnService> 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> &netSpecifier,
const sptr<INetConnCallback> &callback)
{
sptr<INetConnService> 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> &netSupplierInfo)
{
sptr<INetConnService> 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<INetConnService> 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> &netLinkInfo)
{
sptr<INetConnService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return IPC_PROXY_ERR;
}
return proxy->UpdateNetLinkInfo(supplierId, netLinkInfo);
}
sptr<INetConnService> NetConnClient::GetProxy()
{
std::lock_guard lock(mutex_);
if (NetConnService_) {
NETMGR_LOGI("get proxy is ok");
return NetConnService_;
}
NETMGR_LOGI("execute GetSystemAbilityManager");
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
NETMGR_LOGE("GetProxy, get SystemAbilityManager failed");
return nullptr;
}
sptr<IRemoteObject> 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<NetConnDeathRecipient>(*this)).release();
if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) {
NETMGR_LOGE("add death recipient failed");
return nullptr;
}
NetConnService_ = iface_cast<INetConnService>(remote);
if (NetConnService_ == nullptr) {
NETMGR_LOGE("get Remote service proxy failed");
return nullptr;
}
return NetConnService_;
}
void NetConnClient::OnRemoteDied(const wptr<IRemoteObject> &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<IRemoteObject> 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
@@ -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> NetLinkInfo::Unmarshalling(Parcel &parcel)
{
sptr<NetLinkInfo> ptr = (std::make_unique<NetLinkInfo>()).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<INetAddr> 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> 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<NetLinkInfo> &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
@@ -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> NetSpecifier::Unmarshalling(Parcel &parcel)
{
sptr<NetSpecifier> ptr = (std::make_unique<NetSpecifier>()).release();
if (ptr == nullptr) {
NETMGR_LOGE("make_unique<NetSpecifier>() 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<NetSpecifier> &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
@@ -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> NetSupplierInfo::Unmarshalling(Parcel &parcel)
{
sptr<NetSupplierInfo> ptr = (std::make_unique<NetSupplierInfo>()).release();
if (ptr == nullptr) {
NETMGR_LOGE("make_unique<NetSupplierInfo>() 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<NetSupplierInfo> &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
+117
View File
@@ -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> Route::Unmarshalling(Parcel &parcel)
{
sptr<Route> ptr = (std::make_unique<Route>()).release();
if (ptr == nullptr) {
NETMGR_LOGE("make_unique<Route>() failed");
return nullptr;
}
if (!parcel.ReadString(ptr->iface_)) {
return nullptr;
}
sptr<INetAddr> destination = INetAddr::Unmarshalling(parcel);
if (destination == nullptr) {
NETMGR_LOGE("read destination from parcel failed");
return nullptr;
}
ptr->destination_ = *destination;
sptr<INetAddr> 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<Route> &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
@@ -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<INetPolicyService> 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<INetPolicyService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return NetUidPolicy::NET_POLICY_NONE;
}
return proxy->GetUidPolicy(uid);
}
std::vector<uint32_t> NetPolicyClient::GetUids(NetUidPolicy policy)
{
std::vector<uint32_t> uids;
sptr<INetPolicyService> 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<INetPolicyService> 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<INetPolicyService> proxy = GetProxy();
if (proxy == nullptr) {
NETMGR_LOGE("proxy is nullptr");
return false;
}
return proxy->IsUidNetAccess(uid, ifaceName);
}
sptr<INetPolicyService> NetPolicyClient::GetProxy()
{
std::lock_guard lock(mutex_);
if (netPolicyService_ != nullptr) {
return netPolicyService_;
}
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
NETMGR_LOGE("GetProxy, get SystemAbilityManager failed");
return nullptr;
}
sptr<IRemoteObject> 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<NetPolicyDeathRecipient>(*this)).release();
if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) {
NETMGR_LOGE("add death recipient failed");
return nullptr;
}
netPolicyService_ = iface_cast<INetPolicyService>(remote);
if (netPolicyService_ == nullptr) {
NETMGR_LOGE("get Remote service proxy failed");
return nullptr;
}
return netPolicyService_;
}
void NetPolicyClient::OnRemoteDied(const wptr<IRemoteObject> &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<IRemoteObject> 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
+72
View File
@@ -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
+70
View File
@@ -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 <string>
#include <vector>
#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
+57
View File
@@ -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"
}
+52
View File
@@ -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 <string>
#include <vector>
#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<std::string> 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
+158
View File
@@ -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<DnsResolverAsyncContext *>(data);
if (context == nullptr) {
NETMGR_LOGE("context == nullptr");
return;
}
std::string hostName = context->host;
std::vector<INetAddr> addrInfo;
NETMGR_LOGI("ExecDnsResolverCallback [%{public}s]", hostName.c_str());
DelayedSingleton<DnsResolverClient>::GetInstance()->GetAddressesByName(hostName, addrInfo);
NETMGR_LOGI("ExecDnsResolverCallback, addrInfo.size = [%{public}d]", static_cast<int>(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<DnsResolverAsyncContext *>(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<DnsResolverAsyncContext>().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<int>(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
+62
View File
@@ -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"
}
+86
View File
@@ -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 <string>
#include <vector>
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<std::string> 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
+470
View File
@@ -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 <memory>
#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<InterfaceConfiguration> config = std::make_unique<InterfaceConfiguration>().release();
if (config == nullptr) {
NETMGR_LOGE("config == nullptr");
return;
}
addr0.address_ = context->dns0AddrInfo;
addr1.address_ = context->dns1AddrInfo;
config->mode_ = static_cast<IPSetMode>(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<EthernetClient>::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<EthernetAsyncContext *>(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<InterfaceConfiguration> config =
DelayedSingleton<EthernetClient>::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<EthernetAsyncContext *>(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<EthernetClient>::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<EthernetAsyncContext *>(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<EthernetClient>::GetInstance()->GetActivateInterfaces();
}
void NapiEthernet::CompleteGetActivateInterfaces(napi_env env, napi_status status, void *data)
{
NETMGR_LOGI("CompleteGetActivateInterfaces");
EthernetAsyncContext* context = static_cast<EthernetAsyncContext *>(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<int>(argc));
EthernetAsyncContext* context = std::make_unique<EthernetAsyncContext>().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<int>(argc));
EthernetAsyncContext* context = std::make_unique<EthernetAsyncContext>().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<int>(argc));
EthernetAsyncContext* context = std::make_unique<EthernetAsyncContext>().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<int>(argc));
EthernetAsyncContext* context = std::make_unique<EthernetAsyncContext>().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<int32_t>(IPSetMode::STATIC))),
DECLARE_NAPI_STATIC_PROPERTY("DHCP",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(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
+55
View File
@@ -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"
}
+73
View File
@@ -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 <string>
#include <vector>
#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<uint32_t> 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
+442
View File
@@ -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 <memory>
#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<NetPolicyAsyncContext *>(data);
if (context == nullptr) {
NETMGR_LOGE("context == nullptr");
return;
}
NetUidPolicy policy = static_cast<NetUidPolicy>(context->policy);
context->policyResult =
static_cast<int32_t>(DelayedSingleton<NetPolicyClient>::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<NetPolicyAsyncContext *>(data);
if (context == nullptr) {
NETMGR_LOGE("context == nullptr");
return;
}
NetUidPolicy policy = static_cast<NetUidPolicy>(context->policy);
context->uidTogether = DelayedSingleton<NetPolicyClient>::GetInstance()->GetUids(policy);
NETMGR_LOGI("ExecGetUids, policy = [%{public}d], res.length = [%{public}d]",
context->policy, static_cast<int>(context->uidTogether.size()));
}
void NapiNetPolicy::ExecGetUidPolicy(napi_env env, void *data)
{
NetPolicyAsyncContext* context = static_cast<NetPolicyAsyncContext *>(data);
if (context == nullptr) {
NETMGR_LOGE("context == nullptr");
return;
}
context->policyResult =
static_cast<int32_t>(DelayedSingleton<NetPolicyClient>::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<NetPolicyAsyncContext *>(data);
if (context == nullptr) {
NETMGR_LOGE("context == nullptr");
return;
}
if (context->interfaceName.length() > 0) {
context->result =
DelayedSingleton<NetPolicyClient>::GetInstance()->IsUidNetAccess(context->uid, context->interfaceName);
} else {
context->result =
DelayedSingleton<NetPolicyClient>::GetInstance()->IsUidNetAccess(context->uid, context->metered);
}
}
void NapiNetPolicy::CompleteSetUidPolicy(napi_env env, napi_status status, void *data)
{
NetPolicyAsyncContext* context = static_cast<NetPolicyAsyncContext *>(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<int32_t>(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<int32_t>(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<NetPolicyAsyncContext *>(data);
if (context == nullptr) {
NETMGR_LOGE("context == nullptr");
return;
}
napi_value info = nullptr;
std::vector<uint32_t>& 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<NetPolicyAsyncContext *>(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<NetPolicyAsyncContext *>(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<int32_t>(NetUidPolicy::NET_POLICY_NONE))),
DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_ALLOW_METERED_BACKGROUND",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(NetUidPolicy::NET_POLICY_ALLOW_METERED_BACKGROUND))),
DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_TEMPORARY_ALLOW_METERED",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(NetUidPolicy::NET_POLICY_TEMPORARY_ALLOW_METERED))),
DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_REJECT_METERED_BACKGROUND",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(NetUidPolicy::NET_POLICY_REJECT_METERED_BACKGROUND))),
DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_ALLOW_ALL",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(NetUidPolicy::NET_POLICY_ALLOW_ALL))),
DECLARE_NAPI_STATIC_PROPERTY("NET_POLICY_REJECT_ALL",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(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<int32_t>(NetPolicyResultCode::ERR_NONE))),
DECLARE_NAPI_STATIC_PROPERTY("ERR_INTERNAL_ERROR",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(NetPolicyResultCode::ERR_INTERNAL_ERROR))),
DECLARE_NAPI_STATIC_PROPERTY("ERR_INVALID_UID",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(NetPolicyResultCode::ERR_INVALID_UID))),
DECLARE_NAPI_STATIC_PROPERTY("ERR_INVALID_POLICY",
NpiCommon::NapiValueByInt32(env, static_cast<int32_t>(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<NetPolicyAsyncContext>().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<int>(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<NetPolicyAsyncContext>().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<int>(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<NetPolicyAsyncContext>().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<int>(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<NetPolicyAsyncContext>().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<int>(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
+77
View File
@@ -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"
}
@@ -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 <string>
#include <vector>
#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<DnsAddrInfo> Unmarshalling(Parcel &parcel);
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif
@@ -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 <string>
#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<INetAddr> &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<DnsAddrInfo> &hints, std::vector<sptr<DnsAddrInfo>> &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<std::string> &servers, const std::vector<std::string> &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<std::string> &servers,
std::vector<std::string> &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<IRemoteObject> &remote) override
{
client_.OnRemoteDied(remote);
}
private:
DnsResolverClient &client_;
};
private:
sptr<IDnsResolverService> GetProxy();
void OnRemoteDied(const wptr<IRemoteObject> &remote);
private:
std::mutex mutex_;
sptr<IDnsResolverService> dnsResolverService_;
sptr<IRemoteObject::DeathRecipient> deathRecipient_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // DNS_RESOLVER_MANAGER_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
+80
View File
@@ -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"
}
@@ -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 <string>
#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<InterfaceConfiguration> &ic);
/**
* @brief Gets the network interface configuration parameters
*
* @param Network interface name
* @return Parameter is returned on success, null on failure
*/
sptr<InterfaceConfiguration> 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<std::string> GetActivateInterfaces();
private:
class EthernetDeathRecipient : public IRemoteObject::DeathRecipient {
public:
explicit EthernetDeathRecipient(EthernetClient &client) : client_(client) {}
~EthernetDeathRecipient() override = default;
void OnRemoteDied(const wptr<IRemoteObject> &remote) override
{
client_.OnRemoteDied(remote);
}
private:
EthernetClient &client_;
};
private:
sptr<IEthernetService> GetProxy();
void OnRemoteDied(const wptr<IRemoteObject> &remote);
private:
std::mutex mutex_;
sptr<IEthernetService> ethernetService_;
sptr<IRemoteObject::DeathRecipient> deathRecipient_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // ETHERNET_MANAGER_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
@@ -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<InterfaceConfiguration> Unmarshalling(Parcel &parcel);
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif
@@ -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 <string>
#include <vector>
#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<INetAddr> dnsServers_;
std::string domain_;
virtual bool Marshalling(Parcel &parcel) const override;
static sptr<StaticConfiguration> Unmarshalling(Parcel &parcel);
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif
+67
View File
@@ -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 <errors.h>
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
+83
View File
@@ -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"
}
@@ -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 <string>
#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<INetAddr> Unmarshalling(Parcel &parcel);
static bool Marshalling(Parcel &parcel, const sptr<INetAddr> &object);
std::string ToString(const std::string tab = "") const;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif
@@ -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 <string>
#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<NetConnCallbackInfo> &info) = 0;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // I_NET_CONN_CALLBACK_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 <map>
#include "iremote_stub.h"
#include "i_net_conn_callback.h"
namespace OHOS {
namespace NetManagerStandard {
class NetConnCallbackStub : public IRemoteStub<INetConnCallback> {
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<uint32_t, NetConnCallbackFunc> memberFuncMap_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NET_CONN_CALLBACK_STUB_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 <string>
#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<NetConnCallbackInfo> Unmarshalling(Parcel &parcel);
static bool Marshalling(Parcel &parcel, const sptr<NetConnCallbackInfo> &object);
std::string ToString(const std::string &tab) const;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NET_CALLBACK_INFO_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 <string>
#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<INetConnCallback> &callback);
int32_t RegisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback);
int32_t UnregisterNetConnCallback(const sptr<INetConnCallback> &callback);
int32_t UnregisterNetConnCallback(const sptr<NetSpecifier> &netSpecifier, const sptr<INetConnCallback> &callback);
int32_t UpdateNetSupplierInfo(uint32_t supplierId, const sptr<NetSupplierInfo> &netSupplierInfo);
int32_t UpdateNetCapabilities(uint32_t supplierId, uint64_t netCapabilities);
int32_t UpdateNetLinkInfo(uint32_t supplierId, const sptr<NetLinkInfo> &netLinkInfo);
private:
class NetConnDeathRecipient : public IRemoteObject::DeathRecipient {
public:
explicit NetConnDeathRecipient(NetConnClient &client) : client_(client) {}
~NetConnDeathRecipient() override = default;
void OnRemoteDied(const wptr<IRemoteObject> &remote) override
{
client_.OnRemoteDied(remote);
}
private:
NetConnClient &client_;
};
private:
sptr<INetConnService> GetProxy();
void OnRemoteDied(const wptr<IRemoteObject> &remote);
private:
std::mutex mutex_;
sptr<INetConnService> NetConnService_;
sptr<IRemoteObject::DeathRecipient> deathRecipient_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NET_CONN_MANAGER_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
@@ -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 <list>
#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<INetAddr> netAddrList_;
std::list<INetAddr> dnsList_;
std::list<Route> routeList_;
uint16_t mtu_ = 0;
virtual bool Marshalling(Parcel &parcel) const override;
static sptr<NetLinkInfo> Unmarshalling(Parcel &parcel);
static bool Marshalling(Parcel &parcel, const sptr<NetLinkInfo> &object);
std::string ToString(const std::string &tab) const;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NET_LINK_INFO_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 <string>
#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<NetSpecifier> Unmarshalling(Parcel &parcel);
static bool Marshalling(Parcel &parcel, const sptr<NetSpecifier> &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
@@ -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 <string>
#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<NetSupplierInfo> Unmarshalling(Parcel &parcel);
static bool Marshalling(Parcel &parcel, const sptr<NetSupplierInfo> &object);
std::string ToString(const std::string &tab) const;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NET_SUPPLIER_INFO_H
+39
View File
@@ -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 <string>
#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<Route> Unmarshalling(Parcel &parcel);
static bool Marshalling(Parcel &parcel, const sptr<Route> &object);
std::string ToString(const std::string &tab) const;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif
+75
View File
@@ -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"
}
@@ -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<uint32_t> 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<IRemoteObject> &remote) override
{
client_.OnRemoteDied(remote);
}
private:
NetPolicyClient &client_;
};
private:
sptr<INetPolicyService> GetProxy();
void OnRemoteDied(const wptr<IRemoteObject> &remote);
private:
std::mutex mutex_;
sptr<INetPolicyService> netPolicyService_;
sptr<IRemoteObject::DeathRecipient> deathRecipient_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NET_POLICY_MANAGER_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
+32
View File
@@ -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
}
Executable
+62
View File
@@ -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"
]
}
}
}
+36
View File
@@ -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"
}
Binary file not shown.
Binary file not shown.
@@ -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 <condition_variable>
#include <mutex>
#include <vector>
namespace OHOS {
namespace nmd {
template<typename T>
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<std::mutex> 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<std::mutex> 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<T> vt_;
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_BLOCKING_QUEUE_H__
+39
View File
@@ -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 <vector>
#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<common::socket_base> serverSocket)
: fd_(fd), msg_(msg, msg + msgLen), serverSocket_(serverSocket)
{}
virtual ~job() = default;
virtual void run() = 0;
protected:
int fd_;
std::vector<uint8_t> msg_;
std::shared_ptr<common::socket_base> serverSocket_;
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_JOB_H__
+539
View File
@@ -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 <cstring>
#include <limits>
#include <memory>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <string>
#include <unistd.h>
#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<uint8_t>::max(), "AF_UNSPEC value too large");
static_assert(AF_INET <= std::numeric_limits<uint8_t>::max(), "AF_INET value too large");
static_assert(AF_INET6 <= std::numeric_limits<uint8_t>::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<struct addrinfo, struct addrinfo_deleter> 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<const sockaddr_in *>(&sa));
case AF_INET6:
return ip_sock_addr(*reinterpret_cast<const sockaddr_in6 *>(&sa));
default:
return ip_sock_addr();
}
}
static ip_sock_addr toIPSockAddr(const sockaddr_storage &ss)
{
return toIPSockAddr(*reinterpret_cast<const sockaddr *>(&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<sockaddr_in *>(&ss)->sin_addr = mData.ip.v4;
reinterpret_cast<sockaddr_in *>(&ss)->sin_port = htons(mData.port);
break;
case AF_INET6:
reinterpret_cast<sockaddr_in6 *>(&ss)->sin6_addr = mData.ip.v6;
reinterpret_cast<sockaddr_in6 *>(&ss)->sin6_port = htons(mData.port);
reinterpret_cast<sockaddr_in6 *>(&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__
@@ -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__
@@ -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 <string>
#include <memory>
#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<nmd::common::server_socket>()),
pool_(std::make_shared<nmd::thread_pool>(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<nmd::common::server_socket> server_;
std::shared_ptr<thread_pool> pool_;
nmd::job *job_;
bool mRunning = false;
};
} // namespace common
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_SERVER_TEMPLATE_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 <functional>
#include <memory>
#include <netinet/in.h>
#include <sys/epoll.h>
#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<typename R, typename... Params>
void setRecevedHandler(R (*)(Params...))
{}
template<typename R, typename C, typename... Params>
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<void(const int, const uint8_t *, const size_t)> handler_;
private:
int create(int domain, int protocol);
};
} // namespace common
} // namespace nmd
} // namespace OHOS
#endif // !NETD_SOCKET_BASE_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 <memory>
#include <vector>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
#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<std::thread *> workers_;
nmd::blocking_queue<nmd::job *> *workQueue_;
std::mutex mutex_;
std::condition_variable cond_;
void threadLoop();
nmd::job *takeJobFromQueue();
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_THREAD_POOL_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__
@@ -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 <netinet/in.h>
#include <string>
#include <vector>
#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<uint8_t> answer = std::vector<uint8_t>(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<std::string> searchDomains {}; // domains to search
std::vector<nmd::common::net_utils::ip_sock_addr> 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 &param)
{
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<std::string> servers;
std::vector<std::string> 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__
@@ -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 <netdb.h>
#include <netinet/in.h>
#include <vector>
#include <string>
namespace OHOS {
namespace nmd {
struct dnsresolver_params;
struct netd_net_context;
class dnsresolv_controller {
public:
int getResolverInfo(const uint16_t netid, std::vector<std::string> &servers, std::vector<std::string> &domains,
struct dns_res_params &param);
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__
@@ -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 <stdint.h>
#include <string>
#include <vector>
#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<common::socket_base> 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<std::string> &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<std::string> &servers, std::vector<std::string> &domains,
dns_res_params &param);
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_
@@ -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 <string>
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__
@@ -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 <memory>
#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<common::server_socket> &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__
@@ -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 <string>
#include <vector>
#include <ostream>
namespace OHOS {
namespace nmd {
typedef struct interface_configuration_parcel {
std::string ifName;
std::string hwAddr;
std::string ipv4Addr;
int prefixLength;
std::vector<std::string> 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<std::string> 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__
@@ -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 <interface_controller.h>
#include <memory>
#include <network_controller.h>
#include <route_controller.h>
#include <string>
#include <traffic_controller.h>
#include <vector>
#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<char> destination;
int prefixLength;
std::vector<char> srcL2Address;
std::vector<char> dstL2Address;
int pmtu = 1500;
} tether_offload_rule_parcel;
typedef struct tether_config_parcel {
bool usingLegacyDnsProxy;
std::vector<std::string> 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<unsigned int> 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<std::string> 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<network_controller> networkController_;
std::shared_ptr<route_controller> routeController_;
std::shared_ptr<interface_controller> interfaceController_;
static std::vector<unsigned int> interfaceIdex_;
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_NET_MANAGER_NATIVE_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 <map>
#include <stddef.h>
#include <string>
#include <stdio.h>
#include <stdint.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
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<std::string, std::string>(key, value));
}
const char *findParam(const char *key);
const char *rtMessageName(int type);
~netlink_event();
private:
Action action_;
std::map<std::string, std::string> params_;
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_NETLINK_EVENT_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 <vector>
#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<netlink_event> 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<event_reporter> &reporter)
{
this->reporter_ = reporter;
}
netlink_handler(int protocol, int pid);
~netlink_handler();
private:
std::shared_ptr<event_reporter> reporter_;
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_NETLINK_HANDLER_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 <functional>
#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<void(std::shared_ptr<netlink_event>)> &handler);
int listen();
void stopListen();
bool getNetlinkListenerState();
private:
bool running_ = false;
std::function<void(std::shared_ptr<netlink_event>)> onEventHandler_;
void onDataAvaliable(int fd, char *buf, ssize_t size);
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_NETLINK_LISTENER_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 <memory>
#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<netlink_handler> getRouteHandler()
{
return this->routeHandler_;
}
static int getPid()
{
return pid_;
}
static void setPid(int pid)
{
pid_ = pid;
}
static std::shared_ptr<event_reporter> getReporter()
{
return reporter_;
}
explicit netlink_manager(int pid);
~netlink_manager();
private:
static int pid_;
static std::shared_ptr<event_reporter> reporter_;
std::shared_ptr<netlink_handler> routeHandler_;
void startRouteHandler();
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_NETLINK_MANAGER_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 <functional>
#include <memory>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
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<void(int, char *, ssize_t)> &handler);
void setPid(int pid)
{
this->pid_ = pid;
}
private:
std::function<void(int, char *, ssize_t)> 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__
@@ -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 <string>
#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
@@ -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 <map>
#include <tuple>
#include <vector>
#include <set>
#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<nmd::NmdNetwork *> getNetworks();
nmd::NmdNetwork *getNetwork(int netId);
private:
int defaultNetId_;
std::map<int, NmdNetwork *> networks_;
std::tuple<bool, nmd::NmdNetwork *> findNetworkById(int netId);
int getNetworkForInterface(std::string &interfaceName);
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_NETWORK_CONTROLLER_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 <set>
#include <string>
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<std::string> 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<std::string> interfaces_;
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_NMD_NETWORK_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 <map>
#include <netinet/in.h>
#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<std::string, uint32_t> interfaceToTable_;
static uint32_t getRouteTableForInterface(const char *interfaceName);
void modifyIpRule(std::string interface, NetworkPermission permission);
};
} // namespace nmd
} // namespace OHOS
#endif // !INCLUDE_ROUTE_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 <ostream>
#include <string>
#include <vector>
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<arp_cache_information> 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__
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
* 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.
-->
<info>
<process>netmanager</process>
<systemability> <!-- Declare a system ability and its profile -->
<name>1151</name> <!-- Declare the id of system ability. Must be same with system_ability_definition.h -->
<libpath>libnet_conn_manager.z.so</libpath> <!-- Declare the path of .so file which includes the system ability; Note: 1 .so file can have 1 to N system abilities. -->
<!--<depend></depend> --> <!-- Declare the name of system abilities which the system ability depends on, using ";" as separator among names. If there are dependencies, it needs to check if all those dependencies are available in service manager before starting the system ability. -->
<!--<depend-time-out></depend-time-out> --> <!-- Check all dependencies are available before the timeout period ended. The MAX_DEPENDENCY_TIMEOUT is 60s. -->
<run-on-create>true</run-on-create> <!-- "true" means the system ability would start immediately, "false" means the system ability would start on demand. -->
<distributed>false</distributed> <!-- "true" means the system ability supports distributed scheduling while "false" is not. -->
<dump-level>1</dump-level> <!-- Declare the dump level. 1-high; 2-media; 3-low -->
</systemability>
</info>
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
* 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.
-->
<info>
<process>netmanager</process>
<systemability> <!-- Declare a system ability and its profile -->
<name>1152</name> <!-- Declare the id of system ability. Must be same with system_ability_definition.h -->
<libpath>libnet_policy_manager.z.so</libpath> <!-- Declare the path of .so file which includes the system ability; Note: 1 .so file can have 1 to N system abilities. -->
<!--<depend></depend> --> <!-- Declare the name of system abilities which the system ability depends on, using ";" as separator among names. If there are dependencies, it needs to check if all those dependencies are available in service manager before starting the system ability. -->
<!--<depend-time-out></depend-time-out> --> <!-- Check all dependencies are available before the timeout period ended. The MAX_DEPENDENCY_TIMEOUT is 60s. -->
<run-on-create>true</run-on-create> <!-- "true" means the system ability would start immediately, "false" means the system ability would start on demand. -->
<distributed>false</distributed> <!-- "true" means the system ability supports distributed scheduling while "false" is not. -->
<dump-level>1</dump-level> <!-- Declare the dump level. 1-high; 2-media; 3-low -->
</systemability>
</info>
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
* 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.
-->
<info>
<process>netmanager</process>
<systemability> <!-- Declare a system ability and its profile -->
<name>1156</name> <!-- Declare the id of system ability. Must be same with system_ability_definition.h -->
<libpath>libdns_resolver_manager.z.so</libpath> <!-- Declare the path of .so file which includes the system ability; Note: 1 .so file can have 1 to N system abilities. -->
<!--<depend></depend> --> <!-- Declare the name of system abilities which the system ability depends on, using ";" as separator among names. If there are dependencies, it needs to check if all those dependencies are available in service manager before starting the system ability. -->
<!--<depend-time-out></depend-time-out> --> <!-- Check all dependencies are available before the timeout period ended. The MAX_DEPENDENCY_TIMEOUT is 60s. -->
<run-on-create>true</run-on-create> <!-- "true" means the system ability would start immediately, "false" means the system ability would start on demand. -->
<distributed>false</distributed> <!-- "true" means the system ability supports distributed scheduling while "false" is not. -->
<dump-level>1</dump-level> <!-- Declare the dump level. 1-high; 2-media; 3-low -->
</systemability>
</info>
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
* 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.
-->
<info>
<process>netmanager</process>
<systemability> <!-- Declare a system ability and its profile -->
<name>1157</name> <!-- Declare the id of system ability. Must be same with system_ability_definition.h -->
<libpath>libethernet_manager.z.so</libpath> <!-- Declare the path of .so file which includes the system ability; Note: 1 .so file can have 1 to N system abilities. -->
<!--<depend></depend> --> <!-- Declare the name of system abilities which the system ability depends on, using ";" as separator among names. If there are dependencies, it needs to check if all those dependencies are available in service manager before starting the system ability. -->
<!--<depend-time-out></depend-time-out> --> <!-- Check all dependencies are available before the timeout period ended. The MAX_DEPENDENCY_TIMEOUT is 60s. -->
<run-on-create>true</run-on-create> <!-- "true" means the system ability would start immediately, "false" means the system ability would start on demand. -->
<distributed>false</distributed> <!-- "true" means the system ability supports distributed scheduling while "false" is not. -->
<dump-level>1</dump-level> <!-- Declare the dump level. 1-high; 2-media; 3-low -->
</systemability>
</info>
+25
View File
@@ -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"
}
+49
View File
@@ -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 <string>
#include <map>
#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<std::string, bool> &param);
bool SendBroadcast(const BroadcastInfo &info, const std::map<std::string, int32_t> &param);
bool SendBroadcast(const BroadcastInfo &info, const std::map<std::string, std::string> &param);
private:
template <typename T>
bool SendBroadcastEx(const BroadcastInfo &info, const std::map<std::string, T> &param);
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // BROADCAST_MANAGER_H
+243
View File
@@ -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 <string>
#include <mutex>
#ifdef NATIVE_NETD_FEATURE
#include "dnsresolv_service.h"
#include "fwmark_server.h"
#include "net_manager_native.h"
#include "netlink_manager.h"
#else
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/route.h>
#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<std::string> &servers, const std::vector<std::string> &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<std::string> &servers,
std::vector<std::string> &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<addrinfo> &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<OHOS::nmd::NetManagerNative> netdService_ = nullptr;
std::unique_ptr<OHOS::nmd::netlink_manager> manager_ = nullptr;
std::unique_ptr<OHOS::nmd::fwmark_server> fwmarkServer_ = nullptr;
std::unique_ptr<OHOS::nmd::dnsresolv_service> dnsResolvService_ = nullptr;
#endif
static NetdController *singleInstance_;
static std::mutex mutex_;
bool initFlag_ = false;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NETD_CONTROLLER_H
+97
View File
@@ -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 <atomic>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <thread>
#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<void()> 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<std::mutex> locker(mutex_);
stopStatus_ = true;
timerCond_.notify_one();
}).detach();
}
void StartOnce(int interval, std::function<void()> 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<std::mutex> locker(mutex_);
timerCond_.wait(locker, [this] { return stopStatus_ == true; });
if (stopStatus_ == true)
tryStopFlag_ = false;
}
private:
std::atomic<bool> stopStatus_;
std::atomic<bool> tryStopFlag_;
std::mutex mutex_;
std::condition_variable timerCond_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // NET_MANAGER_TIMER_H
+75
View File
@@ -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<std::string, bool> &param)
{
return SendBroadcastEx(info, param);
}
bool BroadcastManager::SendBroadcast(const BroadcastInfo &info, const std::map<std::string, int32_t> &param)
{
return SendBroadcastEx(info, param);
}
bool BroadcastManager::SendBroadcast(const BroadcastInfo &info, const std::map<std::string, std::string> &param)
{
return SendBroadcastEx(info, param);
}
template <typename T>
bool BroadcastManager::SendBroadcastEx(const BroadcastInfo &info, const std::map<std::string, T> &param)
{
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
+430
View File
@@ -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 <signal.h>
#include "net_conn_types.h"
#else
#include <sys/ioctl.h>
#include <fcntl.h>
#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<nmd::NetManagerNative>();
netdService_->init();
int32_t pid = getpid();
manager_ = std::make_unique<OHOS::nmd::netlink_manager>(pid);
std::thread nlManager([&] { manager_->start(); });
fwmarkServer_ = std::make_unique<OHOS::nmd::fwmark_server>();
std::thread fwserve([&] { fwmarkServer_->start(); });
dnsResolvService_ = std::make_unique<OHOS::nmd::dnsresolv_service>();
std::thread dnsresolvServe([&] { dnsResolvService_->start(); });
nlManager.detach();
fwserve.detach();
dnsresolvServe.detach();
#else
return;
#endif
}
NetdController *NetdController::GetInstance()
{
if (singleInstance_ == nullptr) {
std::unique_lock<std::mutex> lock(mutex_);
if (singleInstance_ == nullptr) {
singleInstance_ = std::make_unique<NetdController>().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<std::string> &servers, const std::vector<std::string> &domains)
{
std::unique_lock<std::mutex> 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<std::string> &servers,
std::vector<std::string> &domains,
uint16_t &baseTimeoutMsec, uint8_t &retryCount)
{
std::unique_lock<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<addrinfo> &res, uint16_t netId)
{
std::unique_lock<std::mutex> 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<struct sockaddr_in*>(&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<struct sockaddr_in*>(&rt.rt_genmask))->sin_family=AF_INET;
if (inet_aton(mask.c_str(), &(reinterpret_cast<struct sockaddr_in*>(&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
+69
View File
@@ -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"
}
+61
View File
@@ -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<DnsResolverService> {
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<INetAddr> &addrInfo) override;
int32_t GetAddrInfo(const std::string &hostName, const std::string &server,
const sptr<DnsAddrInfo> &hints, std::vector<sptr<DnsAddrInfo>> &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<std::string> &servers, const std::vector<std::string> &domains) override;
int32_t GetResolverInfo(uint16_t netId, std::vector<std::string> &servers,
std::vector<std::string> &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
@@ -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 <string>
#include "iremote_proxy.h"
#include "i_dns_resolver_service.h"
namespace OHOS {
namespace NetManagerStandard {
class DnsResolverServiceProxy : public IRemoteProxy<IDnsResolverService> {
public:
explicit DnsResolverServiceProxy(const sptr<IRemoteObject> &impl);
virtual ~DnsResolverServiceProxy();
bool WriteInterfaceToken(MessageParcel &data);
int32_t GetAddressesByName(const std::string &hostName, std::vector<INetAddr> &addrInfo) override;
int32_t GetAddrInfo(const std::string &hostName, const std::string &server,
const sptr<DnsAddrInfo> &hints, std::vector<sptr<DnsAddrInfo>> &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<std::string> &servers, const std::vector<std::string> &domains) override;
int32_t GetResolverInfo(uint16_t netId, std::vector<std::string> &servers,
std::vector<std::string> &domains, uint16_t &baseTimeoutMsec, uint8_t &retryCount) override;
private:
static inline BrokerDelegator<DnsResolverServiceProxy> delegator_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // 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_STUB_H
#define DNS_RESOLVER_SERVICE_STUB_H
#include <map>
#include "iremote_stub.h"
#include "i_dns_resolver_service.h"
namespace OHOS {
namespace NetManagerStandard {
class DnsResolverServiceStub : public IRemoteStub<IDnsResolverService> {
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<uint32_t, DnsResolverServiceFunc> memberFuncMap_;
};
} // namespace NetManagerStandard
} // namespace OHOS
#endif // DNS_RESOLVER_SERVICE_STUB_H

Some files were not shown because too many files have changed in this diff Show More