update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai 2021-06-02 00:43:15 +08:00
parent 24ee7bc004
commit 30300b7591
292 changed files with 43544 additions and 86 deletions

15
.gitattributes vendored Normal file
View File

@ -0,0 +1,15 @@
*.tgz filter=lfs diff=lfs merge=lfs -text
*.trp filter=lfs diff=lfs merge=lfs -text
*.apk filter=lfs diff=lfs merge=lfs -text
*.jar filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.asm filter=lfs diff=lfs merge=lfs -text
*.8svn filter=lfs diff=lfs merge=lfs -text
*.9svn filter=lfs diff=lfs merge=lfs -text
*.dylib filter=lfs diff=lfs merge=lfs -text
*.exe filter=lfs diff=lfs merge=lfs -text
*.a filter=lfs diff=lfs merge=lfs -text
*.so filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.dll filter=lfs diff=lfs merge=lfs -text

41
BUILD.gn Normal file
View File

@ -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.
import("deviceauth_env.gni")
import("hals/deviceauth_hals.gni")
group("deviceauth_build") {
deps = [
"${hals_path}:${hal_module_name}",
"services:deviceauth",
]
}
group("deviceauth_service_build") {
deps = [
"${hals_path}:${hal_module_name}",
"services:deviceauth_service",
]
}
group("deviceauth_sdk_build") {
deps = [
"${hals_path}:${hal_module_name}",
"services:deviceauth_sdk",
]
}
group("deviceauth_test_build") {
testonly = true
deps = [ "test/unittest/deviceauth:deviceauth_llt" ]
}

0
LICENSE Executable file → Normal file
View File

147
README.md
View File

@ -1,43 +1,140 @@
# Introduction<a name="EN-US_TOPIC_0000001085515342"></a>
# deviceauth<a name="EN-US_TOPIC_0000001150002727"></a>
- **Device interconnection security**
- [Introduction](#section11660541593)
- [Directory Structure](#section161941989596)
- [Usage](#section1312121216216)
- [Available APIs](#section1551164914237)
To securely transmit user data between devices, the device authentication module provides the capabilities of establishing and verifying trust relationships between devices. This document describes how an IoT controller and an IoT device establish and verify a trust relationship.
- [Repositories Involved](#section1371113476307)
- **IoT device interconnection security**
## Introduction<a name="section11660541593"></a>
The device authentication module allows an IoT controller \(such as a smartphone and tablet\) and an IoT device \(such as a smart home device and wearable\) to establish and verify a P2P trust relationship with each other, without requiring login to the IoT controller and IoT device using the same account. Based on the trust relationship, the IoT controller and IoT device can transmit encrypted user data through a secure P2P connection.
The device authentication module belongs to the security subsystem of OpenHarmony. It manages the entire lifecycle of trust relationships between devices, including establishment, maintenance, use, and cancellation, and implements authentication and secure session key exchange between trusted devices. It provides basic capabilities for trusted interconnections between devices that run OpenHarmony.
- **IoT controller identifier**
The device authentication module provides the following capabilities:
When a P2P trust relationship is established between the IoT controller and IoT device, a public/private key pair is generated based on the elliptic curve cryptography \(ECC\) and serves as the identifier of the IoT controller. The IoT controller may connect to multiple IoT devices. The device authentication module generates different identifiers for the IoT controller to isolate its connections to different IoT devices.
- Device trust relationship management: manages the establishment, maintenance, and cancellation of trust relationships between devices in a unified manner; allows the isolation and controllable sharing of trust relationships created by different services.
- Device trust relationship authentication: authenticates trust relationships between devices, allows trusted devices to exchange secure session keys with each other, and sets up connections between trusted devices through the DSoftBus.
- **IoT device identifier**
The device authentication module consists of three submodules: device group management, device group authentication, and account-irrelevant P2P device authentication. The following figure shows the logical architecture of the device authentication module.
The IoT device identifier is also a public/private key pair generated based on the ECC when a P2P trust relationship is established between the IoT controller and IoT device. The private key is stored on the IoT device. Each time the device is restored to factory settings, the public/private key pair will be reset.
**Figure 1** Architecture of the device authentication module<a name="fig4460722185514"></a>
The preceding identifiers are used for secure communications between the IoT controller and IoT device.
- **P2P trust relationship establishment and verification**
![](figures/en-us_deviceauth_architecture.png)
When an IoT controller and an IoT device establish a P2P trust relationship, they exchange identifiers.
In the architecture:
During this process, the user needs to enter the personal identification number \(PIN\) or any other information provided by the IoT device on the IoT controller. Typically, a PIN is dynamically generated if the IoT device has a screen, or preset by the manufacturer if the IoT device does not have a screen. A PIN can be a number consisting of six digits or a QR code. After the user enters the PIN, the IoT controller and IoT device invoke the device authentication service to perform authentication and session key exchange based on the password authenticated key exchange \(PAKE\) protocol, and use the session key to exchange the public keys of their identifiers.
- Device group management: allows you to manage the trust relationships between the local device and other devices created by different services in a unified manner, create trust relationships between devices using the provided APIs, create an account-irrelevant device group, add trusted devices to the group, and create a trust relationship between isolated devices.
- Device group authentication: allows devices to authenticate the trust relationships that have been established between them and exchange session keys.
- Account-irrelevant P2P device authentication: allows two devices to establish a trust relationship based on a shared secret, and exchange a session key for secure communication based on the trusted relationship.
When the IoT controller and IoT device communicate with each other after establishing a trust relationship, they exchange public keys of their identifiers and verify the trust relationship by checking whether they have stored the identity information of each other. Based on their public/private key pairs, the IoT controller and IoT device exchange keys and establish a secure communications channel for transmitting encrypted data.
# Directory Structure<a name="EN-US_TOPIC_0000001085515522"></a>
## Directory Structure<a name="section161941989596"></a>
```
base/security
├── deviceauth
│ ├── frameworks
│ │ └── deviceauth_lite # Device authentication implementation
│ └── interfaces
│ └── innerkits
│ └── deviceauth_lite # Device authentication APIs
/base/security/deviceauth
├── frameworks # Device authentication framework code
├── hals # HAL code for the tool library
│ ├── inc # Tool library header files
│ └── src # Tool library source files
├── interfaces # APIs exposed externally
└── services # Device authentication services
├── common # Common code
├── group_auth # Device group authentication
├── group_manager # Device group management
├── module # Authenticator module (including the account-irrelevant P2P device authenticator)
└── session # Scheduling and session management module
```
# Repositories Involved<a name="EN-US_TOPIC_0000001085355664"></a>
## Usage<a name="section1312121216216"></a>
### Available APIs<a name="section1551164914237"></a>
The device group management sub-module abstracts trust relationships established by different services between devices into trust groups and provides unified APIs for creating, deleting, and querying groups. The device group authentication sub-module provides trusted device authentication and end-to-end session key exchange based on the trust groups.
**Table 1** APIs in DeviceGroupManager
<a name="table1731550155318"></a>
<table><thead align="left"><tr id="row4419501537"><th class="cellrowborder" valign="top" width="57.38999999999999%" id="mcps1.2.3.1.1"><p id="p54150165315"><a name="p54150165315"></a><a name="p54150165315"></a>API</p>
</th>
<th class="cellrowborder" valign="top" width="42.61%" id="mcps1.2.3.1.2"><p id="p941150145313"><a name="p941150145313"></a><a name="p941150145313"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row34145016535"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1487722894416"><a name="p1487722894416"></a><a name="p1487722894416"></a>const DeviceGroupManager *GetGmInstance()</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p13562171015712"><a name="p13562171015712"></a><a name="p13562171015712"></a>Obtains a <strong id="b4999346135811"><a name="b4999346135811"></a><a name="b4999346135811"></a>DeviceGroupManager</strong> instance.</p>
</td>
</tr>
<tr id="row1027292610453"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1227312634518"><a name="p1227312634518"></a><a name="p1227312634518"></a>int32_t RegCallback(const char *appId, const DeviceAuthCallback *callback)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p7488141134613"><a name="p7488141134613"></a><a name="p7488141134613"></a>Registers a callback.</p>
</td>
</tr>
<tr id="row1746172917474"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p9758144610285"><a name="p9758144610285"></a><a name="p9758144610285"></a>int32_t CreateGroup(int64_t requestId, const char *appId, const char *createParams)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p2431455765"><a name="p2431455765"></a><a name="p2431455765"></a>Creates a group of trusted devices.</p>
</td>
</tr>
<tr id="row10992232154714"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1310363994713"><a name="p1310363994713"></a><a name="p1310363994713"></a>int32_t DeleteGroup(int64_t requestId, const char *appId, const char *disbandParams)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p126575774517"><a name="p126575774517"></a><a name="p126575774517"></a>Deletes a group of trusted devices.</p>
</td>
</tr>
<tr id="row1440154863415"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p19702122715481"><a name="p19702122715481"></a><a name="p19702122715481"></a>int32_t AddMemberToGroup(int64_t requestId, const char *appId, const char *addParams)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p240224817343"><a name="p240224817343"></a><a name="p240224817343"></a>Adds a member to a specified group.</p>
</td>
</tr>
<tr id="row495164812345"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1872417515488"><a name="p1872417515488"></a><a name="p1872417515488"></a>int32_t DeleteMemberFromGroup(int64_t requestId, const char *appId, const char *deleteParams);</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p1995144893411"><a name="p1995144893411"></a><a name="p1995144893411"></a>Deletes a member from a specified group.</p>
</td>
</tr>
<tr id="row4107114933418"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p794617473016"><a name="p794617473016"></a><a name="p794617473016"></a>int32_t ProcessData(int64_t requestId, const uint8_t *data, uint32_t dataLen)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p11107849113418"><a name="p11107849113418"></a><a name="p11107849113418"></a>Processes data that is bound or unbound.</p>
</td>
</tr>
<tr id="row3270349193419"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p179130216514"><a name="p179130216514"></a><a name="p179130216514"></a>int32_t GetGroupInfo(const char *appId, const char *queryParams, char **returnGroupVec, uint32_t *groupNum)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p12701049183411"><a name="p12701049183411"></a><a name="p12701049183411"></a>Obtains information about a trusted group of devices.</p>
</td>
</tr>
</tbody>
</table>
**Table 2** APIs in GroupAuthManager
<a name="table12330133114308"></a>
<table><thead align="left"><tr id="row15330631193013"><th class="cellrowborder" valign="top" width="57.38999999999999%" id="mcps1.2.3.1.1"><p id="p73319319302"><a name="p73319319302"></a><a name="p73319319302"></a>API</p>
</th>
<th class="cellrowborder" valign="top" width="42.61%" id="mcps1.2.3.1.2"><p id="p133312317305"><a name="p133312317305"></a><a name="p133312317305"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row15331183193010"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p19743328133620"><a name="p19743328133620"></a><a name="p19743328133620"></a>const GroupAuthManager *GetGaInstance()</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p16742028153611"><a name="p16742028153611"></a><a name="p16742028153611"></a>Obtains a <strong id="b13399173415119"><a name="b13399173415119"></a><a name="b13399173415119"></a>GroupAuthManager</strong> instance.</p>
</td>
</tr>
<tr id="row7331133163017"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p118111117133514"><a name="p118111117133514"></a><a name="p118111117133514"></a>int32_t AuthDevice(int64_t authReqId, const char *authParams, const DeviceAuthCallback *gaCallback)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p151481335193817"><a name="p151481335193817"></a><a name="p151481335193817"></a>Authenticates a peer device.</p>
</td>
</tr>
<tr id="row633283153012"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p12534111115352"><a name="p12534111115352"></a><a name="p12534111115352"></a>int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t dataLen,</p>
<p id="p16534181113358"><a name="p16534181113358"></a><a name="p16534181113358"></a>const DeviceAuthCallback *gaCallback)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p1633173173012"><a name="p1633173173012"></a><a name="p1633173173012"></a>Processes authentication data.</p>
</td>
</tr>
</tbody>
</table>
## Repositories Involved<a name="section1371113476307"></a>
**Security subsystem**
security\_deviceauth
deviceauth

View File

@ -1,43 +1,140 @@
# 简介<a name="ZH-CN_TOPIC_0000001085515342"></a>
# 设备认证<a name="ZH-CN_TOPIC_0000001150002727"></a>
- **设备互联安全性**
- [简介](#section11660541593)
- [目录](#section161941989596)
- [说明](#section1312121216216)
- [接口说明](#section1551164914237)
为实现用户数据在多个终端设备间的安全流转设备认证组件提供将用户多个设备安全连接起来的能力这种能力体现在设备间信任关系建立和设备通信时信任关系验证两个阶段。本文档主要描述IoT设备可信互联场景中主控设备与IoT设备建立、验证信任关系的实现。
- [相关仓](#section1371113476307)
- **IoT设备互联安全**
## 简介<a name="section11660541593"></a>
设备认证提供了IoT主控设备手机、平板等与IoT配件设备如智能家居、智能穿戴等间建立并验证帐号无关点对点信任关系的能力。具备这种信任关系的设备在通信连接时可搭建安全的连接通道实现用户数据的端到端加密传输
在OpenHarmony中设备认证模块作为安全子系统的子模块负责设备间可信关系的建立、维护、使用、撤销等全生命周期的管理实现可信设备间的互信认证和安全会话密钥协商是搭载OpenHarmony的设备进行可信互联的基础平台能力
- **IoT主控设备的身份标识**
设备认证模块当前提供如下功能:
IoT主控设备在与配件设备建立点对点信任关系时会生成椭圆曲线公私钥对作为本设备的身份标识IoT主控设备上可能存在多种IoT设备互联业务设备认证组件将针对不同的IoT设备互联业务为主控设备生成不同的身份标识形成不同业务间的隔离。
- 设备互信关系管理功能:统一管理设备互信关系的建立、维护、撤销过程;支持各个业务创建的设备互信关系的隔离和可控共享。
- 设备互信关系认证功能:提供认证设备间互信关系、进行安全会话密钥协商的能力,支持分布式软总线实现互信设备间的组网。
- **IoT配件设备的身份标识**
为实现上述功能,设备认证模块当前包含设备群组管理、设备群组认证和帐号无关点对点认证三个子模块,其部署逻辑如下图:
IoT配件设备同样会在与主控设备建立点对点信任关系时生成椭圆曲线公私钥对作为本设备的身份标识其中私钥不出IoT设备设备每次恢复出厂设置时会重置该公私钥对。
**图 1** 子系统架构图<a name="fig4460722185514"></a>
上述的身份标识用于IoT主控设备与IoT配件设备间的安全通信下面将描述基于身份标识的帐号无关点对点信任关系建立与验证的实现。
- **设备间点对点信任关系的建立与验证**
![](figures/zh-cn_deviceauth_architecture.png)
IoT主控设备和IoT配件建立帐号无关点对点信任关系的过程实际上是相互交换身份标识的过程。
其中,
在信任关系建立过程中用户需要在主控设备上输入配件设备提供的PIN码或其他形式的共享信息。典型的PIN码呈现形式为对于有屏幕的设备该PIN码动态生成对于没有屏幕的设备该PIN码由设备生产厂家预置并打印在设备上PIN码的格式可以是一个用户可读的6位数字也可以是一个二维码。在用户完成PIN码输入后主控设备和配件设备将调用设备认证服务基于PAKE协议完成认证会话密钥协商并基于该会话密钥安全的交换各自身份公钥。
- 设备群组管理服务:统一管理不同业务建立的本设备与其他设备间的互信关系,并对外提供设备互信关系的创建入口 完成信任建立后创建帐号无关设备群组并将信任对象设备添加进群组OpenHarmony上各业务可独立创建相互隔离的设备间可信关系。
- 设备群组认证服务:支持已建立可信关系的设备间完成互信关系的认证及会话密钥的协商。
- 帐号无关点对点设备认证:提供设备间基于共享秘密建立一对一互信关系的功能,并支持基于这种互信关系的认证密钥协商。
当建立过信任关系的主控设备与配件设备间进行通信时双方将相互交换身份公钥并通过检查本地是否存储对端身份信息的方式确认对端与本设备的信任关系。进一步地基于双方的身份公私钥对通信对端设备可以基于STS协议进行密钥协商并建立安全通信通道支撑设备间通信数据的端到端加密传输。
# 目录<a name="ZH-CN_TOPIC_0000001085515522"></a>
## 目录<a name="section161941989596"></a>
```
base/security
├── deviceauth
│ ├── frameworks
│ │ └── deviceauth_lite 设备授权实现
│ └── interfaces
│ └── innerkits
│ └── deviceauth_lite 设备授权接口
/base/security/deviceauth
├── frameworks # 设备认证框架层代码
├── hals # 平台相关工具库抽象层
│ ├── inc # 工具库头文件
│ └── src # 工具库源文件
├── interfaces # 对外接口目录
└── services # 设备认证服务层代码
├── common # 公共代码库
├── group_auth # 设备群组认证模块
├── group_manager # 设备群组管理模块
├── module # 认证器模块(包括帐号无关点对点设备认证器)
└── session # 调度及会话管理模块
```
# 相关仓<a name="ZH-CN_TOPIC_0000001085355664"></a>
## 说明<a name="section1312121216216"></a>
### 接口说明<a name="section1551164914237"></a>
设备认证组件中,设备群组管理服务负责将不同业务建立的设备间可信关系抽象成一个个可信群组,对外提供统一的接口,包含群组创建、删除、查询等功能;设备群组认证服务基于已经建立过可信关系的设备群组,提供设备可信认证与端到端会话密钥协商功能。
**表 1** 设备群组管理服务提供的API接口\(DeviceGroupManager\)功能介绍
<a name="table1731550155318"></a>
<table><thead align="left"><tr id="row4419501537"><th class="cellrowborder" valign="top" width="57.38999999999999%" id="mcps1.2.3.1.1"><p id="p54150165315"><a name="p54150165315"></a><a name="p54150165315"></a>接口名</p>
</th>
<th class="cellrowborder" valign="top" width="42.61%" id="mcps1.2.3.1.2"><p id="p941150145313"><a name="p941150145313"></a><a name="p941150145313"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row34145016535"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1487722894416"><a name="p1487722894416"></a><a name="p1487722894416"></a>const DeviceGroupManager *GetGmInstance()</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p13562171015712"><a name="p13562171015712"></a><a name="p13562171015712"></a>获取设备群组管理的实例。</p>
</td>
</tr>
<tr id="row1027292610453"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1227312634518"><a name="p1227312634518"></a><a name="p1227312634518"></a>int32_t RegCallback(const char *appId, const DeviceAuthCallback *callback)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p7488141134613"><a name="p7488141134613"></a><a name="p7488141134613"></a>注册业务的监听回调。</p>
</td>
</tr>
<tr id="row1746172917474"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p9758144610285"><a name="p9758144610285"></a><a name="p9758144610285"></a>int32_t CreateGroup(int64_t requestId, const char *appId, const char *createParams)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p2431455765"><a name="p2431455765"></a><a name="p2431455765"></a>创建一个可信设备群组。</p>
</td>
</tr>
<tr id="row10992232154714"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1310363994713"><a name="p1310363994713"></a><a name="p1310363994713"></a>int32_t DeleteGroup(int64_t requestId, const char *appId, const char *disbandParams)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p126575774517"><a name="p126575774517"></a><a name="p126575774517"></a>删除一个可信设备群组。</p>
</td>
</tr>
<tr id="row1440154863415"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p19702122715481"><a name="p19702122715481"></a><a name="p19702122715481"></a>int32_t AddMemberToGroup(int64_t requestId, const char *appId, const char *addParams)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p240224817343"><a name="p240224817343"></a><a name="p240224817343"></a>添加成员到指定群组ID的可信设备群组。</p>
</td>
</tr>
<tr id="row495164812345"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p1872417515488"><a name="p1872417515488"></a><a name="p1872417515488"></a>int32_t DeleteMemberFromGroup(int64_t requestId, const char *appId, const char *deleteParams);</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p1995144893411"><a name="p1995144893411"></a><a name="p1995144893411"></a>从指定可信设备群组里删除可信成员。</p>
</td>
</tr>
<tr id="row4107114933418"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p794617473016"><a name="p794617473016"></a><a name="p794617473016"></a>int32_t ProcessData(int64_t requestId, const uint8_t *data, uint32_t dataLen)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p11107849113418"><a name="p11107849113418"></a><a name="p11107849113418"></a>处理绑定或者解绑的数据。</p>
</td>
</tr>
<tr id="row3270349193419"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p179130216514"><a name="p179130216514"></a><a name="p179130216514"></a>int32_t GetGroupInfo(const char *appId, const char *queryParams, char **returnGroupVec, uint32_t *groupNum)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p12701049183411"><a name="p12701049183411"></a><a name="p12701049183411"></a>查询可信设备群组信息。</p>
</td>
</tr>
</tbody>
</table>
**表 2** 设备群组认证模块提供的API接口\(GroupAuthManager\)功能介绍
<a name="table12330133114308"></a>
<table><thead align="left"><tr id="row15330631193013"><th class="cellrowborder" valign="top" width="57.38999999999999%" id="mcps1.2.3.1.1"><p id="p73319319302"><a name="p73319319302"></a><a name="p73319319302"></a>接口名</p>
</th>
<th class="cellrowborder" valign="top" width="42.61%" id="mcps1.2.3.1.2"><p id="p133312317305"><a name="p133312317305"></a><a name="p133312317305"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row15331183193010"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p19743328133620"><a name="p19743328133620"></a><a name="p19743328133620"></a>const GroupAuthManager *GetGaInstance()</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p16742028153611"><a name="p16742028153611"></a><a name="p16742028153611"></a>获取设备群组认证的实例。</p>
</td>
</tr>
<tr id="row7331133163017"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p118111117133514"><a name="p118111117133514"></a><a name="p118111117133514"></a>int32_t AuthDevice(int64_t authReqId, const char *authParams, const DeviceAuthCallback *gaCallback)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p151481335193817"><a name="p151481335193817"></a><a name="p151481335193817"></a>认证对端是否是可信设备。</p>
</td>
</tr>
<tr id="row633283153012"><td class="cellrowborder" valign="top" width="57.38999999999999%" headers="mcps1.2.3.1.1 "><p id="p12534111115352"><a name="p12534111115352"></a><a name="p12534111115352"></a>int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t dataLen,</p>
<p id="p16534181113358"><a name="p16534181113358"></a><a name="p16534181113358"></a>const DeviceAuthCallback *gaCallback)</p>
</td>
<td class="cellrowborder" valign="top" width="42.61%" headers="mcps1.2.3.1.2 "><p id="p1633173173012"><a name="p1633173173012"></a><a name="p1633173173012"></a>处理认证的数据。</p>
</td>
</tr>
</tbody>
</table>
## 相关仓<a name="section1371113476307"></a>
**安全子系统**
security\_deviceauth
deviceauth

18
deviceauth_env.gni Normal file
View File

@ -0,0 +1,18 @@
# 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.
deviceauth_path = "//base/security/deviceauth"
hals_path = "${deviceauth_path}/hals"
innerkits_path = "${deviceauth_path}/interfaces/innerkits"
frameworks_path = "${deviceauth_path}/frameworks"
services_path = "${deviceauth_path}/services"

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

BIN
figures/icon-caution.gif Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 580 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

0
frameworks/deviceauth_lite/source/hichain.c Normal file → Executable file
View File

View File

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 IPC_ADAPT_H
#define IPC_ADAPT_H
#include <stdbool.h>
#include <stdint.h>
#include "device_auth.h"
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_REQUEST_PARAMS_NUM 8
#define CB_TYPE_DEV_AUTH 1
#define CB_TYPE_TMP_DEV_AUTH 2
#define CB_TYPE_LISTENER 3
typedef struct {
int32_t type;
int32_t valSz;
uint8_t *val;
int32_t idx;
} IpcDataInfo;
enum {
CB_ID_ON_TRANS = 1,
CB_ID_SESS_KEY_DONE,
CB_ID_ON_FINISH,
CB_ID_ON_ERROR,
CB_ID_ON_REQUEST,
CB_ID_ON_GROUP_CREATED,
CB_ID_ON_GROUP_DELETED,
CB_ID_ON_DEV_BOUND,
CB_ID_ON_DEV_UNBOUND,
CB_ID_ON_DEV_UNTRUSTED,
CB_ID_ON_LAST_GROUP_DELETED,
CB_ID_ON_TRUST_DEV_NUM_CHANGED,
};
typedef int32_t (*IpcServiceCall)(const IpcDataInfo *, int32_t, uintptr_t);
int32_t IpcEncodeCallReplay(uintptr_t replayCache, int32_t type, const uint8_t *result, int32_t resultSz);
uint32_t SetIpcCallMap(uintptr_t ipcInstance, IpcServiceCall method, int32_t methodId);
void SetCbCtxToDataCtx(uintptr_t callCtx, int32_t cbIdx);
int32_t CreateCallCtx(uintptr_t *callCtx, uintptr_t *cbCtx);
void DestroyCallCtx(uintptr_t *callCtx, uintptr_t *cbCtx);
int32_t DoBinderCall(uintptr_t callCtx, int32_t methodId, bool withSync);
int32_t SetCallRequestParamInfo(uintptr_t callCtx, int32_t type, const uint8_t *param, int32_t paramSz);
int32_t CreateServiceInstance(uintptr_t *ipcInstance);
void DestroyServiceInstance(uintptr_t *ipcInstance);
int32_t AddDevAuthServiceToManager(uintptr_t *serviceCtx);
void DecodeCallReply(uintptr_t callCtx, IpcDataInfo *replyCache, int32_t cacheNum);
int32_t InitIpcCallBackList(void);
void DeInitIpcCallBackList(void);
void InitDeviceAuthCbCtx(DeviceAuthCallback *ctx, int32_t type);
void InitDevAuthListenerCbCtx(DataChangeListener *ctx);
int32_t AddIpcCallBackByAppId(const char *appId, const uint8_t *cbPtr, int32_t cbSz, int32_t type);
void DelIpcCallBackByAppId(const char *appId, int32_t type);
int32_t AddIpcCallBackByReqId(int64_t reqId, const uint8_t *cbPtr, int32_t cbSz, int32_t type);
void DelIpcCallBackByReqId(int64_t reqId, int32_t type, bool withLock);
int32_t DecodeIpcData(uintptr_t data, int32_t *type, uint8_t **val, int32_t *valSz);
void ProcCbHook(int32_t callbackId, uintptr_t cbHook,
const IpcDataInfo *cbDataCache, int32_t cacheNum, uintptr_t replyCtx);
int32_t GetIpcRequestParamByType(const IpcDataInfo *ipcParams, int32_t paramNum,
int32_t type, uint8_t *paramCache, int32_t *cacheLen);
int32_t AddReqIdByAppId(const char *appId, int64_t reqId);
void AddIpcCbObjByAppId(const char *appId, int32_t objIdx, int32_t type);
void AddIpcCbObjByReqId(int64_t reqId, int32_t objIdx, int32_t type);
bool IsCallbackMethod(int32_t methodId);
bool IsServiceRunning(void);
void ResetIpcCallBackNodeByNodeId(int32_t nodeIdx);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -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 IPC_CALLBACK_PROXY_H
#define IPC_CALLBACK_PROXY_H
#include "ipc_iface.h"
#include "iremote_proxy.h"
namespace OHOS {
class ProxyDevAuthCb : public IRemoteProxy<ICommIpcCallback> {
public:
explicit ProxyDevAuthCb(const sptr<IRemoteObject> &impl);
~ProxyDevAuthCb();
virtual void DoCallBack(int32_t callbackId, uintptr_t cbHook,
MessageParcel &dataParcel, MessageParcel &reply) override;
private:
static inline BrokerDelegator<ProxyDevAuthCb> delegator_;
};
}
#endif

View File

@ -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 IPC_CALLBACK_STUB_H
#define IPC_CALLBACK_STUB_H
#include "ipc_iface.h"
#include "iremote_stub.h"
namespace OHOS {
class StubDevAuthCb : public IRemoteStub<ICommIpcCallback> {
public:
StubDevAuthCb();
~StubDevAuthCb();
virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
virtual void DoCallBack(int32_t callbackId, uintptr_t cbHook,
MessageParcel &dataParcel, MessageParcel &reply) override;
};
}
#endif

View File

@ -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 IPC_DEV_AUTH_PROXY_H
#define IPC_DEV_AUTH_PROXY_H
#include "ipc_iface.h"
#include "iremote_proxy.h"
#include "ipc_callback_stub.h"
namespace OHOS {
class ProxyDevAuth : public IRemoteProxy<IMethodsIpcCall> {
public:
explicit ProxyDevAuth(const sptr<IRemoteObject> &impl);
~ProxyDevAuth();
int32_t DoCallRequest(MessageParcel &dataParcel, MessageParcel &replyParcel, bool withSync);
static bool ServiceRunning(void);
private:
static inline BrokerDelegator<ProxyDevAuth> delegator_;
};
class ProxyDevAuthData {
public:
ProxyDevAuthData() = default;
virtual ~ProxyDevAuthData() = default;
int32_t EncodeCallRequest(int32_t type, const uint8_t *param, int32_t paramSz);
int32_t FinalCallRequest(int32_t methodId);
int32_t ActCall(bool withSync);
void SetCallbackStub(sptr<IRemoteObject> cbRemote);
MessageParcel *GetReplyParcel(void);
public:
MessageParcel replyParcel;
private:
MessageParcel dataParcel;
MessageParcel tmpDataParcel;
sptr<IRemoteObject> cbStub = nullptr;
int32_t paramCnt = 0;
sptr<ProxyDevAuth> GetProxy() const;
bool withCallback = false;
};
}
#endif

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.
*/
#ifndef IPC_DEV_AUTH_STUB_H
#define IPC_DEV_AUTH_STUB_H
#include "ipc_iface.h"
#include "ipc_adapt.h"
#include "iremote_stub.h"
namespace OHOS {
typedef struct {
IpcServiceCall method;
int32_t methodId;
} IpcServiceCallMap;
const int32_t MAX_CALLMAP_SIZE = 32;
const int32_t MAX_CBSTUB_SIZE = 32;
class ServiceDevAuth : public IRemoteStub<IMethodsIpcCall> {
public:
ServiceDevAuth();
~ServiceDevAuth();
virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
void ResetCallMap(void);
int32_t SetCallMap(IpcServiceCall method, int32_t methodId);
static int32_t SetRemoteObject(sptr<IRemoteObject> &object);
static void SetCbDeathRecipient(int32_t cbStubIdx, int32_t cbDataIdx);
static void ResetRemoteObject(int32_t idx);
static void ActCallback(int32_t objIdx, int32_t callbackId,
uintptr_t cbHook, MessageParcel &dataParcel, MessageParcel &reply);
private:
int32_t maxCallMapSz = MAX_CALLMAP_SIZE;
IpcServiceCallMap *callMapTable = nullptr;
int32_t callMapElemNum = 0;
IpcServiceCall GetCallMethodByMethodId(int32_t methodId);
};
class DevAuthDeathRecipient : public IRemoteObject::DeathRecipient {
public:
DevAuthDeathRecipient() {}
DevAuthDeathRecipient(int32_t cbIdx);
~DevAuthDeathRecipient() {}
virtual void OnRemoteDied(const wptr<IRemoteObject>& remoteObject) override;
private:
int32_t callbackIdx;
};
}
#endif

View File

@ -0,0 +1,43 @@
/*
* 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 IPC_IFACE_H
#define IPC_IFACE_H
#include <cstdint>
#include "iremote_broker.h"
#include "message_parcel.h"
namespace OHOS {
class IMethodsIpcCall : public IRemoteBroker {
public:
enum {
DEV_AUTH_CALL_REQUEST = 1,
};
DECLARE_INTERFACE_DESCRIPTOR(u"MethodsIpcCall");
};
class ICommIpcCallback : public IRemoteBroker {
public:
enum {
DEV_AUTH_CALLBACK_REQUEST = 1,
};
DECLARE_INTERFACE_DESCRIPTOR(u"CommIpcCallback");
virtual void DoCallBack(int32_t callbackId, uintptr_t cbHook,
MessageParcel &dataParcel, MessageParcel &reply) = 0;
};
}
#endif

105
frameworks/inc/ipc_sdk.h Normal file
View File

@ -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.
*/
#ifndef IPC_SDK_H
#define IPC_SDK_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define IPC_RESULT_NUM_1 1
#define IPC_RESULT_NUM_2 2
#define IPC_CALL_BACK_STUB_AUTH_ID 0
#define IPC_CALL_BACK_STUB_BIND_ID 1
/* params type for ipc call */
#define PARAM_TYPE_APPID 1
#define PARAM_TYPE_DEV_AUTH_CB 2
#define PARAM_TYPE_LISTERNER 3
#define PARAM_TYPE_REQID 4
#define PARAM_TYPE_CREATE_PARAMS 5
#define PARAM_TYPE_GROUPID 6
#define PARAM_TYPE_UDID 7
#define PARAM_TYPE_ADD_PARAMS 8
#define PARAM_TYPE_DEL_PARAMS 9
#define PARAM_TYPE_COMM_DATA 10
#define PARAM_TYPE_REQ_CFM 11
#define PARAM_TYPE_BIND 12
#define PARAM_TYPE_UNBIND 13
#define PARAM_TYPE_GROUP_TYPE 14
#define PARAM_TYPE_CREDENTIAL 15
#define PARAM_TYPE_MGR_APPID 16
#define PARAM_TYPE_FRIEND_APPID 17
#define PARAM_TYPE_QUERY_PARAMS 18
#define PARAM_TYPE_REG_INFO 19
#define PARAM_TYPE_DATA_NUM 20
#define PARAM_TYPE_SESS_KEY 21
#define PARAM_TYPE_OPCODE 22
#define PARAM_TYPE_IPC_RESULT 23
#define PARAM_TYPE_IPC_RESULT_NUM 24
#define PARAM_TYPE_ERRCODE 25
#define PARAM_TYPE_ERR_INFO 26
#define PARAM_TYPE_REQ_INFO 27
#define PARAM_TYPE_GROUP_INFO 28
#define PARAM_TYPE_DEVICE_INFO 29
#define PARAM_TYPE_AUTH_PARAMS 30
#define PARAM_TYPE_CB_OBJECT 31
enum {
IPC_CALL_ID_REG_CB = 1,
IPC_CALL_ID_UNREG_CB,
IPC_CALL_ID_REG_LISTENER,
IPC_CALL_ID_UNREG_LISTENER,
IPC_CALL_ID_CREATE_GROUP,
IPC_CALL_ID_DEL_GROUP,
IPC_CALL_ID_ADD_GROUP_MEMBER,
IPC_CALL_ID_DEL_GROUP_MEMBER,
IPC_CALL_ID_GM_PROC_DATA,
IPC_CALL_ID_CFM_REQUEST,
IPC_CALL_ID_BIND_PEER,
IPC_CALL_ID_UNBIND_PEER,
IPC_CALL_ID_PROC_LIGHT_DATA,
IPC_CALL_ID_SAVE_CREDENTIAL,
IPC_CALL_ID_APPLY_REG_INFO,
IPC_CALL_ID_ADD_GROUP_MGR,
IPC_CALL_ID_ADD_GROUP_FRIEND,
IPC_CALL_ID_DEL_GROUP_MGR,
IPC_CALL_ID_DEL_GROUP_FRIEND,
IPC_CALL_ID_GET_GROUP_MGR,
IPC_CALL_ID_GET_GROUP_FRIEND,
IPC_CALL_ID_GET_GROUP_INFO,
IPC_CALL_ID_SEARCH_GROUPS,
IPC_CALL_ID_GET_JOINED_GROUPS,
IPC_CALL_ID_GET_RELATED_GROUPS,
IPC_CALL_ID_GET_DEV_INFO_BY_ID,
IPC_CALL_ID_GET_TRUST_DEVICES,
IPC_CALL_ID_IS_DEV_IN_GROUP,
IPC_CALL_ID_DESTROY_INFO,
IPC_CALL_ID_GA_PROC_DATA,
IPC_CALL_ID_QUERY_TRUST_DEV_NUM,
IPC_CALL_ID_IS_TRUST_DEVICE,
IPC_CALL_ID_GET_AUTH_STATE,
IPC_CALL_ID_AUTH_DEVICE,
IPC_CALL_ID_INFORM_DEV_DISCONN
};
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,26 @@
/*
* 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 IPC_SERVICE_H
#define IPC_SERVICE_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,21 @@
# Copyright (C) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
on post-fs-data
start deviceauth_service
service deviceauth_service /system/bin/deviceauth_service
class z_core
user system
group system shell
seclabel u:r:deviceauth_service:s0

1477
frameworks/src/ipc_adapt.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,50 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_callback_proxy.h"
#include "hc_log.h"
#include "ipc_adapt.h"
#include "system_ability_definition.h"
namespace OHOS {
ProxyDevAuthCb::ProxyDevAuthCb(const sptr<IRemoteObject> &impl) : IRemoteProxy<ICommIpcCallback>(impl)
{}
ProxyDevAuthCb::~ProxyDevAuthCb()
{}
void ProxyDevAuthCb::DoCallBack(int32_t callbackId, uintptr_t cbHook, MessageParcel &dataParcel, MessageParcel &reply)
{
int32_t ret;
MessageParcel data;
MessageOption option(MessageOption::TF_SYNC);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
LOGE("Proxy DoCallBack Remote() is null");
return;
}
(void)data.WriteInt32(callbackId);
(void)data.WritePointer(cbHook);
if (dataParcel.GetDataSize() > 0) {
(void)data.WriteBuffer(reinterpret_cast<const void *>(dataParcel.GetData()), dataParcel.GetDataSize());
}
ret = remote->SendRequest(static_cast<uint32_t>(DEV_AUTH_CALLBACK_REQUEST), data, reply, option);
if (ret != NO_ERROR) {
LOGE("SendRequest is failed, error code: %d", ret);
}
return;
}
}

View File

@ -0,0 +1,74 @@
/*
* 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 "ipc_callback_stub.h"
#include "common_defs.h"
#include "hc_log.h"
#include "ipc_adapt.h"
#include "securec.h"
#include "system_ability_definition.h"
namespace OHOS {
StubDevAuthCb::StubDevAuthCb()
{}
StubDevAuthCb::~StubDevAuthCb()
{}
void StubDevAuthCb::DoCallBack(int32_t callbackId, uintptr_t cbHook, MessageParcel &dataParcel, MessageParcel &reply)
{
int32_t ret;
int32_t i;
MessageParcel retParcel;
IpcDataInfo cbDataCache[MAX_REQUEST_PARAMS_NUM] = {{0}};
if (cbHook == 0x0) {
LOGE("Invalid call back hook");
return;
}
for (i = 0; i < MAX_REQUEST_PARAMS_NUM; i++) {
ret = DecodeIpcData(reinterpret_cast<uintptr_t>(&dataParcel), &(cbDataCache[i].type),
&(cbDataCache[i].val), &(cbDataCache[i].valSz));
if (ret != HC_SUCCESS) {
LOGE("decode failed, ret %d", ret);
return;
}
}
ProcCbHook(callbackId, cbHook, cbDataCache, MAX_REQUEST_PARAMS_NUM, reinterpret_cast<uintptr_t>(&reply));
return;
}
int32_t StubDevAuthCb::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
int32_t callbackId;
uintptr_t cbHook = 0x0;
LOGI("enter invoking callback...");
switch (code) {
case DEV_AUTH_CALLBACK_REQUEST:
callbackId = data.ReadInt32();
cbHook = data.ReadPointer();
StubDevAuthCb::DoCallBack(callbackId, cbHook, data, reply);
break;
default:
LOGE("Invoke call back cmd id error, %u", code);
break;
}
LOGI("Invoke callback done");
return 0;
}
}

View File

@ -0,0 +1,148 @@
/*
* 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 "ipc_dev_auth_proxy.h"
#include "common_defs.h"
#include "hc_log.h"
#include "ipc_adapt.h"
#include "ipc_sdk.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
namespace OHOS {
ProxyDevAuth::ProxyDevAuth(const sptr<IRemoteObject> &impl) : IRemoteProxy<IMethodsIpcCall>(impl)
{}
ProxyDevAuth::~ProxyDevAuth()
{}
int32_t ProxyDevAuth::DoCallRequest(MessageParcel &dataParcel, MessageParcel &replyParcel, bool withSync)
{
int32_t ret;
sptr<IRemoteObject> remote = nullptr;
MessageOption option = { MessageOption::TF_SYNC };
LOGI("ProxyDevAuth, SendRequest...");
remote = Remote();
if (remote == nullptr) {
LOGE("Proxy DoCallRequest Remote() is null");
return HC_ERR_IPC_INTERNAL_FAILED;
}
if (withSync == false) {
option = { MessageOption::TF_ASYNC };
}
ret = remote->SendRequest(DEV_AUTH_CALL_REQUEST, dataParcel, replyParcel, option);
LOGI("SendRequest done, ret %d", ret);
(ret == ERR_NONE) ? replyParcel.ReadInt32(ret) : (ret = HC_ERR_IPC_INTERNAL_FAILED);
return ret;
}
bool ProxyDevAuth::ServiceRunning(void)
{
auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (saMgr == nullptr) {
return false;
}
auto daSa = saMgr->GetSystemAbility(DEVICE_AUTH_SERVICE_ID);
if (daSa == nullptr) {
return false;
}
return true;
}
int32_t ProxyDevAuthData::EncodeCallRequest(int32_t type, const uint8_t *param, int32_t paramSz)
{
LOGI("type %d, paramSz %d", type, paramSz);
if (tmpDataParcel.WriteInt32(type) && tmpDataParcel.WriteInt32(paramSz) &&
tmpDataParcel.WriteBuffer(reinterpret_cast<const void *>(param), static_cast<size_t>(paramSz))) {
paramCnt++;
return HC_SUCCESS;
}
return HC_ERROR;
}
int32_t ProxyDevAuthData::FinalCallRequest(int32_t methodId)
{
int32_t dataLen;
const uint8_t *dataPtr = nullptr;
dataLen = static_cast<int32_t>(tmpDataParcel.GetDataSize());
dataPtr = const_cast<const uint8_t *>(reinterpret_cast<uint8_t *>(tmpDataParcel.GetData()));
if ((dataLen <= 0) || (dataPtr == nullptr)) {
LOGE("data invalid");
return HC_ERROR;
}
LOGI("method id %d, param num %d, data length %d", methodId, paramCnt, dataLen);
/* request data length = number of params + params information */
if (!dataParcel.WriteInt32(methodId) || !dataParcel.WriteInt32(dataLen + sizeof(int32_t)) ||
!dataParcel.WriteInt32(paramCnt)) {
return HC_ERROR;
}
if (!dataParcel.WriteBuffer(reinterpret_cast<const void *>(dataPtr), static_cast<size_t>(dataLen))) {
return HC_ERROR;
}
if (withCallback) {
if (!dataParcel.WriteInt32(PARAM_TYPE_CB_OBJECT) || !dataParcel.WriteRemoteObject(cbStub)) {
return HC_ERROR;
}
LOGI("type %d, cbStub %s", PARAM_TYPE_CB_OBJECT, (cbStub != nullptr) ? "true" : "false");
}
cbStub = nullptr;
withCallback = false;
return HC_SUCCESS;
}
sptr<ProxyDevAuth> ProxyDevAuthData::GetProxy() const
{
auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (saMgr == nullptr) {
LOGE("GetSystemAbilityManager failed");
return nullptr;
}
auto daSa = saMgr->GetSystemAbility(DEVICE_AUTH_SERVICE_ID);
if (daSa == nullptr) {
LOGE("GetSystemAbility failed");
return nullptr;
}
return iface_cast<ProxyDevAuth>(daSa);
}
int32_t ProxyDevAuthData::ActCall(bool withSync)
{
auto proxy = GetProxy();
if (proxy == nullptr) {
LOGE("proxy failed");
return HC_ERR_IPC_GET_PROXY;
}
return proxy->DoCallRequest(dataParcel, replyParcel, withSync);
}
MessageParcel *ProxyDevAuthData::GetReplyParcel(void)
{
return &replyParcel;
}
void ProxyDevAuthData::SetCallbackStub(sptr<IRemoteObject> cbRemote)
{
if (cbRemote != nullptr) {
this->cbStub = cbRemote;
withCallback = true;
}
return;
}
}

View File

@ -0,0 +1,298 @@
/*
* 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 "ipc_dev_auth_stub.h"
#include "common_defs.h"
#include "hc_log.h"
#include "ipc_adapt.h"
#include "ipc_callback_stub.h"
#include "ipc_sdk.h"
#include "securec.h"
#include "system_ability_definition.h"
using namespace std;
namespace OHOS {
static std::mutex g_cBMutex;
struct CbStubInfo {
sptr<IRemoteObject> cbStub;
bool inUse;
};
static struct CbStubInfo g_cbStub[MAX_CBSTUB_SIZE];
static bool g_cbStubInited = false;
ServiceDevAuth::ServiceDevAuth()
{}
ServiceDevAuth::~ServiceDevAuth()
{
maxCallMapSz = MAX_CALLMAP_SIZE;
if (callMapTable != nullptr) {
delete callMapTable;
callMapTable = nullptr;
}
callMapElemNum = 0;
}
IpcServiceCall ServiceDevAuth::GetCallMethodByMethodId(int32_t methodId)
{
int32_t i;
if (callMapTable == nullptr) {
return nullptr;
}
for (i = 0; i < maxCallMapSz; i++) {
if ((callMapTable[i].methodId == methodId) && (callMapTable[i].method != nullptr)) {
return callMapTable[i].method;
}
}
return nullptr;
}
static int32_t DecodeCallRequest(MessageParcel &data, IpcDataInfo *paramsCache, int32_t cacheNum, int32_t &inParamNum)
{
int32_t dataLen = 0;
int32_t i;
int32_t ret;
if (data.GetReadableBytes() == 0) {
return HC_SUCCESS;
}
data.ReadInt32(dataLen);
if (dataLen > static_cast<int32_t>(data.GetReadableBytes())) {
return HC_ERR_IPC_BAD_MESSAGE_LENGTH;
}
data.ReadInt32(inParamNum);
if ((inParamNum < 0) || (inParamNum > cacheNum)) {
LOGE("param number invalid, inParamNum - %d", inParamNum);
return HC_ERR_IPC_BAD_PARAM_NUM;
}
LOGI("param number: %d", inParamNum);
for (i = 0; i < inParamNum; i++) {
ret = DecodeIpcData(reinterpret_cast<uintptr_t>(&data), &(paramsCache[i].type),
&(paramsCache[i].val), &(paramsCache[i].valSz));
if (ret != HC_SUCCESS) {
LOGE("decode failed, ret %d", ret);
return ret;
}
LOGI("decode success, param type %d, val size %d", paramsCache[i].type, paramsCache[i].valSz);
}
return HC_SUCCESS;
}
static int32_t GetMethodId(MessageParcel &data, int32_t &methodId)
{
if (data.GetDataSize() < sizeof(int32_t)) {
return HC_ERR_IPC_CALL_DATA_LENGTH;
}
methodId = data.ReadInt32();
LOGI("GetMethodId, id code %d", methodId);
return HC_SUCCESS;
}
static void WithObject(int32_t methodId, MessageParcel &data, IpcDataInfo &ipcData, int32_t &cnt)
{
if (IsCallbackMethod(methodId)) {
ipcData.type = data.ReadInt32();
ipcData.valSz = sizeof(StubDevAuthCb);
sptr<IRemoteObject> tmp = data.ReadRemoteObject();
if (!tmp) {
LOGE("should with remote object, but read failed");
return;
}
ipcData.idx = ServiceDevAuth::SetRemoteObject(tmp);
if (ipcData.idx >= 0) {
ipcData.val = reinterpret_cast<uint8_t *>(&(ipcData.idx));
LOGI("object trans success, set id %d", ipcData.idx);
cnt++;
}
}
return;
}
static void InitCbStubTable()
{
int32_t i;
if (g_cbStubInited) {
return;
}
std::lock_guard<std::mutex> autoLock(g_cBMutex);
if (g_cbStubInited) { /* for first init at the same time */
return;
}
for (i = 0; i < MAX_CBSTUB_SIZE; i++) {
g_cbStub[i].inUse = false;
}
g_cbStubInited = true;
return;
}
int32_t ServiceDevAuth::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
int32_t ret = HC_ERR_IPC_UNKNOW_OPCODE;
int32_t dataLen;
int32_t methodId = 0;
int32_t reqParamNum = 0;
MessageParcel replyCache;
IpcDataInfo reqParams[MAX_REQUEST_PARAMS_NUM] = {{0}};
IpcServiceCall serviceCall = nullptr;
LOGI("request code %u", code);
switch (code) {
case DEV_AUTH_CALL_REQUEST:
ret = GetMethodId(data, methodId);
if (ret != HC_SUCCESS) {
break;
}
serviceCall = GetCallMethodByMethodId(methodId);
if (serviceCall == nullptr) {
ret = HC_ERR_IPC_METHOD_ID_INVALID;
break;
}
ret = DecodeCallRequest(data, reqParams, MAX_REQUEST_PARAMS_NUM, reqParamNum);
if (ret != HC_SUCCESS) {
break;
}
if (reqParamNum < (MAX_REQUEST_PARAMS_NUM - 1)) {
InitCbStubTable();
WithObject(methodId, data, reqParams[reqParamNum], reqParamNum);
}
ret = serviceCall(reqParams, reqParamNum, reinterpret_cast<uintptr_t>(&replyCache));
break;
default:
break;
}
reply.WriteInt32(ret);
dataLen = replyCache.GetDataSize();
if (dataLen > 0) {
reply.WriteInt32(dataLen);
reply.WriteBuffer(reinterpret_cast<const void *>(replyCache.GetData()), dataLen);
}
LOGI("done, request code %u, method id %d, call result %d", code, methodId, ret);
return 0;
}
int32_t ServiceDevAuth::SetCallMap(IpcServiceCall method, int32_t methodId)
{
int32_t len;
errno_t eno;
IpcServiceCallMap *callMapTmp = nullptr;
if ((1 + callMapElemNum) > maxCallMapSz) {
maxCallMapSz += MAX_CALLMAP_SIZE;
if (callMapTable != nullptr) {
callMapTmp = callMapTable;
callMapTable = nullptr;
}
}
if (callMapTable == nullptr) {
callMapTable = new(std::nothrow) IpcServiceCallMap[maxCallMapSz];
if (callMapTable == nullptr) {
return HC_ERR_ALLOC_MEMORY;
}
len = sizeof(IpcServiceCallMap) * maxCallMapSz;
(void)memset_s(callMapTable, len, 0, len);
if (callMapTmp != nullptr) {
eno = memcpy_s(callMapTable, len, callMapTmp, (sizeof(IpcServiceCallMap) * callMapElemNum));
if (eno != EOK) {
delete callMapTable;
callMapTable = callMapTmp;
maxCallMapSz -= MAX_CALLMAP_SIZE;
return HC_ERR_MEMORY_COPY;
}
delete callMapTmp;
callMapTmp = nullptr;
}
}
callMapTable[callMapElemNum].method = method;
callMapTable[callMapElemNum].methodId = methodId;
callMapElemNum++;
return HC_SUCCESS;
}
int32_t ServiceDevAuth::SetRemoteObject(sptr<IRemoteObject> &object)
{
int32_t idx = -1;
int32_t i;
std::lock_guard<std::mutex> autoLock(g_cBMutex);
for (i = 0; i < MAX_CBSTUB_SIZE; i++) {
if (!g_cbStub[i].inUse) {
idx = i;
break;
}
}
LOGI("remote object cache index %d", idx);
if (idx == -1) {
return -1;
}
g_cbStub[idx].cbStub = object;
g_cbStub[idx].inUse = true;
return idx;
}
void ServiceDevAuth::SetCbDeathRecipient(int32_t objIdx, int32_t cbDataIdx)
{
bool bRet = false;
if ((objIdx < 0) || (objIdx >= MAX_CBSTUB_SIZE) || (!g_cbStub[objIdx].inUse)) {
return;
}
std::lock_guard<std::mutex> autoLock(g_cBMutex);
bRet = g_cbStub[objIdx].cbStub->AddDeathRecipient(new(std::nothrow) DevAuthDeathRecipient(cbDataIdx));
LOGI("AddDeathRecipient %s, callback stub idx %d", bRet ? "success" : "failed", objIdx);
return;
}
void ServiceDevAuth::ResetRemoteObject(int32_t idx)
{
if ((idx >= 0) && (idx < MAX_CBSTUB_SIZE)) {
LOGI("remote object used done, idx %d", idx);
std::lock_guard<std::mutex> autoLock(g_cBMutex);
g_cbStub[idx].inUse = false;
}
return;
}
void ServiceDevAuth::ActCallback(int32_t objIdx, int32_t callbackId,
uintptr_t cbHook, MessageParcel &dataParcel, MessageParcel &reply)
{
if ((objIdx < 0) || (objIdx >= MAX_CBSTUB_SIZE) || (!g_cbStub[objIdx].inUse)) {
LOGW("nothing to do, callback id %d, remote object id %d", callbackId, objIdx);
return;
}
std::lock_guard<std::mutex> autoLock(g_cBMutex);
sptr<ICommIpcCallback> proxy = iface_cast<ICommIpcCallback>(g_cbStub[objIdx].cbStub);
proxy->DoCallBack(callbackId, cbHook, dataParcel, reply);
return;
}
DevAuthDeathRecipient::DevAuthDeathRecipient(int32_t cbIdx)
{
callbackIdx = cbIdx;
}
void DevAuthDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remoteObject)
{
LOGI("remote is not actively, to reset local resource");
ResetIpcCallBackNodeByNodeId(callbackIdx);
}
}

2125
frameworks/src/ipc_sdk.c Normal file

File diff suppressed because it is too large Load Diff

1327
frameworks/src/ipc_service.c Normal file

File diff suppressed because it is too large Load Diff

94
hals/BUILD.gn Normal file
View File

@ -0,0 +1,94 @@
# 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("deviceauth_hals.gni")
hal_common_files = [
"src/common/hc_parcel.c",
"src/common/hc_string.c",
"src/common/hc_task_thread.c",
"src/common/hc_tlv_parser.c",
"src/common/json_utils.c",
"src/common/common_util.c",
"src/common/alg_loader.c",
]
ohos_static_library("deviceauth_hal_linux") {
subsystem_name = "security"
include_dirs = hals_inc_path
include_dirs += [
"//third_party/cJSON",
"//utils/native/base/include",
"//third_party/openssl/include/",
"//base/security/huks/interfaces/innerkits/huks_standard/main/include",
]
sources = hal_common_files
sources += [
"src/dev_info/3516/hc_dev_info.c",
"src/linux/L2/crypto_hash_to_point.c",
"src/linux/L2/huks_adapter.c",
"src/linux/hc_condition.c",
"src/linux/hc_file.c",
"src/linux/hc_init_protection.c",
"src/linux/hc_mutex.c",
"src/linux/hc_thread.c",
"src/linux/hc_time.c",
"src/linux/hc_types.c",
]
cflags = [ "-DHILOG_ENABLE" ]
deps = [
"//base/security/huks/interfaces/innerkits/huks_standard/main:libhukssdk",
"//third_party/cJSON:cjson_static",
"//third_party/openssl:libcrypto_static",
"//utils/native/base:utils",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
}
ohos_static_library("deviceauth_hal_liteos") {
subsystem_name = "security"
include_dirs = hals_inc_path
include_dirs += [
"//third_party/cJSON",
"//utils/native/base/include",
]
sources = hal_common_files
sources += [
"src/dev_info/watch/hc_dev_info.c",
"src/liteos/L0/hc_init_protection.c",
"src/liteos/L0/huks_adapter.c",
"src/liteos/hc_condition.c",
"src/liteos/hc_file.c",
"src/liteos/hc_mutex.c",
"src/liteos/hc_thread.c",
"src/liteos/hc_time.c",
"src/liteos/hc_types.c",
]
cflags = [ "-DHILOG_ENABLE" ]
deps = [
"//third_party/cJSON:cjson",
"//utils/native/base:utils",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
}

30
hals/deviceauth_hals.gni Normal file
View File

@ -0,0 +1,30 @@
# 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("//base/security/deviceauth/deviceauth_env.gni")
if (target_os == "liteos") {
hals_inc_path = [
"${hals_path}/inc/common",
"${hals_path}/inc/liteos",
"${hals_path}/inc/dev_info/watch",
]
hal_module_name = "deviceauth_hal_liteos"
} else {
hals_inc_path = [
"${hals_path}/inc/common",
"${hals_path}/inc/linux",
"${hals_path}/inc/dev_info/3516",
]
hal_module_name = "deviceauth_hal_linux"
}

151
hals/inc/common/alg_defs.h Normal file
View File

@ -0,0 +1,151 @@
/*
* 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 ALG_DEFS_H
#define ALG_DEFS_H
#include "common_util.h"
#include "hc_types.h"
#define SHA256_LEN 32
#define HMAC_LEN 32
#define SIGNATURE_LEN 64
#define AE_TAG_LEN 16
#define BIG_PRIME_LEN_384 384
#define BIG_PRIME_LEN_256 256
typedef enum {
PAIR_TYPE_BIND = 0,
PAIR_TYPE_CLONE = 1,
PAIR_TYPE_END
} PairType; // range: 0 ~ 2^8-1
typedef struct {
Uint8Buff authId;
int32_t userType;
int32_t pairType;
} ExtraInfo;
typedef enum {
ED25519 = 0,
X25519 = 1,
P256 = 2,
} Algorithm;
typedef enum {
CURVE_NONE,
CURVE_256,
CURVE_25519,
} CurveType;
typedef struct {
uint8_t *nonce;
uint32_t nonceLen;
uint8_t *aad;
uint32_t aadLen;
} GcmParam;
typedef struct {
uint8_t *key;
uint32_t keyLen;
bool isAlias;
} KeyBuff;
typedef int32_t (*InitAlgFunc)();
typedef int32_t (*Sha256Func)(const Uint8Buff *message, Uint8Buff *hash);
typedef int32_t (*GenerateRandomFunc)(Uint8Buff *rand);
typedef int32_t (*ComputeHmacFunc)(const Uint8Buff *key, const Uint8Buff *message, Uint8Buff *outHmac, bool isAlias);
typedef int32_t (*ComputeHkdfFunc)(const Uint8Buff *baseKey, const Uint8Buff *salt, const Uint8Buff *keyInfo,
Uint8Buff *outHkdf, bool isAlias);
typedef int32_t (*ImportAsymmetricKeyFunc)(const Uint8Buff *keyAlias, const Uint8Buff *authToken,
const ExtraInfo *exInfo);
typedef int32_t (*CheckKeyExistFunc)(const Uint8Buff *keyAlias);
typedef int32_t (*DeleteKeyFunc)(const Uint8Buff *keyAlias);
typedef int32_t (*AesGcmEncryptFunc)(const Uint8Buff *key, const Uint8Buff *plain,
const GcmParam *encryptInfo, bool isAlias, Uint8Buff *outCipher);
typedef int32_t (*AesGcmDecryptFunc)(const Uint8Buff *key, const Uint8Buff *cipher,
const GcmParam *decryptInfo, bool isAlias, Uint8Buff *outPlain);
typedef int32_t (*GetTrustAuthIdListFunc)(const Uint8Buff *ownerAuthId, int32_t trustUserType,
Uint8Buff *outAuthIdList, uint32_t *outCount);
typedef int32_t (*HashToPointFunc)(const Uint8Buff *hash, Algorithm algo, Uint8Buff *outEcPoint);
typedef int32_t (*AgreeSharedSecretWithStorageFunc)(const KeyBuff *priKey, const KeyBuff *pubKey, Algorithm algo,
uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias);
typedef int32_t (*AgreeSharedSecretFunc)(const KeyBuff *priKey, const KeyBuff *pubKey, Algorithm algo,
Uint8Buff *sharedKey);
typedef int32_t (*ComputePublicKeyFunc)(const Uint8Buff *priKey, const Uint8Buff *base, Algorithm algo,
Uint8Buff *pubKey);
typedef int32_t (*BigNumExpModFunc)(const Uint8Buff *base, const Uint8Buff *exp, const char *bigNumHex,
Uint8Buff *outNum);
typedef int32_t (*GenerateKeyPairWithStorageFunc)(const Uint8Buff *keyAlias, uint32_t keyLen, Algorithm algo,
const ExtraInfo *exInfo);
typedef int32_t (*GenerateKeyPairFunc)(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *outPubKey);
typedef int32_t (*ExportPublicKeyFunc)(const Uint8Buff *keyAlias, Uint8Buff *outPubKey);
typedef int32_t (*SignFunc)(const Uint8Buff *keyAlias, const Uint8Buff *message, Algorithm algo,
Uint8Buff *outSignature, bool isAlias);
typedef int32_t (*VerifyFunc)(const Uint8Buff *key, const Uint8Buff *message, Algorithm algo,
const Uint8Buff *signature, bool isAlias);
typedef int32_t (*ImportPublicKeyFunc)(const Uint8Buff *keyAlias, const Uint8Buff *pubKey, Algorithm algo,
const ExtraInfo *exInfo);
typedef bool (*CheckEcPublicKeyFunc)(const Uint8Buff *pubKey, Algorithm algo);
typedef bool (*CheckDlPublicKeyFunc)(const Uint8Buff *key, const char *primeHex);
typedef struct {
InitAlgFunc initAlg;
Sha256Func sha256;
GenerateRandomFunc generateRandom;
ComputeHmacFunc computeHmac;
ComputeHkdfFunc computeHkdf;
ImportAsymmetricKeyFunc importAsymmetricKey;
CheckKeyExistFunc checkKeyExist;
DeleteKeyFunc deleteKey;
AesGcmEncryptFunc aesGcmEncrypt;
AesGcmDecryptFunc aesGcmDecrypt;
HashToPointFunc hashToPoint;
AgreeSharedSecretWithStorageFunc agreeSharedSecretWithStorage;
AgreeSharedSecretFunc agreeSharedSecret;
BigNumExpModFunc bigNumExpMod;
GenerateKeyPairWithStorageFunc generateKeyPairWithStorage;
GenerateKeyPairFunc generateKeyPair;
ExportPublicKeyFunc exportPublicKey;
SignFunc sign;
VerifyFunc verify;
ImportPublicKeyFunc importPublicKey;
ComputePublicKeyFunc computePublicKey;
CheckDlPublicKeyFunc checkDlPublicKey;
CheckEcPublicKeyFunc checkEcPublicKey;
} AlgLoader;
#endif

View File

@ -0,0 +1,23 @@
/*
* 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 ALG_LOADER_H
#define ALG_LOADER_H
#include "alg_defs.h"
const AlgLoader *GetLoaderInstance();
#endif

56
hals/inc/common/common_util.h Executable file
View File

@ -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 COMMON_UTIL_H
#define COMMON_UTIL_H
#include <stdint.h>
#define BYTE_TO_HEX_OPER_LENGTH 2
#define DEC 10
typedef struct {
uint8_t *val;
uint32_t length;
} Uint8Buff;
/*
* Convert hex string to byte.
* @param hexStr: hex string
* @param byte: the converted result, need malloc by caller
* @param byteLen: the length of byte
* @result success(0), otherwise, failure.
*/
int32_t HexStringToByte(const char *hexStr, uint8_t *byte, uint32_t byteLen);
/*
* Convert byte to hex string.
* @param byte: byte to be converted
* @param byteLen: the length of byte
* @param hexStr: the converted result, need malloc by caller, and need malloc for '\0'
* @param hexLen: strlen(hexStr) + 1, for '\0'
* @result success(0), otherwise, failure.
*/
int32_t ByteToHexString(const uint8_t *byte, uint32_t byteLen, char *hexStr, uint32_t hexLen);
/*
* Convert string to int64_t.
* @param cp: string to be converted
* @return the converted result.
*/
int64_t StringToInt64(const char *cp);
#endif

45
hals/inc/common/hc_error.h Executable file
View File

@ -0,0 +1,45 @@
/*
* 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 HC_ERROR_H
#define HC_ERROR_H
enum {
HAL_SUCCESS = 0,
HAL_FAILED = -1,
HAL_ERR_INVALID_PARAM = -2,
HAL_ERR_INVALID_LEN = -3,
HAL_ERR_BAD_ALLOC = -4,
HAL_ERR_NULL_PTR = -5,
HAL_ERR_MEMORY_COPY = -6,
HAL_ERR_FILE_NOT_EXIST = -7,
HAL_ERR_FILE = -8,
HAL_ERR_JSON_FAILED = -9,
HAL_ERR_JSON_GET = -10,
HAL_ERR_JSON_ADD = -11,
HAL_ERR_JSON_REPLACE = -12,
HAL_ERR_JSON_DUPLICATE = -13,
HAL_ERR_INIT_PARAM_SET_FAILED = -14,
HAL_ERR_ADD_PARAM_FAILED = -15,
HAL_ERR_GET_PARAM_FAILED = -16,
HAL_ERR_BUILD_PARAM_SET_FAILED = -17,
HAL_ERR_FRESH_PARAM_SET_FAILED = -18,
HAL_ERR_INIT_FAILED = -19,
};
#endif

88
hals/inc/common/hc_parcel.h Executable file
View File

@ -0,0 +1,88 @@
/*
* 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 HC_PARCEL_H
#define HC_PARCEL_H
#include "hc_types.h"
#define PARCEL_DEFAULT_LENGTH 0
#define PARCEL_DEFAULT_ALLOC_UNIT 0
typedef struct {
char *data;
unsigned int beginPos;
unsigned int endPos;
unsigned int length;
unsigned int allocUnit;
} HcParcel;
HcParcel CreateParcel(uint32_t size, uint32_t allocUnit);
void DeleteParcel(HcParcel *parcel);
void ClearParcel(HcParcel *parcel);
void ResetParcel(HcParcel *parcel, uint32_t size, uint32_t allocUnit);
HcBool ParcelReadWithoutPopData(HcParcel *parcel, void *dst, uint32_t dataSize);
HcBool ParcelRead(HcParcel *parcel, void *dst, uint32_t dataSize);
HcBool ParcelWrite(HcParcel *parcel, const void *src, uint32_t dataSize);
HcBool ParcelReadRevert(HcParcel *parcel, void *dst, uint32_t dataSize);
HcBool ParcelWriteRevert(HcParcel *parcel, const void *src, uint32_t dataSize);
uint32_t GetParcelDataSize(const HcParcel *parcel);
const char *GetParcelData(const HcParcel *parcel);
const char* GetParcelLastChar(const HcParcel *parcel);
HcBool ParcelReadInt32(HcParcel *parcel, int *dst);
HcBool ParcelReadUint32(HcParcel *parcel, uint32_t *dst);
HcBool ParcelReadInt16(HcParcel *parcel, short *dst);
HcBool ParcelReadUint16(HcParcel *parcel, uint16_t *dst);
HcBool ParcelReadInt8(HcParcel *parcel, char *dst);
HcBool ParcelReadUint8(HcParcel *parcel, uint8_t *dst);
HcBool ParcelReadUint64(HcParcel *parcel, uint64_t *dst);
HcBool ParcelReadInt64(HcParcel *parcel, int64_t *dst);
HcBool ParcelWriteInt32(HcParcel *parcel, int src);
HcBool ParcelWriteUint32(HcParcel *parcel, uint32_t src);
HcBool ParcelWriteInt16(HcParcel *parcel, short src);
HcBool ParcelWriteUint16(HcParcel *parcel, uint16_t src);
HcBool ParcelWriteInt8(HcParcel *parcel, char src);
HcBool ParcelWriteUint8(HcParcel *parcel, uint8_t src);
HcBool ParcelWriteUint64(HcParcel *parcel, uint64_t src);
HcBool ParcelWriteInt64(HcParcel *parcel, int64_t src);
HcBool ParcelWriteString(HcParcel *parcel, const char *str);
HcBool ParcelReadString(HcParcel *parcel, char **str);
HcBool ParcelReadParcel(HcParcel *src, HcParcel *dst, uint32_t size, HcBool copy);
HcBool ParcelCopy(HcParcel *src, HcParcel *dst);
HcBool ParcelReadInt32Revert(HcParcel *parcel, int32_t *dst);
HcBool ParcelReadUint32Revert(HcParcel *parcel, uint32_t *dst);
HcBool ParcelReadInt16Revert(HcParcel *parcel, short *dst);
HcBool ParcelReadUint16Revert(HcParcel *parcel, uint16_t *dst);
HcBool ParcelReadInt8Revert(HcParcel *parcel, char *dst);
HcBool ParcelReadUint8Revert(HcParcel *parcel, uint8_t *dst);
HcBool ParcelReadUint64Revert(HcParcel *parcel, uint64_t *dst);
HcBool ParcelReadInt64Revert(HcParcel *parcel, int64_t *dst);
HcBool ParcelWriteInt32Revert(HcParcel *parcel, int src);
HcBool ParcelWriteUint32Revert(HcParcel *parcel, uint32_t src);
HcBool ParcelWriteInt16Revert(HcParcel *parcel, short src);
HcBool ParcelWriteUint16Revert(HcParcel *parcel, uint16_t src);
HcBool ParcelWriteInt8Revert(HcParcel *parcel, char src);
HcBool ParcelWriteUint8Revert(HcParcel *parcel, uint8_t src);
HcBool ParcelWriteUint64Revert(HcParcel *parcel, uint64_t src);
HcBool ParcelWriteInt64Revert(HcParcel *parcel, int64_t src);
void DataRevert(void *data, uint32_t length);
HcBool ParcelPopBack(HcParcel *parcel, uint32_t size);
HcBool ParcelPopFront(HcParcel *parcel, uint32_t size);
HcBool ParcelEraseBlock(HcParcel *parcel, uint32_t start, uint32_t data_size, void *dst);
#endif

100
hals/inc/common/hc_string.h Executable file
View File

@ -0,0 +1,100 @@
/*
* 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 HC_STRING_H
#define HC_STRING_H
#include "hc_parcel.h"
typedef struct HcString {
HcParcel parcel; // parcel data, used to storage the string data
} HcString;
/*
* Append a HcString
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: append string.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringAppend(HcString *self, HcString str);
/*
* Append string pointer
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: string pointer.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringAppendPointer(HcString *self, const char *str);
/*
* Append a char
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: char.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringAppendChar(HcString *self, char c);
/*
* Assign a value to the HcString
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: assign value of ta_sting.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringSet(HcString *self, HcString str);
/*
* Assign a value to the HcString
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: assign value of string pointer.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringSetPointer(HcString *self, const char *str);
/*
* Get the string pointer data
* @param self: self pointer.
* @return the pointer data of the string
*/
const char* StringGet(const HcString *self);
/*
* Get the length of the string
* @param self: self pointer.
* @return the length of the string
*/
uint32_t StringLength(const HcString *self);
/*
* Create a string.
* Notice: You should delete string when you don't need the string anymore.
* @return the created string.
*/
HcString CreateString();
/*
* Delete a string. In fact it will not destroy the string,
* but only free the allocated memory of the string and reset the member's value
* of the string. You can continue to use the string if you want.
* Notice: You should delete the string when you don't need it any more to avoid memory leak.
* @param str: The string you want to delete.
*/
void DeleteString(HcString *str);
#endif

View File

@ -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 HC_TASK_THREAD_H
#define HC_TASK_THREAD_H
#include "hc_thread.h"
#include "hc_vector.h"
typedef struct HcTaskBaseT {
void (*doAction) (struct HcTaskBaseT*);
void (*destroy) (struct HcTaskBaseT*);
} HcTaskBase;
typedef struct {
HcTaskBase* task;
} HcTaskWrap;
DECLARE_HC_VECTOR(TaskVec, HcTaskWrap)
typedef struct HcTaskThreadT {
HcThread thread;
TaskVec tasks;
int32_t (*startThread)(struct HcTaskThreadT* thread);
void (*pushTask) (struct HcTaskThreadT* thread, HcTaskBase* task);
void (*clear) (struct HcTaskThreadT* thread);
void (*stopAndClear) (struct HcTaskThreadT* thread);
HcMutex queueLock;
HcBool quit;
} HcTaskThread;
int32_t InitHcTaskThread(HcTaskThread* thread, size_t stackSize, const char* threadName);
void DestroyHcTaskThread(HcTaskThread* thread);
#endif

313
hals/inc/common/hc_tlv_parser.h Executable file
View File

@ -0,0 +1,313 @@
/*
* 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 HC_TLV_PARSER_H
#define HC_TLV_PARSER_H
#include <hc_parcel.h>
#include <hc_vector.h>
#include <hc_string.h>
#define USE_DEFAULT_TAG 0xFFFF
#define TLV_FAIL (-1)
#define NO_REVERT 0
#define NEED_REVERT 1
#define MAX_TOTOL_LEN (100 * 1024 * 1024)
typedef struct TlvBaseT {
unsigned short tag;
unsigned short length;
unsigned short checkTag;
unsigned short hasValue;
int32_t (*parse)(struct TlvBaseT *, HcParcel *, HcBool);
int32_t (*getlen)(struct TlvBaseT *);
int32_t (*encode)(struct TlvBaseT *, HcParcel *);
void (*deinit)(struct TlvBaseT *);
} TlvBase;
#define DECLARE_TLV_STRUCT(x) \
TlvBase base; \
unsigned int offsetCount; \
unsigned int offset[x];
unsigned short GetTag(unsigned short checkTag, unsigned short defaultTag);
#define BEGIN_TLV_STRUCT_DEFINE(TlvS, CheckTag) \
void Init##TlvS(TlvS *tlv, unsigned short checkTag) \
{ \
typedef TlvS TlvStructType; \
unsigned int index = 0; \
(void)memset_s(&tlv->base, sizeof(tlv->base), 0, sizeof(tlv->base)); \
tlv->base.checkTag = GetTag(checkTag, CheckTag);
#define TLV_MEMBER_OPTION(TlvMember, TlvMemberName, CheckTag) \
Init##TlvMember(&tlv->TlvMemberName, CheckTag); \
tlv->TlvMemberName.base.option = 1; \
tlv->offset[index++] = offsetof(TlvStructType, TlvMemberName);
#define TLV_MEMBER(TlvMember, TlvMemberName, CheckTag) \
Init##TlvMember(&tlv->TlvMemberName, CheckTag); \
tlv->offset[index++] = offsetof(TlvStructType, TlvMemberName);
#define END_TLV_STRUCT_DEFINE() \
tlv->offsetCount = index; \
tlv->base.parse = ParseTlvStruct; \
tlv->base.getlen = GetLenTlvStruct; \
tlv->base.encode = EncodeTlvStruct; \
tlv->base.deinit = DeinitTlvStruct; \
}
#define DECLARE_TLV_FIX_LENGTH_TYPE(TlvName, TypeName) \
typedef struct \
{ \
TlvBase base; \
TypeName data; \
} TlvName;
DECLARE_TLV_FIX_LENGTH_TYPE(TlvInt32, int)
DECLARE_TLV_FIX_LENGTH_TYPE(TlvInt16, short)
DECLARE_TLV_FIX_LENGTH_TYPE(TlvInt8, char)
DECLARE_TLV_FIX_LENGTH_TYPE(TlvUint32, uint32_t)
DECLARE_TLV_FIX_LENGTH_TYPE(TlvUint16, uint16_t)
DECLARE_TLV_FIX_LENGTH_TYPE(TlvUint8, uint8_t)
DECLARE_TLV_FIX_LENGTH_TYPE(TlvUint64, uint64_t)
DECLARE_TLV_FIX_LENGTH_TYPE(TlvInt64, uint64_t)
#define DEFINE_TLV_FIX_LENGTH_TYPE(TlvName, Revert) \
int32_t ParseTlv##TlvName(TlvBase *tlv, HcParcel *parcel, HcBool strict) \
{ \
(void)strict; \
TlvName *realTlv = (TlvName *)(tlv); \
HcBool readRet = HC_FALSE; \
if (tlv->length != sizeof(realTlv->data)) \
{ \
return TLV_FAIL; \
} \
\
if (Revert) \
{ \
readRet = ParcelReadRevert(parcel, &realTlv->data, sizeof(realTlv->data)); \
} else { \
readRet = ParcelRead(parcel, &realTlv->data, sizeof(realTlv->data)); \
} \
if (readRet) \
{ \
return tlv->length; \
} else { \
return TLV_FAIL; \
} \
} \
\
int32_t GetLenTlv##TlvName(TlvBase *tlv) \
{ \
TlvName *realTlv = (TlvName *)(tlv); \
return (int32_t)sizeof(realTlv->data); \
} \
\
int32_t EncodeTlv##TlvName(TlvBase *tlv, HcParcel *parcel) \
{ \
HcBool writeRet = HC_FALSE; \
TlvName *realTlv = (TlvName *)(tlv); \
if (Revert) \
{ \
writeRet = ParcelWriteRevert(parcel, &realTlv->data, sizeof(realTlv->data)); \
} else { \
writeRet = ParcelWrite(parcel, &realTlv->data, sizeof(realTlv->data)); \
} \
if (writeRet) \
{ \
return sizeof(realTlv->data); \
} else { \
return TLV_FAIL; \
} \
} \
\
DECLARE_TLV_PARSE_FUNC(TlvName, ParseTlv##TlvName, GetLenTlv##TlvName, EncodeTlv##TlvName);
void DeinitTlvFixMember(TlvBase *tlv);
#define DECLARE_TLV_PARSE_FUNC(TlvName, TlvParseFunc, TlvGetLenFunc, TlvEncodeFunc) \
void Init##TlvName(TlvName *tlv, unsigned short checkTag) \
{ \
(void)memset_s(&tlv->base, sizeof(tlv->base), 0, sizeof(tlv->base)); \
tlv->base.parse = TlvParseFunc; \
tlv->base.getlen = TlvGetLenFunc; \
tlv->base.encode = TlvEncodeFunc; \
tlv->base.deinit = DeinitTlvFixMember; \
tlv->base.checkTag = checkTag; \
}
#define TLV_INIT(TlvName, TlvData) Init##TlvName(TlvData, USE_DEFAULT_TAG);
#define TLV_DEINIT(TlvData) TlvData.base.deinit((TlvBase *)(&TlvData));
typedef struct {
TlvBase base;
unsigned int offsetCount;
unsigned int offset[0];
} TlvOffsetExample;
HcBool ParseTlvHead(TlvBase *tlv, HcParcel *parcel);
int32_t ParseTlvNode(TlvBase *tlv, HcParcel *parcel, HcBool strict);
int32_t GetlenTlvNode(TlvBase *tlv);
void DeinitTlvNode(TlvBase *tlv);
int32_t ParseTlvStruct(TlvBase *tlv, HcParcel *parcel, HcBool strict);
int32_t EncodeTlvStruct(TlvBase *tlv, HcParcel *parcel);
int32_t GetLenTlvStruct(TlvBase *tlv);
void DeinitTlvStruct(TlvBase *tlv);
int32_t EncodeTlvNode(TlvBase *tlv, HcParcel *parcel, HcBool isRoot);
HcBool DecodeTlvMessage(TlvBase *msg, HcParcel *parcel, HcBool strict);
HcBool EncodeTlvMessage(TlvBase *msg, HcParcel *parcel);
typedef struct {
TlvBase base;
HcParcel data;
} TlvBuffer;
void InitTlvBuffer(TlvBuffer *tlv, unsigned short checkTag);
int32_t ParseTlvBuffer(TlvBase *tlv, HcParcel *parcel, HcBool strict);
int32_t GetlenTlvBuffer(TlvBase *tlv);
int32_t EncodeTlvBuffer(TlvBase *tlv, HcParcel *parcel);
void DeinitTlvBuffer(TlvBase *tlv);
typedef struct {
TlvBase base;
HcString data;
} TlvString;
void InitTlvString(TlvString *tlv, unsigned short checkTag);
int32_t ParseTlvString(TlvBase *tlv, HcParcel *parcel, HcBool strict);
int32_t GetlenTlvString(TlvBase *tlv);
int32_t EncodeTlvString(TlvBase *tlv, HcParcel *parcel);
void DeinitTlvString(TlvBase *tlv);
#define DECLEAR_INIT_FUNC(TlvStruct) \
void Init##TlvStruct(TlvStruct *tlv, unsigned short checkTag);
DECLEAR_INIT_FUNC(TlvUint64)
DECLEAR_INIT_FUNC(TlvUint32)
DECLEAR_INIT_FUNC(TlvUint16)
DECLEAR_INIT_FUNC(TlvUint8)
DECLEAR_INIT_FUNC(TlvInt64)
DECLEAR_INIT_FUNC(TlvInt32)
DECLEAR_INIT_FUNC(TlvInt16)
DECLEAR_INIT_FUNC(TlvInt8)
#define DECLARE_TLV_VECTOR(TlvVecName, TlvVecElement) \
DECLARE_HC_VECTOR(Vec##TlvVecName, TlvVecElement) \
typedef struct { \
TlvBase base; \
Vec##TlvVecName data; \
} TlvVecName; \
void DeinitTlv##TlvVecName(TlvBase *tlv); \
void Init##TlvVecName(TlvVecName *tlv, unsigned short checkTag);
#define IMPLEMENT_TLV_VECTOR(TlvVecName, TlvElementName, VecAllocCount) \
IMPLEMENT_HC_VECTOR(Vec##TlvVecName, TlvElementName, VecAllocCount) \
int32_t ParseTlv##TlvVecName(TlvBase *tlv, HcParcel *parcel, HcBool strict) \
{ \
TlvVecName *realTlv = (TlvVecName *)(tlv); \
uint32_t count = 0; \
if (!ParcelReadUint32(parcel, &count)) { \
return TLV_FAIL; \
} \
int32_t totalLen = sizeof(count); \
uint32_t index = 0; \
for (index = 0; index < count; ++index) { \
TlvElementName tlvElement; \
TlvElementName *curElement = realTlv->data.pushBack(&realTlv->data, &tlvElement); \
if (curElement == NULL) { \
return TLV_FAIL; \
} \
TLV_INIT(TlvElementName, curElement); \
\
int32_t elementLen = ParseTlvNode((TlvBase *)curElement, parcel, strict); \
if (elementLen < 0) { \
return TLV_FAIL; \
} \
totalLen += elementLen; \
if (totalLen >= MAX_TOTOL_LEN) { \
return TLV_FAIL; \
} \
} \
\
return totalLen; \
} \
\
int32_t EncodeTlv##TlvVecName(TlvBase *tlv, HcParcel *parcel) \
{ \
TlvVecName *realTlv = (TlvVecName *)(tlv); \
uint32_t index = 0; \
TlvElementName *element = NULL; \
uint32_t totalLen = 4; \
uint32_t count = realTlv->data.size(&realTlv->data); \
if (!ParcelWriteUint32(parcel, count)) { \
return TLV_FAIL; \
} \
\
FOR_EACH_HC_VECTOR(realTlv->data, index, element) { \
if (element != NULL) { \
uint32_t len = EncodeTlvNode((TlvBase *)element, parcel, HC_FALSE); \
totalLen += len; \
if (totalLen >= MAX_TOTOL_LEN) { \
return TLV_FAIL; \
} \
} \
} \
return totalLen; \
} \
int32_t GetLenTlv##TlvVecName(TlvBase *tlv) \
{ \
TlvVecName *realTlv = (TlvVecName *)(tlv); \
uint32_t index = 0; \
TlvElementName *element = NULL; \
uint32_t totalLen = sizeof(uint32_t); \
FOR_EACH_HC_VECTOR(realTlv->data, index, element) { \
if (element != NULL) { \
totalLen += GetlenTlvNode((TlvBase *)element); \
if (totalLen >= MAX_TOTOL_LEN) { \
return TLV_FAIL; \
} \
} else { \
return TLV_FAIL; \
} \
} \
return totalLen; \
} \
\
void DeinitTlv##TlvVecName(TlvBase *tlv) \
{ \
TlvVecName *realTlv = (TlvVecName *)(tlv); \
uint32_t index = 0; \
TlvElementName *element = NULL; \
FOR_EACH_HC_VECTOR(realTlv->data, index, element) { \
if (element != NULL) { \
TLV_DEINIT((*element)); \
} \
} \
DESTROY_HC_VECTOR(Vec##TlvVecName, &((TlvVecName *)tlv)->data); \
} \
\
void Init##TlvVecName(TlvVecName *tlv, unsigned short checkTag) \
{ \
(void)memset_s(&tlv->base, sizeof(tlv->base), 0, sizeof(tlv->base)); \
tlv->base.parse = ParseTlv##TlvVecName; \
tlv->base.encode = EncodeTlv##TlvVecName; \
tlv->base.getlen = GetLenTlv##TlvVecName; \
tlv->base.deinit = DeinitTlv##TlvVecName; \
tlv->base.checkTag = checkTag; \
tlv->data = CREATE_HC_VECTOR(Vec##TlvVecName); \
}
#endif

172
hals/inc/common/hc_vector.h Executable file
View File

@ -0,0 +1,172 @@
/*
* 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 HC_VECTOR_H
#define HC_VECTOR_H
#include "hc_parcel.h"
#include "securec.h"
/*
* Use DECLARE_HC_VECTOR to declare the vector in the head/src file.
* @para ClassName: the name of the vector-class/vector-struct
* @para Element: the type of the vector element
* @for example:
* DECLARE_HC_VECTOR(IntVec, int)
*/
#define DECLARE_HC_VECTOR(ClassName, Element) \
typedef struct V##ClassName{ \
Element* (*pushBack)(struct V##ClassName*, const Element*); \
Element* (*pushBackT)(struct V##ClassName*, Element); \
HcBool (*popFront)(struct V##ClassName*, Element*); \
HcBool (*eraseElement)(struct V##ClassName*, Element*, uint32_t index); \
uint32_t (*size)(const struct V##ClassName*); \
Element (*get)(const struct V##ClassName*, uint32_t index); \
Element* (*getp)(const struct V##ClassName*, uint32_t index); \
void (*clear)(struct V##ClassName*); \
HcParcel parcel; \
} ClassName;
/*
* Use IMPLEMENT_HC_VECTOR to implement the vector in the source file.
* @para ClassName: the name of the vector-class/vector-struct
* @para Element: the type of the vector element
* @para allocCount: the minimum alloc count
* @for example:
* IMPLEMENT_HC_VECTOR(IntVec, int)
*/
#define IMPLEMENT_HC_VECTOR(ClassName, Element, allocCount) \
Element* VPushBack##ClassName(ClassName* obj, const Element *e) { \
if (obj == NULL || e == NULL) { \
return NULL; \
} \
\
if (ParcelWrite(&obj->parcel, e, sizeof(Element))) { \
int size = obj->size(obj); \
return obj->getp(obj, size-1); \
} else { \
return NULL; \
} \
} \
Element* VPushBackT##ClassName(ClassName* obj, Element e) { \
if (obj == NULL) { \
return NULL; \
} \
\
if (ParcelWrite(&obj->parcel, &e, sizeof(Element))) { \
int size = obj->size(obj); \
return obj->getp(obj, size-1); \
} else { \
return NULL; \
} \
} \
HcBool VPopFront##ClassName(ClassName* obj, Element* e) { \
if (NULL == obj || NULL == e) { \
return HC_FALSE; \
} \
if (obj->size(obj) > 0) { \
return ParcelRead(&obj->parcel, e, sizeof(Element)); \
} else { \
return HC_FALSE; \
} \
} \
HcBool VErase##ClassName(ClassName* obj, Element* e, uint32_t index) { \
if (NULL == obj || NULL == e || index + 1 > obj->size(obj)) { \
return HC_FALSE; \
} \
if (obj->size(obj) > 0) { \
return ParcelEraseBlock(&obj->parcel, index*sizeof(Element), sizeof(Element), e); \
} else { \
return HC_FALSE; \
} \
} \
uint32_t VSize##ClassName(const ClassName* obj) \
{ \
if (NULL == obj) { \
return 0; \
} \
return GetParcelDataSize(&obj->parcel) / sizeof(Element); \
} \
Element VGet##ClassName(const ClassName* obj, uint32_t index) \
{ \
Element e; \
(void)memset_s(&e, sizeof(e), 0, sizeof(e)); \
if (NULL != obj) { \
if (index < obj->size(obj)) { \
if (GetParcelData(&obj->parcel)) { \
return *((Element*)(GetParcelData(&obj->parcel)) + index); \
} else { \
return e; \
} \
} \
} \
(void)memset_s(&e, sizeof(e), 0, sizeof(e)); \
return e; \
} \
Element* VGetPointer##ClassName(const ClassName* obj, uint32_t index) \
{ \
if (NULL != obj) { \
if (index < obj->size(obj)) { \
if (GetParcelData(&obj->parcel)) { \
return ((Element*)(GetParcelData(&obj->parcel)) + index); \
} else { \
return NULL; \
} \
} \
} \
return NULL; \
} \
void VClear##ClassName(ClassName* obj) \
{ \
if (NULL != obj) { \
ClearParcel(&obj->parcel); \
} \
} \
ClassName Create##ClassName() \
{ \
ClassName obj; \
obj.pushBack = VPushBack##ClassName; \
obj.pushBackT = VPushBackT##ClassName; \
obj.popFront = VPopFront##ClassName; \
obj.clear = VClear##ClassName; \
obj.eraseElement = VErase##ClassName; \
obj.size = VSize##ClassName; \
obj.get = VGet##ClassName; \
obj.getp = VGetPointer##ClassName; \
obj.parcel = CreateParcel(0, sizeof(Element) * allocCount); \
return obj; \
} \
void Destroy##ClassName(ClassName* obj) \
{ \
if (NULL != obj) { \
DeleteParcel(&obj->parcel); \
} \
}
/* Use these two macros to create and destroy vector */
#define CREATE_HC_VECTOR(classname) Create##classname();
#define DESTROY_HC_VECTOR(classname, obj) Destroy##classname(obj);
#define FOR_EACH_HC_VECTOR(vec, index, iter) for (index = 0; index < (vec).size(&(vec)) && \
(iter = (vec).getp(&(vec), index)); ++index)
#define HC_VECTOR_PUSHBACK(obj, element) (obj)->pushBack((obj), (element))
#define HC_VECTOR_POPFRONT(obj, element) (obj)->popFront((obj), (element))
#define HC_VECTOR_POPELEMENT(obj, element, index) (obj)->eraseElement((obj), (element), (index))
#define HC_VECTOR_SIZE(obj) (obj)->size(obj)
#define HC_VECTOR_GET(obj, index) (obj)->get((obj), (index))
#define HC_VECTOR_GETP(_obj, _index) (_obj)->getp((_obj), (_index))
#endif

View File

@ -0,0 +1,81 @@
/*
* 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 HUKS_ADAPTER_H
#define HUKS_ADAPTER_H
#include "alg_defs.h"
#include "hc_error.h"
#include "hc_types.h"
#define BITS_PER_BYTE 8
#define CAL_ARRAY_SIZE(arr) ((sizeof(arr)) / (sizeof((arr)[0])))
#define CHECK_LEN_ZERO_RETURN_ERROR_CODE(len, paramTag) \
do { \
if ((len) == 0) { \
LOGE("%s is invalid length", (paramTag)); \
return HAL_ERR_INVALID_LEN; \
} \
} while (0)
#define CHECK_PTR_RETURN_ERROR_CODE(ptr, paramTag) \
do { \
if ((ptr) == NULL) { \
LOGE("%s is null ptr", (paramTag)); \
return HAL_ERR_NULL_PTR; \
} \
} while (0)
#define CHECK_LEN_LOWER_RETURN(len, min, paramTag) \
do { \
if ((len) < (min)) { \
LOGE("%s is invalid length.", (paramTag)); \
return HAL_ERR_INVALID_LEN; \
} \
} while (0)
#define CHECK_LEN_HIGHER_RETURN(len, max, paramTag) \
do { \
if ((len) > (max)) { \
LOGE("%s is invalid length.", (paramTag)); \
return HAL_ERR_INVALID_LEN; \
} \
} while (0)
#define CHECK_LEN_EQUAL_RETURN(len, value, paramTag) \
do { \
if ((len) != (value)) { \
LOGE("%s is invalid length.", (paramTag)); \
return HAL_ERR_INVALID_LEN; \
} \
} while (0)
struct KeyRoleInfo {
uint8_t userType;
uint8_t pairType;
uint8_t reserved1;
uint8_t reserved2;
};
union KeyRoleInfoUnion {
struct KeyRoleInfo roleInfoStruct;
uint32_t roleInfo;
};
const AlgLoader *GetRealLoaderInstance();
#endif

View File

@ -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.
*/
#ifndef JSON_UTILS_H
#define JSON_UTILS_H
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
typedef cJSON CJson;
/* Need to call FreeJson to free the returned pointer when it's no longer in use. */
CJson *CreateJsonFromString(const char *jsonStr);
/* Need to call FreeJson to free the returned pointer when it's no longer in use. */
CJson *CreateJson();
/* Need to call FreeJson to free the returned pointer when it's no longer in use. */
CJson *CreateJsonArray();
/* Need to call FreeJson to free the returned pointer when it's no longer in use. */
CJson *DuplicateJson(const CJson *jsonObj);
void FreeJson(CJson *jsonObj);
void DeleteItemFromJson(CJson *jsonObj, const char *key);
void DeleteAllItemExceptOne(CJson *jsonObj, const char *key);
void DeleteAllItem(CJson *jsonObj);
CJson *DetachItemFromJson(CJson *jsonObj, const char *key);
/* Need to call FreeJsonString to free the returned pointer when it's no longer in use. */
char *PackJsonToString(const CJson *jsonObj);
void FreeJsonString(char *jsonStr);
int GetItemNum(const CJson *jsonObj);
/*
* Can't release the returned pointer, otherwise, an exception may occur.
* It refers to the parent object(param--jsonObj)'s memory.
* It will be recycled along with jsonObj when jsonObj is released.
*/
const char *GetItemKey(const CJson *item);
/*
* Can't release the returned pointer, otherwise, an exception may occur.
* It refers to the parent object(param--jsonObj)'s memory.
* It will be recycled along with jsonObj when jsonObj is released.
*/
CJson *GetObjFromJson(const CJson *jsonObj, const char *key);
/*
* Can't release the returned pointer, otherwise, an exception may occur.
* It refers to the parent object(param--jsonObj)'s memory.
* It will be recycled along with jsonObj when jsonObj is released.
*/
CJson *GetItemFromArray(const CJson *jsonArr, int index);
/*
* Can't release the returned pointer, otherwise, an exception may occur.
* It refers to the parent object(param--jsonObj)'s memory.
* It will be recycled along with jsonObj when jsonObj is released.
*/
const char *GetStringFromJson(const CJson *jsonObj, const char *key);
/*
* The byte in jsonObj must be in the form of hex string.
* This function will convert the hex string to byte, and then put it in param--byte in the form of byte.
*/
int32_t GetByteFromJson(const CJson *jsonObj, const char *key, uint8_t *byte, uint32_t len);
int32_t GetIntFromJson(const CJson *jsonObj, const char *key, int *value);
int32_t GetInt64FromJson(const CJson *jsonObj, const char *key, int64_t *value);
int32_t GetBoolFromJson(const CJson *jsonObj, const char *key, bool *value);
char *GetStringValue(const CJson *item);
int32_t AddObjToJson(CJson *jsonObj, const char *key, const CJson *childObj);
int32_t AddObjToArray(CJson *jsonArr, CJson *item);
int32_t AddStringToJson(CJson *jsonObj, const char *key, const char *value);
int32_t AddStringToArray(CJson *jsonArr, const char *string);
/* The function will convert the byte to hex string, and then add it to object. */
int32_t AddByteToJson(CJson *jsonObj, const char *key, const uint8_t *byte, uint32_t len);
int32_t AddBoolToJson(CJson *jsonObj, const char *key, bool value);
int32_t AddIntToJson(CJson *jsonObj, const char *key, int value);
int32_t AddInt64StringToJson(CJson *jsonObj, const char *key, int64_t value);
int32_t AddStringArrayToJson(CJson *jsonObj, const char *key, const char * const *stringArray, uint32_t arrayLen);
void ClearSensitiveStringInJson(CJson *jsonObj, const char *key);
void ClearAndFreeJsonString(char *jsonStr);
#endif

View File

@ -0,0 +1,43 @@
/*
* 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 HC_DEV_INFO_H
#define HC_DEV_INFO_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define INPUT_UDID_LEN 65
#define MAX_INPUT_UDID_LEN 200
#define MAX_SESSION_COUNT 30
/*
* Get the unique device ID of the device(UDID).
* udid: It is used to store the UDID finally obtained.
* udidLen: The size of array to store UDID. Its value is the real udid size + 1 (including '\0').
* In liteos and linux, the udidLen must be 65.
* Return 0 if the UDID is successfully obtained, other returns an error code.
*/
int32_t HcGetUdid(uint8_t *udid, int32_t udidLen);
const char *GetStoragePath();
#ifdef __cplusplus
}
#endif
#endif

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.
*/
#ifndef HC_DEV_INFO_H
#define HC_DEV_INFO_H
#include <stdint.h>
#define INPUT_UDID_LEN 65
#define MAX_INPUT_UDID_LEN 200
#define MAX_SESSION_COUNT 20
/*
* Get the unique device ID of the device(UDID).
* udid: It is used to store the UDID finally obtained.
* udidLen: The size of array to store UDID. Its value is the real udid size + 1 (including '\0').
* In liteos and linux, the udidLen must be 65.
* Return 0 if the UDID is successfully obtained, other returns an error code.
*/
int32_t HcGetUdid(uint8_t *udid, int32_t udidLen);
const char *GetStoragePath();
#endif

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.
*/
#ifndef CRYPTO_HASH_TO_POINT_H
#define CRYPTO_HASH_TO_POINT_H
#include <openssl/bn.h>
#include "hks_type.h"
#ifdef __cplusplus
extern "C" {
#endif
int32_t OpensslHashToPoint(const struct HksBlob *hash, struct HksBlob *point);
#ifdef __cplusplus
}
#endif
#endif

45
hals/inc/linux/hc_condition.h Executable file
View File

@ -0,0 +1,45 @@
/*
* 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 HC_CONDITION_H
#define HC_CONDITION_H
#include "hc_mutex.h"
#include "hc_types.h"
#include "pthread.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct HcConditionT {
HcBool notified;
HcBool innerMutex;
HcBool waited;
HcMutex* mutex;
int (*wait)(struct HcConditionT*);
void (*notify)(struct HcConditionT*);
int (*waitWithoutLock)(struct HcConditionT*);
void (*notifyWithoutLock)(struct HcConditionT*);
pthread_cond_t cond;
} HcCondition;
int32_t InitHcCond(HcCondition* hcCond, HcMutex* mutex);
void DestroyHcCond(HcCondition* hcCond);
#ifdef __cplusplus
}
#endif
#endif

49
hals/inc/linux/hc_file.h Normal file
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 HC_FILE_H
#define HC_FILE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef union {
void *pfd;
int fd;
} FileHandle;
typedef enum FileIdEnumT {
FILE_ID_GROUP = 0,
FILE_ID_LAST,
} FileIdEnum;
#define MODE_FILE_READ 0
#define MODE_FILE_WRITE 1
// 0 indicates success
// -1 indicates fail
int HcFileOpen(int fileId, int mode, FileHandle *file);
int HcFileSize(FileHandle file);
int HcFileRead(FileHandle file, void *dst, int dstSize);
int HcFileWrite(FileHandle file, const void *src, int srcSize);
void HcFileClose(FileHandle file);
void HcFileRemove(int fileId);
void SetFilePath(FileIdEnum fileId, const char *path);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,33 @@
/*
* 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 HC_INIT_PROTECTION_H
#define HC_INIT_PROTECTION_H
#include <stdio.h>
typedef enum InitStatusEnum {
CONTINUE_INIT = 0,
FINISH_INIT,
CONTINUE_DESTROY,
FINISH_DESTROY,
} InitStatus;
int CheckInit();
int CheckDestroy();
void SetInitStatus();
void SetDeInitStatus();
#endif

43
hals/inc/linux/hc_log.h Normal file
View File

@ -0,0 +1,43 @@
/*
* 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 HC_LOG_H
#define HC_LOG_H
#ifdef HILOG_ENABLE
#include "hilog/log.h"
#define LOGD(fmt, ...) \
((void)HiLogPrint(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, "[DEVAUTH]", "%s: " fmt, __FUNCTION__, ##__VA_ARGS__))
#define LOGE(fmt, ...) \
((void)HiLogPrint(LOG_CORE, LOG_ERROR, LOG_DOMAIN, "[DEVAUTH]", "%s: " fmt, __FUNCTION__, ##__VA_ARGS__))
#define LOGI(fmt, ...) \
((void)HiLogPrint(LOG_CORE, LOG_INFO, LOG_DOMAIN, "[DEVAUTH]", "%s: " fmt, __FUNCTION__, ##__VA_ARGS__))
#define LOGW(fmt, ...) \
((void)HiLogPrint(LOG_CORE, LOG_WARN, LOG_DOMAIN, "[DEVAUTH]", "%s: " fmt, __FUNCTION__, ##__VA_ARGS__))
#else
#include <stdio.h>
#include <stdlib.h>
#define LOGD(fmt, ...) printf("[D][%s]" fmt "\n", __FUNCTION__, ##__VA_ARGS__)
#define LOGE(fmt, ...) printf("[E][%s]" fmt "\n", __FUNCTION__, ##__VA_ARGS__)
#define LOGI(fmt, ...) printf("[I][%s]" fmt "\n", __FUNCTION__, ##__VA_ARGS__)
#define LOGW(fmt, ...) printf("[W][%s]" fmt "\n", __FUNCTION__, ##__VA_ARGS__)
#endif
#endif

38
hals/inc/linux/hc_mutex.h Executable file
View File

@ -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 HC_MUTEX_H
#define HC_MUTEX_H
#include "pthread.h"
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct HcMutexT {
int (*lock)(struct HcMutexT* mutex);
void (*unlock)(struct HcMutexT* mutex);
pthread_mutex_t mutex;
} HcMutex;
int32_t InitHcMutex(HcMutex* mutex);
void DestroyHcMutex(HcMutex* mutex);
#ifdef __cplusplus
}
#endif
#endif

51
hals/inc/linux/hc_thread.h Executable file
View File

@ -0,0 +1,51 @@
/*
* 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 HC_THREAD_H
#define HC_THREAD_H
#include "pthread.h"
#include "hc_types.h"
#include "hc_string.h"
#include "hc_condition.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef int (*ThreadFunc)(void*);
typedef struct HcThreadT {
ThreadFunc threadFunc;
int (*start)(struct HcThreadT* thread);
void(*join)(struct HcThreadT* thread);
void (*wait)(struct HcThreadT* thread);
void (*notify)(struct HcThreadT* thread);
pthread_t thread;
size_t stackSize;
HcBool running;
HcString name;
HcCondition threadWaitObj;
HcMutex threadLock;
HcCondition bizWaitObj;
} HcThread;
int32_t InitThread(HcThread* thread, ThreadFunc func, size_t stackSize, const char* threadName);
void DestroyThread(HcThread* thread);
#ifdef __cplusplus
}
#endif
#endif

37
hals/inc/linux/hc_time.h Normal file
View File

@ -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 HC_TIME_H
#define HC_TIME_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Calculate in seconds */
#define TIME_OUT_VALUE 600
/* Return in seconds */
int64_t HcGetCurTime();
/* Return the interval seconds from startTime to current Time */
int64_t HcGetIntervalTime(int64_t startTime);
#ifdef __cplusplus
}
#endif
#endif

46
hals/inc/linux/hc_types.h Executable file
View File

@ -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 HC_TYPES_H
#define HC_TYPES_H
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "securec.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef uint32_t HcBool;
#define HC_TRUE 1
#define HC_FALSE 0
#ifndef NULL
#define NULL 0
#endif
void* HcMalloc(uint32_t size, char val);
void HcFree(void* addr);
void ReportMalloc();
uint32_t HcStrlen(const char *str);
#ifdef __cplusplus
}
#endif
#endif

34
hals/inc/liteos/hc_condition.h Executable file
View File

@ -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 HC_CONDITION_H
#define HC_CONDITION_H
#include "hc_mutex.h"
#include "hc_types.h"
#include <semaphore.h>
typedef struct HcConditionT {
int (*wait)(struct HcConditionT*);
void (*notify)(struct HcConditionT*);
int (*waitWithoutLock)(struct HcConditionT*);
void (*notifyWithoutLock)(struct HcConditionT*);
sem_t sem;
} HcCondition;
int32_t InitHcCond(HcCondition* hcCond, HcMutex* mutex);
void DestroyHcCond(HcCondition* hcCond);
#endif

41
hals/inc/liteos/hc_file.h Executable file
View File

@ -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 HC_FILE_H
#define HC_FILE_H
typedef union {
void* pfd;
int fd;
} FileHandle;
typedef enum FileIdEnumT {
FILE_ID_GROUP = 0,
FILE_ID_LAST,
} FileIdEnum;
#define MODE_FILE_READ 0
#define MODE_FILE_WRITE 1
/* 0 indicates success, -1 indicates fail */
int HcFileOpen(int fileId, int mode, FileHandle* file);
int HcFileSize(FileHandle file);
int HcFileRead(FileHandle file, void* dst, int dstSize);
int HcFileWrite(FileHandle file, const void* src, int srcSize);
void HcFileClose(FileHandle file);
void HcFileRemove(int fileId);
void SetFilePath(FileIdEnum fileId, const char *path);
#endif

View File

@ -0,0 +1,33 @@
/*
* 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 HC_INIT_PROTECTION_H
#define HC_INIT_PROTECTION_H
#include <stdio.h>
typedef enum InitStatusEnum {
CONTINUE_INIT = 0,
FINISH_INIT,
CONTINUE_DESTROY,
FINISH_DESTROY,
} InitStatus;
int CheckInit();
int CheckDestroy();
void SetInitStatus();
void SetDeInitStatus();
#endif

25
hals/inc/liteos/hc_log.h Executable file
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.
*/
#ifndef HC_LOG_H
#define HC_LOG_H
#include "log.h"
#define LOGD(fmt, arg...) HILOG_DEBUG(HILOG_MODULE_SCY, fmt, ##arg)
#define LOGI(fmt, arg...) HILOG_INFO(HILOG_MODULE_SCY, fmt, ##arg)
#define LOGE(fmt, arg...) HILOG_ERROR(HILOG_MODULE_SCY, fmt, ##arg)
#endif

31
hals/inc/liteos/hc_mutex.h Executable file
View File

@ -0,0 +1,31 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HC_MUTEX_H
#define HC_MUTEX_H
#include "pthread.h"
#include <stdint.h>
typedef struct HcMutexT {
int (*lock)(struct HcMutexT* mutex);
void (*unlock)(struct HcMutexT* mutex);
pthread_mutex_t mutex;
} HcMutex;
int32_t InitHcMutex(HcMutex* mutex);
void DestroyHcMutex(HcMutex* mutex);
#endif

44
hals/inc/liteos/hc_thread.h Executable file
View File

@ -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 HC_THREAD_H
#define HC_THREAD_H
#include "pthread.h"
#include "hc_types.h"
#include "hc_string.h"
#include "hc_condition.h"
typedef int (*ThreadFunc)(void*);
typedef struct HcThreadT {
ThreadFunc threadFunc;
int (*start)(struct HcThreadT* thread);
void(*join)(struct HcThreadT* thread);
void (*wait)(struct HcThreadT* thread);
void (*notify)(struct HcThreadT* thread);
pthread_t thread;
size_t stackSize;
HcBool running;
HcString name;
HcCondition threadWaitObj;
HcMutex threadLock;
HcCondition bizWaitObj;
} HcThread;
int32_t InitThread(HcThread* thread, ThreadFunc func, size_t stackSize, const char* threadName);
void DestroyThread(HcThread* thread);
#endif

30
hals/inc/liteos/hc_time.h Executable file
View File

@ -0,0 +1,30 @@
/*
* 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 HC_TIME_H
#define HC_TIME_H
#include <stdint.h>
/* Calculate in seconds */
#define TIME_OUT_VALUE 600
/* Return in seconds */
int64_t HcGetCurTime();
/* Return the interval seconds from startTime to current Time */
int64_t HcGetIntervalTime(int64_t startTime);
#endif

37
hals/inc/liteos/hc_types.h Executable file
View File

@ -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 HC_TYPES_H
#define HC_TYPES_H
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <securec.h>
typedef uint32_t HcBool;
#define HC_TRUE 1
#define HC_FALSE 0
#ifndef NULL
#define NULL 0
#endif
void *HcMalloc(uint32_t size, char val);
void HcFree(void* addr);
uint32_t HcStrlen(const char *str);
#endif

View File

@ -0,0 +1,22 @@
/*
* 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 "alg_loader.h"
#include "huks_adapter.h"
const AlgLoader *GetLoaderInstance()
{
return GetRealLoaderInstance();
}

94
hals/src/common/common_util.c Executable file
View File

@ -0,0 +1,94 @@
/*
* 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 "common_util.h"
#include <stdlib.h>
#include <string.h>
#include "hc_error.h"
#include "hc_log.h"
#define OUT_OF_HEX 16
#define NUMBER_9_IN_DECIMAL 9
static char HexToChar(uint8_t hex)
{
return (hex > NUMBER_9_IN_DECIMAL) ? (hex + 0x37) : (hex + 0x30); /* Convert to the corresponding character */
}
int32_t ByteToHexString(const uint8_t *byte, uint32_t byteLen, char *hexStr, uint32_t hexLen)
{
if (byte == NULL || hexStr == NULL) {
LOGE("Param is null ptr.");
return HAL_ERR_NULL_PTR;
}
/* The terminator('\0') needs 1 bit */
if (hexLen < byteLen * BYTE_TO_HEX_OPER_LENGTH + 1) {
LOGE("Invalid length");
return HAL_ERR_INVALID_LEN;
}
for (uint32_t i = 0; i < byteLen; i++) {
hexStr[i * BYTE_TO_HEX_OPER_LENGTH] = HexToChar((byte[i] & 0xF0) >> 4); /* 4: shift right for filling */
hexStr[i * BYTE_TO_HEX_OPER_LENGTH + 1] = HexToChar(byte[i] & 0x0F); /* get low four bits */
}
hexStr[byteLen * BYTE_TO_HEX_OPER_LENGTH] = '\0';
return HAL_SUCCESS;
}
static uint8_t CharToHex(char c)
{
if ((c >= 'A') && (c <= 'F')) {
return (c - 'A' + DEC);
} else if ((c >= 'a') && (c <= 'f')) {
return (c - 'a' + DEC);
} else if ((c >= '0') && (c <= '9')) {
return (c - '0');
} else {
return OUT_OF_HEX;
}
}
int32_t HexStringToByte(const char *hexStr, uint8_t *byte, uint32_t byteLen)
{
if (byte == NULL || hexStr == NULL) {
LOGE("Param is null ptr.");
return HAL_ERR_NULL_PTR;
}
uint32_t realHexLen = strlen(hexStr);
/* even number or not */
if (realHexLen % BYTE_TO_HEX_OPER_LENGTH != 0 || byteLen < realHexLen / BYTE_TO_HEX_OPER_LENGTH) {
return HAL_ERR_INVALID_LEN;
}
for (uint32_t i = 0; i < realHexLen / BYTE_TO_HEX_OPER_LENGTH; i++) {
uint8_t high = CharToHex(hexStr[i * BYTE_TO_HEX_OPER_LENGTH]);
uint8_t low = CharToHex(hexStr[i * BYTE_TO_HEX_OPER_LENGTH + 1]);
if (high == OUT_OF_HEX || low == OUT_OF_HEX) {
return HAL_ERR_INVALID_PARAM;
}
byte[i] = high << 4; /* 4: Set the high nibble */
byte[i] |= low; /* Set the low nibble */
}
return HAL_SUCCESS;
}
int64_t StringToInt64(const char *cp)
{
if (cp == NULL) {
return 0;
}
return strtoll(cp, NULL, DEC);
}

557
hals/src/common/hc_parcel.c Executable file
View File

@ -0,0 +1,557 @@
/*
* 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 "hc_parcel.h"
#include "hc_log.h"
#include "securec.h"
const int PARCEL_DEFAULT_INCREASE_STEP = 16;
const uint32_t PARCEL_UINT_MAX = 0xffffffffU;
HcParcel CreateParcel(uint32_t size, uint32_t allocUnit)
{
HcParcel parcel;
(void)memset_s(&parcel, sizeof(parcel), 0, sizeof(parcel));
parcel.allocUnit = allocUnit;
if (parcel.allocUnit == 0) {
parcel.allocUnit = PARCEL_DEFAULT_INCREASE_STEP;
}
if (size > 0) {
parcel.data = (char*)HcMalloc(size, 0);
if (parcel.data != NULL) {
parcel.length = size;
}
}
return parcel;
}
void DeleteParcel(HcParcel *parcel)
{
if (parcel == NULL) {
return;
}
if (parcel->data != NULL) {
HcFree(parcel->data);
parcel->data = 0;
}
parcel->length = 0;
parcel->beginPos = 0;
parcel->endPos = 0;
}
void ClearParcel(HcParcel *parcel)
{
if (parcel != NULL) {
parcel->beginPos = 0;
parcel->endPos = 0;
}
}
void ResetParcel(HcParcel *parcel, uint32_t size, uint32_t allocUnit)
{
if (parcel != NULL) {
DeleteParcel(parcel);
HcParcel newParcel = CreateParcel(size, allocUnit);
(void)memcpy_s(parcel, sizeof(HcParcel), &newParcel, sizeof(HcParcel));
}
}
uint32_t GetParcelDataSize(const HcParcel *parcel)
{
if (parcel == NULL) {
return 0;
}
if (parcel->endPos >= parcel->beginPos) {
return parcel->endPos - parcel->beginPos;
}
return 0;
}
const char *GetParcelData(const HcParcel *parcel)
{
if (parcel == NULL) {
return NULL;
}
return parcel->data + parcel->beginPos;
}
const char* GetParcelLastChar(const HcParcel *parcel)
{
if (parcel == NULL || GetParcelDataSize(parcel) == 0) {
return NULL;
}
return parcel->data + parcel->endPos - 1;
}
HcBool ParcelReadWithoutPopData(HcParcel *parcel, void *dst, uint32_t dataSize)
{
#ifdef IS_BIG_ENDIAN
HcBool ret = ParcelReadRevert(parcel, dst, dataSize);
#else
HcBool ret = ParcelRead(parcel, dst, dataSize);
#endif
if (ret == HC_TRUE) {
parcel->beginPos -= dataSize;
}
return ret;
}
HcBool ParcelRead(HcParcel *parcel, void *dst, uint32_t dataSize)
{
errno_t rc;
if (parcel == NULL || dst == NULL || dataSize == 0) {
LOGE("%s: Bad Parameters!", __func__);
return HC_FALSE;
}
if (parcel->beginPos > PARCEL_UINT_MAX - dataSize) {
LOGE("%s: Bad Parameters!", __func__);
return HC_FALSE;
}
if (parcel->beginPos + dataSize > parcel->endPos) {
LOGI("%s: parcel size < dataSize you want to read: parcel size %d while dataSize %u!",
__func__, GetParcelDataSize(parcel), dataSize);
return HC_FALSE;
}
rc = memmove_s(dst, dataSize, parcel->data + parcel->beginPos, dataSize);
if (rc != EOK) {
LOGE("%s: get data failed:%d.\n", __func__, rc);
return HC_FALSE;
}
parcel->beginPos += dataSize;
return HC_TRUE;
}
HcBool ParcelEraseBlock(HcParcel *parcel, uint32_t start, uint32_t dataSize, void *dst)
{
errno_t rc;
if (parcel == NULL || dst == NULL || dataSize == 0) {
LOGE("%s: Bad Parameters!", __func__);
return HC_FALSE;
}
if (start > PARCEL_UINT_MAX - dataSize) {
return HC_FALSE;
}
uint32_t parcelSizeOrg = GetParcelDataSize(parcel);
if (parcelSizeOrg < start + dataSize) {
return HC_FALSE;
}
char *beginCopy = parcel->data + parcel->beginPos + start;
uint32_t copySize = parcelSizeOrg - start - dataSize;
rc = memmove_s(dst, dataSize, beginCopy, dataSize);
if (rc != EOK) {
LOGE("%s: get data failed:%d.\n", __func__, rc);
return HC_FALSE;
}
if (copySize != 0) {
rc = memmove_s(beginCopy, copySize, beginCopy + dataSize, copySize);
if (rc != EOK) {
LOGE("%s: copy data failed:%d.\n", __func__, rc);
return HC_FALSE;
}
}
parcel->endPos -= dataSize;
return HC_TRUE;
}
HcBool ParcelReadRevert(HcParcel *parcel, void *dst, uint32_t dataSize)
{
if (ParcelRead(parcel, dst, dataSize)) {
DataRevert(dst, dataSize);
return HC_TRUE;
} else {
return HC_FALSE;
}
}
HcBool ParcelWriteRevert(HcParcel *parcel, const void *src, uint32_t dataSize)
{
errno_t rc;
void *srcCopy = HcMalloc(dataSize, 0);
if (srcCopy == NULL) {
return HC_FALSE;
}
rc = memmove_s(srcCopy, dataSize, src, dataSize);
if (rc != EOK) {
HcFree(srcCopy);
return HC_FALSE;
}
DataRevert(srcCopy, dataSize);
HcBool ret = ParcelWrite(parcel, srcCopy, dataSize);
HcFree(srcCopy);
return ret;
}
HcBool ParcelReadInt32(HcParcel *parcel, int *dst)
{
return ParcelRead(parcel, dst, sizeof(int));
}
HcBool ParcelReadUint32(HcParcel *parcel, uint32_t *dst)
{
return ParcelRead(parcel, dst, sizeof(uint32_t));
}
HcBool ParcelReadInt16(HcParcel *parcel, short *dst)
{
return ParcelRead(parcel, dst, sizeof(short));
}
HcBool ParcelReadUint16(HcParcel *parcel, uint16_t *dst)
{
return ParcelRead(parcel, dst, sizeof(uint16_t));
}
HcBool ParcelReadInt8(HcParcel *parcel, char *dst)
{
return ParcelRead(parcel, dst, sizeof(char));
}
HcBool ParcelReadUint8(HcParcel *parcel, uint8_t *dst)
{
return ParcelRead(parcel, dst, sizeof(uint8_t));
}
HcBool ParcelReadUint64(HcParcel *parcel, uint64_t *dst)
{
return ParcelRead(parcel, dst, sizeof(uint64_t));
}
HcBool ParcelReadInt64(HcParcel *parcel, int64_t *dst)
{
return ParcelRead(parcel, dst, sizeof(int64_t));
}
static HcBool ParcelRealloc(HcParcel *parcel, uint32_t size)
{
if (parcel->length >= size) {
LOGE("%s: ParcelRealloc failed, length is too big", __func__);
return HC_FALSE;
}
char *newData = (char*)HcMalloc(size, 0);
if (newData == NULL) {
LOGE("%s: ParcelRealloc failed, out of memory", __func__);
return HC_FALSE;
}
if (memcpy_s(newData, size, parcel->data, parcel->length) != EOK) {
HcFree(newData);
return HC_FALSE;
}
HcFree(parcel->data);
parcel->data = newData;
parcel->length = size;
return HC_TRUE;
}
static HcBool ParcelIncrease(HcParcel *parcel, uint32_t size)
{
if (parcel == NULL || size == 0) {
LOGE("%s: ParcelIncrease, invalid parameter", __func__);
return HC_FALSE;
}
if (parcel->data == NULL) {
if (parcel->length != 0) {
LOGE("%s: ParcelIncrease faile, invalid length", __func__);
return HC_FALSE;
}
(*parcel) = CreateParcel(size, parcel->allocUnit);
if (parcel->data == NULL) {
LOGE("%s: ParcelIncrease failed, create parcel failed", __func__);
return HC_FALSE;
} else {
return HC_TRUE;
}
} else {
return ParcelRealloc(parcel, size);
}
}
static void ParcelRecycle(HcParcel *parcel)
{
if (parcel == NULL) {
return;
}
if (parcel->data == NULL || parcel->beginPos < parcel->allocUnit) {
return;
}
uint32_t contentSize = parcel->endPos - parcel->beginPos;
if (contentSize > 0) {
if (memmove_s(parcel->data, parcel->endPos - parcel->beginPos,
parcel->data + parcel->beginPos, parcel->endPos - parcel->beginPos) != EOK) {
LOGE("Move parcel's data failed.");
}
}
parcel->beginPos = 0;
parcel->endPos = contentSize;
}
static uint32_t GetParcelIncreaseSize(HcParcel *parcel, uint32_t newSize)
{
if (parcel == NULL || parcel->allocUnit == 0) {
return 0;
}
if (newSize % parcel->allocUnit) {
return (newSize / parcel->allocUnit + 1) * parcel->allocUnit;
} else {
return (newSize / parcel->allocUnit) * parcel->allocUnit;
}
}
HcBool ParcelWrite(HcParcel *parcel, const void *src, uint32_t dataSize)
{
errno_t rc;
if (parcel == NULL || src == NULL || dataSize == 0) {
LOGE("%s: Bad Parameters!", __func__);
return HC_FALSE;
}
if (parcel->endPos > PARCEL_UINT_MAX - dataSize) {
LOGE("%s: Bad Parameters overflow!", __func__);
return HC_FALSE;
}
if (parcel->endPos + dataSize > parcel->length) {
ParcelRecycle(parcel);
if (parcel->endPos + dataSize > parcel->length) {
uint32_t newSize = GetParcelIncreaseSize(parcel, parcel->endPos + dataSize);
if (!ParcelIncrease(parcel, newSize)) {
LOGE("%s: ParcelIncrease failed", __func__);
return HC_FALSE;
}
}
}
rc = memmove_s(parcel->data + parcel->endPos, dataSize, src, dataSize);
if (rc != EOK) {
LOGE("%s: get data failed:%d.\n", __func__, rc);
return HC_FALSE;
}
parcel->endPos += dataSize;
return HC_TRUE;
}
HcBool ParcelWriteInt32(HcParcel *parcel, int src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelWriteUint32(HcParcel *parcel, uint32_t src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelWriteInt16(HcParcel *parcel, short src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelWriteUint16(HcParcel *parcel, uint16_t src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelWriteInt8(HcParcel *parcel, char src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelWriteUint8(HcParcel *parcel, uint8_t src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelWriteUint64(HcParcel *parcel, uint64_t src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelWriteInt64(HcParcel *parcel, int64_t src)
{
return ParcelWrite(parcel, &src, sizeof(src));
}
HcBool ParcelReadParcel(HcParcel *src, HcParcel *dst, uint32_t size, HcBool copy)
{
if (src == NULL || dst == NULL) {
return HC_FALSE;
}
if (GetParcelDataSize(src) < size) {
return HC_FALSE;
}
if (!ParcelWrite(dst, (void*)GetParcelData(src), size)) {
return HC_FALSE;
}
if (!copy) {
src->beginPos += size;
}
return HC_TRUE;
}
HcBool ParcelCopy(HcParcel *src, HcParcel *dst)
{
if (src == NULL || dst == NULL) {
return HC_FALSE;
}
if (GetParcelDataSize(src) == 0) {
return HC_TRUE;
}
return ParcelReadParcel(src, dst, GetParcelDataSize(src), HC_TRUE);
}
void DataRevert(void *data, uint32_t length)
{
if (data != NULL) {
uint8_t *pc = (uint8_t *) data;
uint32_t i = 0;
for (; i < length / 2; ++i) { /* half of the length */
/* swap p[i] and p[length-i-1] */
pc[i] ^= pc[length - i - 1];
pc[length - i - 1] ^= pc[i];
pc[i] ^= pc[length - i - 1];
}
}
}
HcBool ParcelReadInt32Revert(HcParcel *parcel, int32_t *dst)
{
HcBool ret = ParcelRead(parcel, dst, sizeof(int));
if (ret) {
DataRevert(dst, sizeof(int));
}
return ret;
}
HcBool ParcelReadUint32Revert(HcParcel *parcel, uint32_t *dst)
{
HcBool ret = ParcelRead(parcel, dst, sizeof(uint32_t));
if (ret) {
DataRevert(dst, sizeof(uint32_t));
}
return ret;
}
HcBool ParcelReadInt16Revert(HcParcel *parcel, short *dst)
{
HcBool ret = ParcelRead(parcel, dst, sizeof(short));
if (ret) {
DataRevert(dst, sizeof(short));
}
return ret;
}
HcBool ParcelReadUint16Revert(HcParcel *parcel, uint16_t *dst)
{
if (parcel == NULL || dst == NULL) {
return HC_FALSE;
}
HcBool ret = ParcelRead(parcel, dst, sizeof(uint16_t));
if (ret) {
DataRevert(dst, sizeof(uint16_t));
}
return ret;
}
HcBool ParcelReadInt8Revert(HcParcel *parcel, char *dst)
{
return ParcelRead(parcel, dst, sizeof(char));
}
HcBool ParcelReadUint8Revert(HcParcel *parcel, uint8_t *dst)
{
return ParcelRead(parcel, dst, sizeof(uint8_t));
}
HcBool ParcelReadUint64Revert(HcParcel *parcel, uint64_t *dst)
{
HcBool ret = ParcelRead(parcel, dst, sizeof(uint64_t));
if (ret) {
DataRevert(dst, sizeof(uint64_t));
}
return ret;
}
HcBool ParcelReadInt64Revert(HcParcel *parcel, int64_t *dst)
{
HcBool ret = ParcelRead(parcel, dst, sizeof(int64_t));
if (ret) {
DataRevert(dst, sizeof(int64_t));
}
return ret;
}
HcBool ParcelWriteInt32Revert(HcParcel *parcel, int src)
{
DataRevert(&src, sizeof(src));
return ParcelWriteInt32(parcel, src);
}
HcBool ParcelWriteUint32Revert(HcParcel *parcel, uint32_t src)
{
DataRevert(&src, sizeof(src));
return ParcelWriteUint32(parcel, src);
}
HcBool ParcelWriteInt16Revert(HcParcel *parcel, short src)
{
DataRevert(&src, sizeof(src));
return ParcelWriteInt16(parcel, src);
}
HcBool ParcelWriteUint16Revert(HcParcel *parcel, uint16_t src)
{
DataRevert(&src, sizeof(src));
return ParcelWriteUint16(parcel, src);
}
HcBool ParcelWriteInt8Revert(HcParcel *parcel, char src)
{
return ParcelWriteInt8(parcel, src);
}
HcBool ParcelWriteUint8Revert(HcParcel *parcel, uint8_t src)
{
return ParcelWriteUint8(parcel, src);
}
HcBool ParcelWriteUint64Revert(HcParcel *parcel, uint64_t src)
{
DataRevert(&src, sizeof(src));
return ParcelWriteUint64(parcel, src);
}
HcBool ParcelWriteInt64Revert(HcParcel *parcel, int64_t src)
{
DataRevert(&src, sizeof(src));
return ParcelWriteInt64(parcel, src);
}
HcBool ParcelPopBack(HcParcel *parcel, uint32_t size)
{
if (parcel != NULL && size > 0 && GetParcelDataSize(parcel) >= size) {
parcel->endPos -= size;
return HC_TRUE;
}
return HC_FALSE;
}
HcBool ParcelPopFront(HcParcel *parcel, uint32_t size)
{
if ((parcel != NULL) && (size > 0) && (GetParcelDataSize(parcel) >= size)) {
parcel->beginPos += size;
return HC_TRUE;
}
return HC_FALSE;
}

175
hals/src/common/hc_string.c Normal file
View File

@ -0,0 +1,175 @@
/*
* 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 "hc_string.h"
const uint32_t STRING_ALLOC_SIZE = 10;
const uint32_t STRING_END_CHAR_LENGTH = 1;
const char STRING_END_CHAR = '\0';
/*
* Append a HcString
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: append string.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringAppend(HcString *self, HcString str)
{
uint32_t length = GetParcelDataSize(&str.parcel);
if (self != NULL && length > 0) {
// remove '\0'
ParcelPopBack(&self->parcel, STRING_END_CHAR_LENGTH);
// append string(include '\0')
return StringAppendPointer(self, GetParcelData(&str.parcel));
}
return HC_FALSE;
}
/*
* Append string pointer
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: string pointer.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringAppendPointer(HcString *self, const char *str)
{
if (self != NULL && str != NULL) {
// remove '\0'
ParcelPopBack(&self->parcel, STRING_END_CHAR_LENGTH);
// append string (include '\0')
return ParcelWrite(&self->parcel, (void *)str, strlen(str) + 1);
}
return HC_FALSE;
}
/*
* Append a char
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: char.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringAppendChar(HcString *self, char c)
{
if (self != NULL && c != STRING_END_CHAR) {
// remove '\0'
ParcelPopBack(&self->parcel, STRING_END_CHAR_LENGTH);
if (ParcelWriteInt8(&self->parcel, c)) {
return ParcelWriteInt8(&self->parcel, (uint32_t)STRING_END_CHAR);
}
}
return HC_FALSE;
}
/*
* Assign a value to the HcString
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: assign value of ta_sting.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringSet(HcString *self, HcString str)
{
if (self != NULL) {
DeleteParcel(&self->parcel);
return StringAppend(self, str);
}
return HC_FALSE;
}
/*
* Assign a value to the HcString
* Notice: It will add '\0' automatically.
* @param self: self pointer.
* @param str: assign value of string pointer.
* @return HC_TRUE (ok), HC_FALSE (error)
*/
HcBool StringSetPointer(HcString *self, const char *str)
{
if (self != NULL) {
DeleteParcel(&self->parcel);
return StringAppendPointer(self, str);
}
return HC_FALSE;
}
/*
* Get the string pointer data
* @param self: self pointer.
* @return the pointer data of the string
*/
const char* StringGet(const HcString *self)
{
if (self == NULL) {
return NULL;
}
return GetParcelData(&self->parcel);
}
/*
* Get the length of the string
* @param self: self pointer.
* @return the length of the string
*/
uint32_t StringLength(const HcString *self)
{
if (self == NULL) {
return 0;
} else {
uint32_t length = GetParcelDataSize(&self->parcel);
if (length > 0) {
return length - STRING_END_CHAR_LENGTH;
} else {
return 0;
}
}
}
/*
* Create a string.
* Notice: You should delete_string when you don't need the string anymore.
* @return return the created string.
*/
HcString CreateString()
{
HcString str;
str.parcel = CreateParcel(0, STRING_ALLOC_SIZE);
ParcelWriteInt8(&str.parcel, STRING_END_CHAR);
return str;
}
/*
* Delete a string. In fact it will not destroy the string,
* but only free the allocate memory of the string and reset the member's value
* of the string.
* You can continue to use the string if you want.
* Notice: You should delete the string when you don't need it any more to avoid memory leak.
* @param str: The string you want to delete.
*/
void DeleteString(HcString *str)
{
if (str != NULL) {
DeleteParcel(&str->parcel);
}
}

149
hals/src/common/hc_task_thread.c Executable file
View File

@ -0,0 +1,149 @@
/*
* 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 "hc_task_thread.h"
#include "hc_error.h"
#include "hc_log.h"
#define TASK_ALLOC_UINT 5
IMPLEMENT_HC_VECTOR(TaskVec, HcTaskWrap, TASK_ALLOC_UINT)
static HcTaskBase* PopTask(HcTaskThread* thread)
{
if (thread == NULL) {
return NULL;
}
thread->queueLock.lock(&thread->queueLock);
HcTaskWrap task;
HcBool ret = thread->tasks.popFront(&thread->tasks, &task);
thread->queueLock.unlock(&thread->queueLock);
if (ret) {
return task.task;
}
return NULL;
}
static void PushTask(struct HcTaskThreadT* thread, HcTaskBase* task)
{
if (thread == NULL || task == NULL) {
return;
}
thread->queueLock.lock(&thread->queueLock);
HcTaskWrap taskWarp;
taskWarp.task = task;
thread->tasks.pushBack(&thread->tasks, &taskWarp);
thread->thread.notify(&thread->thread);
thread->queueLock.unlock(&thread->queueLock);
}
static void Clear(struct HcTaskThreadT* thread)
{
thread->queueLock.lock(&thread->queueLock);
HcTaskWrap *taskWarp = NULL;
uint32_t index;
FOR_EACH_HC_VECTOR(thread->tasks, index, taskWarp) {
if (taskWarp->task->destroy) {
taskWarp->task->destroy(taskWarp->task);
}
HcFree(taskWarp->task);
}
thread->tasks.clear(&thread->tasks);
thread->queueLock.unlock(&thread->queueLock);
}
static void StopAndClear(struct HcTaskThreadT* thread)
{
if (thread == NULL) {
return;
}
thread->clear(thread);
thread->quit = HC_TRUE;
thread->thread.notify(&thread->thread);
thread->thread.join(&thread->thread);
}
static int32_t StartTaskThread(struct HcTaskThreadT* thread)
{
if (thread == NULL) {
return HAL_ERR_BAD_ALLOC;
}
thread->quit = HC_FALSE;
int32_t res = thread->thread.start(&thread->thread);
if (res != HAL_SUCCESS) {
LOGE("Start thread failed, res:%d", res);
}
return res;
}
static int TaskThreadLoop(void* args)
{
HcTaskThread* thread = (HcTaskThread*)args;
if (thread == NULL) {
return -1;
}
while (1) {
if (thread->quit) {
break;
}
HcTaskBase* task = PopTask(thread);
if (task != NULL) {
if (task->doAction) {
task->doAction(task);
}
if (task->destroy) {
task->destroy(task);
}
HcFree(task);
} else {
thread->thread.wait(&thread->thread);
}
}
return 0;
}
int32_t InitHcTaskThread(HcTaskThread* thread, size_t stackSize, const char* threadName)
{
if (thread == NULL) {
return -1;
}
thread->pushTask = PushTask;
thread->startThread = StartTaskThread;
thread->clear = Clear;
thread->stopAndClear = StopAndClear;
int32_t res = InitThread(&thread->thread, TaskThreadLoop, stackSize, threadName);
if (res != 0) {
return res;
}
res = InitHcMutex(&thread->queueLock);
if (res != 0) {
DestroyThread(&thread->thread);
return res;
}
thread->tasks = CREATE_HC_VECTOR(TaskVec);
return 0;
}
void DestroyHcTaskThread(HcTaskThread* thread)
{
DESTROY_HC_VECTOR(TaskVec, &thread->tasks);
DestroyHcMutex(&thread->queueLock);
DestroyThread(&thread->thread);
}

476
hals/src/common/hc_tlv_parser.c Executable file
View File

@ -0,0 +1,476 @@
/*
* 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 "hc_tlv_parser.h"
#include <stddef.h>
#include "hc_log.h"
#define MAX_TLV_LENGTH (32 * 1024)
HcBool ParseTlvHead(TlvBase *tlv, HcParcel *parcel)
{
#ifdef IS_BIG_ENDIAN
if (!ParcelReadUint16Revert(parcel, &tlv->tag)) {
LOGE(" ParseTlvHead failed, read tag failed!!!");
return HC_FALSE;
}
#else
if (!ParcelReadUint16(parcel, &tlv->tag)) {
LOGE(" ParseTlvHead failed, read tag failed!!!");
return HC_FALSE;
}
#endif
if (tlv->tag != tlv->checkTag) {
LOGE(" ParseTlvHead failed, tag is error, expect:%x, get:%x!!!", tlv->checkTag, tlv->tag);
return HC_FALSE;
}
#ifdef IS_BIG_ENDIAN
if (!ParcelReadUint16Revert(parcel, &tlv->length)) {
LOGE(" ParseTlvHead failed, read length failed!!!");
return HC_FALSE;
}
#else
if (!ParcelReadUint16(parcel, &tlv->length)) {
LOGE(" ParseTlvHead failed, read length failed!!!");
return HC_FALSE;
}
#endif
if (tlv->length > MAX_TLV_LENGTH) {
return HC_FALSE;
}
return HC_TRUE;
}
int32_t ParseTlvNode(TlvBase *tlv, HcParcel *parcel, HcBool strict)
{
if (!ParseTlvHead(tlv, parcel)) {
return TLV_FAIL;
} else {
if (GetParcelDataSize(parcel) < tlv->length) {
LOGE("parcel buffer too short tlv->tag is:%x, parcel size is %x and tlv->length is %x",
tlv->tag, GetParcelDataSize(parcel), tlv->length);
return TLV_FAIL;
}
int ret = tlv->parse(tlv, parcel, strict);
if (ret < 0 || ret > MAX_TLV_LENGTH) {
return TLV_FAIL;
} else {
return ret + sizeof(tlv->tag) + sizeof(tlv->length);
}
}
}
int32_t GetlenTlvNode(TlvBase *tlv)
{
int32_t bodyLen = tlv->getlen(tlv);
if (bodyLen < 0 || bodyLen > MAX_TLV_LENGTH) {
return TLV_FAIL;
} else {
tlv->length = bodyLen + sizeof(tlv->tag) + sizeof(tlv->length);
return tlv->length;
}
}
void DeinitTlvNode(TlvBase *tlv)
{
if (tlv != NULL) {
tlv->deinit(tlv);
}
}
int32_t EncodeTlvNode(TlvBase *tlv, HcParcel *parcel, HcBool isRoot)
{
int32_t bodyLen = tlv->getlen(tlv);
if (bodyLen < 0 || bodyLen > MAX_TLV_LENGTH) {
return TLV_FAIL;
} else if (bodyLen == 0) {
if (isRoot) {
ResetParcel(parcel, sizeof(uint16_t) + sizeof(uint16_t), 0);
}
#ifdef IS_BIG_ENDIAN
ParcelWriteUint16Revert(parcel, tlv->checkTag);
ParcelWriteUint16Revert(parcel, bodyLen);
#else
ParcelWriteUint16(parcel, tlv->checkTag);
ParcelWriteUint16(parcel, bodyLen);
#endif
return sizeof(tlv->tag) + sizeof(tlv->length);
} else { // has value
if (isRoot) {
ResetParcel(parcel, sizeof(uint16_t) + sizeof(uint16_t) + bodyLen, 0);
}
int32_t encodeLen;
tlv->length = (uint16_t)bodyLen;
#ifdef IS_BIG_ENDIAN
ParcelWriteUint16Revert(parcel, tlv->checkTag);
ParcelWriteUint16Revert(parcel, tlv->length);
#else
ParcelWriteUint16(parcel, tlv->checkTag);
ParcelWriteUint16(parcel, tlv->length);
#endif
encodeLen = tlv->encode(tlv, parcel);
if (encodeLen < 0 || encodeLen > MAX_TLV_LENGTH) {
return TLV_FAIL;
} else {
return encodeLen + sizeof(tlv->tag) + sizeof(tlv->length);
}
}
}
TlvBase* GetEmptyStructNode(TlvBase *tlv, unsigned short tag)
{
if (tlv == NULL) {
return NULL;
}
unsigned int index;
unsigned int memberCount = *(unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offsetCount));
unsigned int *offset = (unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offset));
for (index = 0; index < memberCount; ++index) {
TlvBase *tlvChild = (TlvBase *)(((char *)tlv) + offset[index]);
if (tlvChild->checkTag == tag && tlvChild->hasValue == 0) {
return tlvChild;
}
}
return NULL;
}
int32_t CheckStructNodeAllHasValue(TlvBase *tlv)
{
if (tlv == NULL) {
return 0;
} else {
unsigned int index;
unsigned int memberCount = *(unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offsetCount));
unsigned int *offset = (unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offset));
for (index = 0; index < memberCount; ++index) {
TlvBase *tlvChild = (TlvBase *)(((char *)tlv) + offset[index]);
if (tlvChild->hasValue == 0) {
return -1;
}
}
}
return 0;
}
void SetStructNodeHasValue(TlvBase *tlv)
{
if (tlv != NULL) {
tlv->hasValue = 1;
}
}
int32_t ParseAndSkipTlvUnknownNode(HcParcel *parcel)
{
// read tag
uint16_t tag = 0;
if (!ParcelReadUint16(parcel, &tag)) {
return TLV_FAIL;
}
// read length
uint16_t length = 0;
if (!ParcelReadUint16(parcel, &length)) {
return TLV_FAIL;
}
// pop data
if (!ParcelPopFront(parcel, length)) {
return TLV_FAIL;
}
return sizeof(tag) + sizeof(length) + length;
}
int32_t ParseTlvStruct(TlvBase *tlv, HcParcel *parcel, HcBool strict)
{
uint32_t childTotalLength = 0;
do {
uint16_t tag = 0;
if (!ParcelReadWithoutPopData(parcel, &tag, sizeof(tag))) {
return TLV_FAIL;
}
TlvBase *tlvChild = GetEmptyStructNode(tlv, tag);
if (tlvChild == NULL) {
if (strict) {
LOGE("ParseTlvStruct error, unknown tag in strict mode:%x", tlv->tag);
return TLV_FAIL;
}
int32_t unknownChildLength = ParseAndSkipTlvUnknownNode(parcel);
if (unknownChildLength < 0 || unknownChildLength > MAX_TLV_LENGTH) {
return TLV_FAIL;
}
childTotalLength += unknownChildLength;
if (childTotalLength > MAX_TLV_LENGTH) {
return TLV_FAIL;
}
} else {
int32_t childLength = ParseTlvNode(tlvChild, parcel, strict);
if (childLength < 0 || childLength > MAX_TLV_LENGTH) {
LOGE("ParseTlvStruct parse member child length error:%x", tag);
return TLV_FAIL;
}
SetStructNodeHasValue(tlvChild);
childTotalLength += childLength;
if (childTotalLength > MAX_TLV_LENGTH) {
return TLV_FAIL;
}
}
} while (childTotalLength < tlv->length);
if (childTotalLength > tlv->length) {
LOGE("ParseTlvStruct failed, because child length is too big");
return TLV_FAIL;
}
if (strict && CheckStructNodeAllHasValue(tlv) != 0) {
LOGE("ParseTlvStruct error, the tag's child value is empty, tag:%x", tlv->tag);
return TLV_FAIL;
}
return childTotalLength;
}
int32_t EncodeTlvStruct(TlvBase *tlv, HcParcel *parcel)
{
unsigned int index;
unsigned int memberCount = *(unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offsetCount));
unsigned int *offset = (unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offset));
uint32_t totalLen = 0;
for (index = 0; index < memberCount; ++index) {
TlvBase *tlvChild = (TlvBase *)(((char *)tlv) + offset[index]);
int32_t childLen = EncodeTlvNode(tlvChild, parcel, HC_FALSE);
if (childLen < 0 || childLen > MAX_TLV_LENGTH) {
return TLV_FAIL;
} else {
totalLen += childLen;
}
if (totalLen > MAX_TLV_LENGTH) {
return TLV_FAIL;
}
}
return totalLen;
}
int32_t GetLenTlvStruct(TlvBase *tlv)
{
unsigned int index;
unsigned int memberCount = *(unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offsetCount));
unsigned int *offset = (unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offset));
uint32_t childTotalLength = 0;
for (index = 0; index < memberCount; ++index) {
TlvBase *tlvChild = (TlvBase *)(((char *)tlv) + offset[index]);
int32_t childLength = GetlenTlvNode(tlvChild);
if (childLength <= 0 || childLength > MAX_TLV_LENGTH) {
return TLV_FAIL;
} else {
childTotalLength += childLength;
}
if (childTotalLength > MAX_TLV_LENGTH) {
return TLV_FAIL;
}
}
return childTotalLength;
}
void DeinitTlvStruct(TlvBase *tlv)
{
unsigned int index;
unsigned int memberCount = *(unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offsetCount));
unsigned int *offset = (unsigned int *)((char *)tlv + offsetof(TlvOffsetExample, offset));
for (index = 0; index < memberCount; ++index) {
TlvBase *tlvChild = (TlvBase *)(((char *)tlv) + offset[index]);
DeinitTlvNode(tlvChild);
}
}
HcBool DecodeTlvMessage(TlvBase *msg, HcParcel *parcel, HcBool strict)
{
if (msg == NULL || parcel == NULL) {
return HC_FALSE;
} else {
int32_t msgLen = ParseTlvNode(msg, parcel, strict);
if (msgLen > MAX_TLV_LENGTH) {
return HC_FALSE;
}
if ((int32_t)(msg->length + sizeof(msg->length) + sizeof(msg->tag)) != msgLen) {
return HC_FALSE;
}
if (GetParcelDataSize(parcel) != 0) {
return HC_FALSE;
}
}
return HC_TRUE;
}
HcBool EncodeTlvMessage(TlvBase *msg, HcParcel *parcel)
{
if (msg == NULL || parcel == NULL) {
return HC_FALSE;
} else {
if (EncodeTlvNode(msg, parcel, HC_TRUE) < 0) {
return HC_FALSE;
}
}
return HC_TRUE;
}
int32_t ParseTlvBuffer(TlvBase *tlv, HcParcel *parcel, HcBool strict)
{
(void)strict;
TlvBuffer *realTlv = (TlvBuffer *)(tlv);
if (tlv->length == 0 || ParcelReadParcel(parcel, &realTlv->data, tlv->length, HC_FALSE)) {
return tlv->length;
} else {
LOGE("ParseTlvBuffer error");
return TLV_FAIL;
}
}
int32_t GetlenTlvBuffer(TlvBase *tlv)
{
TlvBuffer *realTlv = (TlvBuffer *)(tlv);
return (int32_t)GetParcelDataSize(&realTlv->data);
}
int32_t EncodeTlvBuffer(TlvBase *tlv, HcParcel *parcel)
{
TlvBuffer *realTlv = (TlvBuffer *)(tlv);
int32_t len = GetlenTlvBuffer(tlv);
if (len <= 0 || len > MAX_TLV_LENGTH) {
return TLV_FAIL;
}
if (ParcelReadParcel(&realTlv->data, parcel, len, HC_TRUE)) {
return len;
} else {
return TLV_FAIL;
}
}
void DeinitTlvBuffer(TlvBase *tlv)
{
DeleteParcel(&((TlvBuffer *)tlv)->data);
}
void InitTlvBuffer(TlvBuffer *tlv, unsigned short checkTag)
{
(void)memset_s(&tlv->base, sizeof(tlv->base), 0, sizeof(tlv->base));
tlv->base.parse = ParseTlvBuffer;
tlv->base.getlen = GetlenTlvBuffer;
tlv->base.encode = EncodeTlvBuffer;
tlv->base.deinit = DeinitTlvBuffer;
tlv->base.checkTag = checkTag;
tlv->data = CreateParcel(PARCEL_DEFAULT_LENGTH, PARCEL_DEFAULT_ALLOC_UNIT);
}
int32_t ParseTlvString(TlvBase *tlv, HcParcel *parcel, HcBool strict)
{
(void)strict;
TlvString *realTlv = (TlvString *)(tlv);
ClearParcel(&realTlv->data.parcel);
if (tlv->length == 0 || ParcelReadParcel(parcel, &realTlv->data.parcel, tlv->length, HC_FALSE)) {
return tlv->length;
} else {
LOGE("ParseTlvBuffer error");
return TLV_FAIL;
}
}
int32_t GetlenTlvString(TlvBase *tlv)
{
TlvString *realTlv = (TlvString *)(tlv);
return (int32_t)GetParcelDataSize(&realTlv->data.parcel);
}
int32_t EncodeTlvString(TlvBase *tlv, HcParcel *parcel)
{
TlvString *realTlv = (TlvString *)(tlv);
int32_t len = GetlenTlvString(tlv);
if (len <= 0 || len > MAX_TLV_LENGTH) {
return TLV_FAIL;
}
if (ParcelReadParcel(&realTlv->data.parcel, parcel, len, HC_TRUE)) {
return len;
} else {
return TLV_FAIL;
}
}
void DeinitTlvString(TlvBase *tlv)
{
DeleteString(&((TlvString*)tlv)->data);
}
void InitTlvString(TlvString *tlv, unsigned short checkTag)
{
(void)memset_s(&tlv->base, sizeof(tlv->base), 0, sizeof(tlv->base));
tlv->base.parse = ParseTlvString;
tlv->base.getlen = GetlenTlvString;
tlv->base.encode = EncodeTlvString;
tlv->base.deinit = DeinitTlvString;
tlv->base.checkTag = checkTag;
tlv->data = CreateString();
}
unsigned short GetTag(unsigned short checkTag, unsigned short defaultTag)
{
if (checkTag == USE_DEFAULT_TAG) {
return defaultTag;
} else {
return checkTag;
}
}
void DeinitTlvFixMember(TlvBase* tlv)
{
(void)tlv;
return;
}
#ifdef IS_BIG_ENDIAN
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt64, NEED_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt32, NEED_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt16, NEED_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt8, NEED_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint64, NEED_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint32, NEED_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint16, NEED_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint8, NEED_REVERT)
#else
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt64, NO_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt32, NO_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt16, NO_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvInt8, NO_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint64, NO_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint32, NO_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint16, NO_REVERT)
DEFINE_TLV_FIX_LENGTH_TYPE(TlvUint8, NO_REVERT)
#endif

551
hals/src/common/json_utils.c Executable file
View File

@ -0,0 +1,551 @@
/*
* 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 "json_utils.h"
#include "cJSON.h"
#include "common_util.h"
#include "hc_error.h"
#include "hc_log.h"
#include "hc_types.h"
#define RECURSE_FLAG_TRUE 1
CJson *CreateJsonFromString(const char *jsonStr)
{
if (jsonStr == NULL) {
LOGE("Param is null.");
return NULL;
}
return cJSON_Parse(jsonStr);
}
CJson *CreateJson()
{
return cJSON_CreateObject();
}
CJson *CreateJsonArray()
{
return cJSON_CreateArray();
}
CJson *DuplicateJson(const CJson *jsonObj)
{
if (jsonObj == NULL) {
LOGE("Param is null.");
return NULL;
}
return cJSON_Duplicate(jsonObj, RECURSE_FLAG_TRUE);
}
void FreeJson(CJson *jsonObj)
{
cJSON_Delete(jsonObj);
}
void DeleteItemFromJson(CJson *jsonObj, const char *key)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return;
}
cJSON_DeleteItemFromObjectCaseSensitive(jsonObj, key);
}
void DeleteAllItemExceptOne(CJson *jsonObj, const char *key)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return;
}
CJson *curItem = jsonObj->child;
CJson *nextItem = NULL;
while (curItem != NULL) {
nextItem = curItem->next;
if (strcmp(key, curItem->string) != 0) {
cJSON_Delete(cJSON_DetachItemViaPointer(jsonObj, curItem));
}
curItem = nextItem;
}
}
void DeleteAllItem(CJson *jsonObj)
{
if (jsonObj == NULL) {
LOGE("Param is null.");
return;
}
CJson *curItem = jsonObj->child;
CJson *nextItem = NULL;
while (curItem != NULL) {
nextItem = curItem->next;
cJSON_Delete(cJSON_DetachItemViaPointer(jsonObj, curItem));
curItem = nextItem;
}
}
CJson *DetachItemFromJson(CJson *jsonObj, const char *key)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return NULL;
}
return cJSON_DetachItemFromObjectCaseSensitive(jsonObj, key);
}
char *PackJsonToString(const CJson *jsonObj)
{
if (jsonObj == NULL) {
LOGE("Param is null.");
return NULL;
}
return cJSON_PrintUnformatted(jsonObj);
}
void FreeJsonString(char *jsonStr)
{
cJSON_free(jsonStr);
}
int GetItemNum(const CJson *jsonObj)
{
if (jsonObj == NULL) {
LOGE("Param is null.");
return 0;
}
return cJSON_GetArraySize(jsonObj);
}
const char *GetItemKey(const CJson *item)
{
if (item == NULL) {
LOGE("Param is null.");
return NULL;
}
return item->string;
}
CJson *GetObjFromJson(const CJson *jsonObj, const char *key)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return NULL;
}
cJSON *objValue = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (objValue != NULL) {
return objValue;
}
int len = cJSON_GetArraySize(jsonObj);
for (int i = 0; i < len; i++) {
cJSON *item = cJSON_GetArrayItem(jsonObj, i);
if (cJSON_IsObject(item)) {
cJSON *obj = GetObjFromJson(item, key);
if (obj != NULL) {
return obj;
}
}
}
return NULL;
}
CJson *GetItemFromArray(const CJson *jsonArr, int index)
{
if (jsonArr == NULL) {
LOGE("Param is null.");
return NULL;
}
return cJSON_GetArrayItem(jsonArr, index);
}
const char *GetStringFromJson(const CJson *jsonObj, const char *key)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return NULL;
}
cJSON *jsonObjTmp = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (jsonObjTmp != NULL && cJSON_IsString(jsonObjTmp)) {
return cJSON_GetStringValue(jsonObjTmp);
}
int len = cJSON_GetArraySize(jsonObj);
for (int i = 0; i < len; i++) {
cJSON *item = cJSON_GetArrayItem(jsonObj, i);
if (cJSON_IsObject(item)) {
const char *resValue = GetStringFromJson(item, key);
if (resValue != NULL) {
return resValue;
}
}
}
return NULL;
}
int32_t GetByteFromJson(const CJson *jsonObj, const char *key, uint8_t *byte, uint32_t len)
{
if (jsonObj == NULL || key == NULL || byte == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
const char *valueStr = GetStringFromJson(jsonObj, key);
if (valueStr == NULL) {
return HAL_ERR_JSON_GET;
}
if (len < strlen(valueStr) / BYTE_TO_HEX_OPER_LENGTH) {
LOGE("Invalid length.");
return HAL_ERR_INVALID_LEN;
}
int32_t ret = HexStringToByte(valueStr, byte, len);
if (ret != HAL_SUCCESS) {
LOGE("Convert hex string to byte failed.");
return ret;
}
return ret;
}
int32_t GetIntFromJson(const CJson *jsonObj, const char *key, int *value)
{
if (jsonObj == NULL || key == NULL || value == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
cJSON *jsonObjTmp = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (jsonObjTmp != NULL && cJSON_IsNumber(jsonObjTmp)) {
*value = (int)cJSON_GetNumberValue(jsonObjTmp);
return HAL_SUCCESS;
}
int len = cJSON_GetArraySize(jsonObj);
for (int i = 0; i < len; i++) {
cJSON *item = cJSON_GetArrayItem(jsonObj, i);
if (cJSON_IsObject(item)) {
int32_t ret = GetIntFromJson(item, key, value);
if (ret == HAL_SUCCESS) {
return ret;
}
}
}
return HAL_ERR_JSON_GET;
}
int32_t GetInt64FromJson(const CJson *jsonObj, const char *key, int64_t *value)
{
const char *str = GetStringFromJson(jsonObj, key);
if (str == NULL) {
LOGE("Failed to get int64_t from json!");
return HAL_ERR_JSON_GET;
}
*value = StringToInt64(str);
return HAL_SUCCESS;
}
int32_t GetBoolFromJson(const CJson *jsonObj, const char *key, bool *value)
{
if (jsonObj == NULL || key == NULL || value == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
cJSON *jsonObjTmp = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (jsonObjTmp != NULL && cJSON_IsBool(jsonObjTmp)) {
*value = cJSON_IsTrue(jsonObjTmp) ? true : false;
return HAL_SUCCESS;
}
int len = cJSON_GetArraySize(jsonObj);
for (int i = 0; i < len; i++) {
cJSON *item = cJSON_GetArrayItem(jsonObj, i);
if (cJSON_IsObject(item)) {
int32_t ret = GetBoolFromJson(item, key, value);
if (ret == HAL_SUCCESS) {
return ret;
}
}
}
return HAL_ERR_JSON_GET;
}
char *GetStringValue(const CJson *item)
{
return cJSON_GetStringValue(item);
}
int32_t AddObjToJson(CJson *jsonObj, const char *key, const CJson *childObj)
{
if (jsonObj == NULL || key == NULL || childObj == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
cJSON *tmpObj = cJSON_Duplicate(childObj, RECURSE_FLAG_TRUE);
if (tmpObj == NULL) {
LOGE("Duplicate json object failed.");
return HAL_ERR_JSON_DUPLICATE;
}
cJSON *objInJson = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (objInJson == NULL) {
if (cJSON_AddItemToObject(jsonObj, key, tmpObj) == false) {
LOGE("Add object to json failed.");
cJSON_Delete(tmpObj);
return HAL_ERR_JSON_ADD;
}
} else {
if (cJSON_ReplaceItemInObjectCaseSensitive(jsonObj, key, tmpObj) == false) {
LOGE("Replace object in json failed.");
cJSON_Delete(tmpObj);
return HAL_ERR_JSON_REPLACE;
}
}
return HAL_SUCCESS;
}
int32_t AddObjToArray(CJson *jsonArr, CJson *item)
{
if (jsonArr == NULL || item == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
if (cJSON_IsArray(jsonArr) == false) {
LOGE("Object is not array.");
return HAL_ERR_INVALID_PARAM;
}
bool ret = cJSON_AddItemToArray(jsonArr, item);
if (ret == false) {
LOGE("Add object to array failed.");
return HAL_ERR_JSON_ADD;
}
return HAL_SUCCESS;
}
int32_t AddStringToArray(CJson *jsonArr, const char *string)
{
if (jsonArr == NULL || string == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
if (cJSON_IsArray(jsonArr) == false) {
LOGE("Object is not array.");
return HAL_ERR_INVALID_PARAM;
}
cJSON *strObj = cJSON_CreateString(string);
if (strObj == NULL) {
LOGE("Create string json object failed.");
return HAL_ERR_BAD_ALLOC;
}
bool ret = cJSON_AddItemToArray(jsonArr, strObj);
if (ret == false) {
LOGE("Add string to array failed.");
cJSON_Delete(strObj);
return HAL_ERR_JSON_ADD;
}
return HAL_SUCCESS;
}
int32_t AddStringToJson(CJson *jsonObj, const char *key, const char *value)
{
if (jsonObj == NULL || key == NULL || value == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
cJSON *objInJson = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (objInJson == NULL) {
if (cJSON_AddStringToObject(jsonObj, key, value) == NULL) {
LOGE("Add string to json failed.");
return HAL_ERR_JSON_GET;
}
} else {
cJSON *tmp = cJSON_CreateString(value);
if (tmp == NULL) {
LOGE("Create string json object failed.");
return HAL_ERR_BAD_ALLOC;
}
if (cJSON_ReplaceItemInObjectCaseSensitive(jsonObj, key, tmp) == false) {
LOGE("Replace string in json failed.");
cJSON_Delete(tmp);
return HAL_ERR_JSON_REPLACE;
}
}
return HAL_SUCCESS;
}
int32_t AddByteToJson(CJson *jsonObj, const char *key, const uint8_t *byte, uint32_t len)
{
if (jsonObj == NULL || key == NULL || byte == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
uint32_t hexLen = len * BYTE_TO_HEX_OPER_LENGTH + 1;
char *hexStr = (char *)HcMalloc(hexLen, 0);
if (hexStr == NULL) {
LOGE("Malloc hex string failed.");
return HAL_ERR_BAD_ALLOC;
}
int32_t ret = ByteToHexString(byte, len, hexStr, hexLen);
if (ret != HAL_SUCCESS) {
LOGE("Convert byte to hex string failed.");
HcFree(hexStr);
return ret;
}
ret = AddStringToJson(jsonObj, key, hexStr);
if (ret != HAL_SUCCESS) {
LOGE("Add string to json failed.");
HcFree(hexStr);
return ret;
}
HcFree(hexStr);
return HAL_SUCCESS;
}
int32_t AddBoolToJson(CJson *jsonObj, const char *key, bool value)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
cJSON *objInJson = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (objInJson == NULL) {
if (cJSON_AddBoolToObject(jsonObj, key, value) == NULL) {
LOGE("Add bool to json failed.");
return HAL_ERR_JSON_GET;
}
} else {
cJSON *tmp = cJSON_CreateBool(value);
if (tmp == NULL) {
LOGE("Create bool json object failed.");
return HAL_ERR_BAD_ALLOC;
}
if (cJSON_ReplaceItemInObjectCaseSensitive(jsonObj, key, tmp) == false) {
LOGE("Repalce bool in json failed.");
cJSON_Delete(tmp);
return HAL_ERR_JSON_REPLACE;
}
}
return HAL_SUCCESS;
}
int32_t AddIntToJson(CJson *jsonObj, const char *key, int value)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
cJSON *objInJson = cJSON_GetObjectItemCaseSensitive(jsonObj, key);
if (objInJson == NULL) {
if (cJSON_AddNumberToObject(jsonObj, key, value) == NULL) {
LOGE("Add int to json failed.");
return HAL_ERR_JSON_GET;
}
} else {
cJSON *tmp = cJSON_CreateNumber(value);
if (tmp == NULL) {
LOGE("Create int json object failed.");
return HAL_ERR_BAD_ALLOC;
}
if (cJSON_ReplaceItemInObjectCaseSensitive(jsonObj, key, tmp) == false) {
LOGE("Replace int in json failed.");
cJSON_Delete(tmp);
return HAL_ERR_JSON_REPLACE;
}
}
return HAL_SUCCESS;
}
int32_t AddInt64StringToJson(CJson *jsonObj, const char *key, int64_t value)
{
char buffer[65] = { 0 };
if (sprintf_s(buffer, sizeof(buffer), "%lld", value) <= 0) {
LOGE("Failed to convert int64_t to string!");
return HAL_FAILED;
}
if (AddStringToJson(jsonObj, key, buffer) != HAL_SUCCESS) {
LOGE("Failed to add int64_t string to json!");
return HAL_ERR_JSON_ADD;
}
return HAL_SUCCESS;
}
int32_t AddStringArrayToJson(CJson *jsonObj, const char *key, const char * const *stringArray, uint32_t arrayLen)
{
if (jsonObj == NULL || key == NULL || stringArray == NULL) {
LOGE("Param is null.");
return HAL_ERR_NULL_PTR;
}
cJSON *strArrayObj = cJSON_CreateStringArray(stringArray, arrayLen);
if (strArrayObj == NULL) {
LOGE("Create string array object failed.");
return HAL_ERR_BAD_ALLOC;
}
if (cJSON_AddItemToObject(jsonObj, key, strArrayObj) == false) {
LOGE("Add string array to json failed.");
cJSON_Delete(strArrayObj);
return HAL_ERR_JSON_ADD;
}
return HAL_SUCCESS;
}
void ClearSensitiveStringInJson(CJson *jsonObj, const char *key)
{
if (jsonObj == NULL || key == NULL) {
LOGE("Param is null.");
return;
}
char *str = (char *)GetStringFromJson(jsonObj, key);
if (str == NULL) {
LOGD("Not find this value in json.");
return;
}
(void)memset_s(str, strlen(str), 0, strlen(str));
}
void ClearAndFreeJsonString(char *jsonStr)
{
if (jsonStr == NULL) {
LOGE("Param is invalid.");
return;
}
(void)memset_s(jsonStr, strlen(jsonStr), 0, strlen(jsonStr));
FreeJsonString(jsonStr);
}

View File

@ -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.
*/
#include "hc_dev_info.h"
#include "hc_error.h"
#include "securec.h"
#ifdef __cplusplus
extern "C" {
#endif
int32_t HcGetUdid(uint8_t *udid, int32_t udidLen)
{
if (udid == NULL || udidLen < INPUT_UDID_LEN || udidLen > MAX_INPUT_UDID_LEN) {
return HAL_ERR_INVALID_PARAM;
}
const char *udidTemp = "ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00";
(void)memset_s(udid, udidLen, 0, udidLen);
if (memcpy_s(udid, udidLen, udidTemp, strlen(udidTemp)) != EOK) {
return HAL_FAILED;
}
return HAL_SUCCESS;
}
const char *GetStoragePath()
{
return "/data/data/deviceauth/hcgroup.dat";
}
#ifdef __cplusplus
}
#endif

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.
*/
#include "hc_dev_info.h"
#include "common_util.h"
#include "hc_error.h"
#include "hc_log.h"
#include "hc_types.h"
#define UDID_BYTE_LEN_IN_L0_DEVICE 32
extern uint8_t GetUdid(uint8_t *buf, uint8_t length);
int32_t HcGetUdid(uint8_t *udid, int32_t udidLen)
{
if (udid == NULL || udidLen < INPUT_UDID_LEN || udidLen > MAX_INPUT_UDID_LEN) {
return HAL_ERR_INVALID_PARAM;
}
uint8_t *udidInner = (uint8_t *)HcMalloc(UDID_BYTE_LEN_IN_L0_DEVICE, 0);
if (udidInner == NULL) {
return HAL_ERR_BAD_ALLOC;
}
uint8_t resultLen = GetUdid(udidInner, UDID_BYTE_LEN_IN_L0_DEVICE);
if (resultLen != UDID_BYTE_LEN_IN_L0_DEVICE) {
HcFree(udidInner);
LOGE("GetUdid in L0 device failed, resultLen:%u", resultLen);
return HAL_FAILED;
}
int32_t result = ByteToHexString(udidInner, UDID_BYTE_LEN_IN_L0_DEVICE, udid, udidLen);
HcFree(udidInner);
if (result != HAL_SUCCESS) {
LOGE("ByteToHexString for udid failed, result:%d", result);
}
return result;
}
const char *GetStoragePath()
{
return "user/Hichain/hcgroup.dat";
}

View File

@ -0,0 +1,382 @@
/*
* 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 "crypto_hash_to_point.h"
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include "hc_error.h"
#include "hc_log.h"
#include "hc_types.h"
#include "hks_type.h"
#define KEY_BYTES_CURVE25519 32
struct CurveConstPara {
BIGNUM *p;
BIGNUM *one;
BIGNUM *d;
BIGNUM *k;
BIGNUM *capitalA;
BIGNUM *minusA;
BIGNUM *u;
BIGNUM *q;
};
/* RFC 8032, the prime of Curve25519, p = 2^255-19 */
static const uint8_t g_curveParamP[KEY_BYTES_CURVE25519] = {
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xed
};
/* RFC 8032, one = 1 */
static const uint8_t g_curveParamOne[KEY_BYTES_CURVE25519] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
};
/* RFC 8032, A non-zero element in the finite field GF(p), not equal to 1 */
static const uint8_t g_curveParamD[KEY_BYTES_CURVE25519] = {
0xa3, 0x78, 0x59, 0x13, 0xca, 0x4d, 0xeb, 0x75, 0xab, 0xd8, 0x41, 0x41, 0x4d, 0x0a, 0x70, 0x00,
0x98, 0xe8, 0x79, 0x77, 0x79, 0x40, 0xc7, 0x8c, 0x73, 0xfe, 0x6f, 0x2b, 0xee, 0x6c, 0x03, 0x52
};
/* RFC 8032, k = (p - 1) / 2 */
static const uint8_t g_curveParamK[KEY_BYTES_CURVE25519] = {
0xf6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f
};
/* RFC 8032, A = 486662 */
static const uint8_t g_curveParamCapitalA[KEY_BYTES_CURVE25519] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x6d, 0x06
};
/* RFC 8032, -A = -486662 */
static const uint8_t g_curveParamMinusA[KEY_BYTES_CURVE25519] = {
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x92, 0xe7
};
/* RFC 8032, u = 2 */
static const uint8_t g_curveParamU[KEY_BYTES_CURVE25519] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02
};
/* RFC 8032, q = endian_swap(k) */
static const uint8_t g_curveParamQ[KEY_BYTES_CURVE25519] = {
0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6
};
static void CurveInitConstPara(struct CurveConstPara *para)
{
para->p = BN_new();
para->one = BN_new();
para->d = BN_new();
para->k = BN_new();
para->capitalA = BN_new();
para->minusA = BN_new();
para->u = BN_new();
para->q = BN_new();
}
static void CurveFreeConstPara(struct CurveConstPara *para)
{
BN_free(para->p);
BN_free(para->one);
BN_free(para->d);
BN_free(para->k);
BN_free(para->capitalA);
BN_free(para->minusA);
BN_free(para->u);
BN_free(para->q);
}
/* b := -A / (1 + u * a ^ 2) */
static int32_t CurveHashToPointCalcB(const struct HksBlob *hash,
const struct CurveConstPara *curvePara, BIGNUM *b, BN_CTX *ctx)
{
BIGNUM *swap = BN_new();
int32_t ret = HAL_FAILED;
do {
if (BN_bin2bn(hash->data, hash->size, swap) == NULL) {
break;
}
if (BN_mul(b, swap, swap, ctx) <= 0) {
break;
}
if (BN_mod(b, b, curvePara->p, ctx) <= 0) {
break;
}
if (BN_mul(swap, b, curvePara->u, ctx) <= 0) {
break;
}
if (BN_mod(swap, swap, curvePara->p, ctx) <= 0) {
break;
}
if (BN_add(b, swap, curvePara->one) <= 0) {
break;
}
if (BN_mod(b, b, curvePara->p, ctx) <= 0) {
break;
}
if (BN_mod_inverse(swap, b, curvePara->p, ctx) <= 0) {
break;
}
if (BN_mul(b, swap, curvePara->minusA, ctx) <= 0) {
break;
}
if (BN_mod(b, b, curvePara->p, ctx) <= 0) {
break;
}
ret = HAL_SUCCESS;
} while (0);
BN_free(swap);
return ret;
}
static int32_t CurveHashToPointCalcA(const BIGNUM *b,
const struct CurveConstPara *curvePara, BIGNUM *a, BN_CTX *ctx)
{
BIGNUM *swap = BN_new();
BIGNUM *result = BN_new();
int32_t ret = HAL_FAILED;
do {
if (BN_mul(result, b, b, ctx) <= 0) {
break;
}
if (BN_mod(result, result, curvePara->p, ctx) <= 0) {
break;
}
if (BN_mul(swap, result, b, ctx) <= 0) {
break;
}
if (BN_mod(swap, swap, curvePara->p, ctx) <= 0) {
break;
}
if (BN_mul(a, result, curvePara->capitalA, ctx) <= 0) {
break;
}
if (BN_mod(a, a, curvePara->p, ctx) <= 0) {
break;
}
if (BN_add(result, swap, a) <= 0) {
break;
}
if (BN_mod(result, result, curvePara->p, ctx) <= 0) {
break;
}
if (BN_add(a, result, b) <= 0) {
break;
}
if (BN_mod(a, a, curvePara->p, ctx) <= 0) {
break;
}
ret = HAL_SUCCESS;
} while (0);
BN_free(swap);
BN_free(result);
return ret;
}
static int32_t CurveHashToPointCalcC(const BIGNUM *a, BIGNUM *b,
const struct CurveConstPara *curvePara, BIGNUM *c, BN_CTX *ctx)
{
BIGNUM *result = BN_new();
int32_t ret = HAL_FAILED;
do {
/* If a is a quadratic residue modulo p, c := b and high_y := 1 Otherwise c := -b - A and high_y := 0 */
if (BN_sub(c, curvePara->p, b) <= 0) {
break;
}
if (BN_mod(c, c, curvePara->p, ctx) <= 0) {
break;
}
if (BN_add(c, c, curvePara->minusA) <= 0) {
break;
}
if (BN_mod(c, c, curvePara->p, ctx) <= 0) {
break;
}
/* Sliding-window exponentiation: result = a^q mod p */
if (BN_mod_exp(result, a, curvePara->q, curvePara->p, ctx) <= 0) {
break;
}
if (BN_cmp(curvePara->q, result) > 0) {
BN_swap(b, c);
}
ret = HAL_SUCCESS;
} while (0);
BN_free(result);
return ret;
}
static int32_t CurveSetConstPara(struct CurveConstPara *para)
{
int32_t ret = HAL_FAILED;
do {
if (BN_bin2bn(g_curveParamP, KEY_BYTES_CURVE25519, para->p) == NULL) {
break;
}
if (BN_bin2bn(g_curveParamOne, KEY_BYTES_CURVE25519, para->one) == NULL) {
break;
}
if (BN_bin2bn(g_curveParamD, KEY_BYTES_CURVE25519, para->d) == NULL) {
break;
}
if (BN_bin2bn(g_curveParamK, KEY_BYTES_CURVE25519, para->k) == NULL) {
break;
}
if (BN_bin2bn(g_curveParamCapitalA, KEY_BYTES_CURVE25519, para->capitalA) == NULL) {
break;
}
if (BN_bin2bn(g_curveParamMinusA, KEY_BYTES_CURVE25519, para->minusA) == NULL) {
break;
}
if (BN_bin2bn(g_curveParamU, KEY_BYTES_CURVE25519, para->u) == NULL) {
break;
}
if (BN_bin2bn(g_curveParamQ, KEY_BYTES_CURVE25519, para->q) == NULL) {
break;
}
ret = HAL_SUCCESS;
} while (0);
return ret;
}
static int32_t CurveHashToPoint(const struct HksBlob *hash, struct HksBlob *point)
{
if ((hash == NULL) || (hash->data == NULL) ||
(hash->size != KEY_BYTES_CURVE25519)) {
return HAL_ERR_NULL_PTR;
}
if ((point == NULL) || (point->data == NULL) ||
(point->size != KEY_BYTES_CURVE25519)) {
return HAL_ERR_NULL_PTR;
}
BIGNUM *a = BN_new();
BIGNUM *b = BN_new();
BIGNUM *c = BN_new();
struct CurveConstPara curvePara;
(void)memset_s(&curvePara, sizeof(curvePara), 0, sizeof(curvePara));
CurveInitConstPara(&curvePara);
int32_t ret;
BN_CTX *ctx = BN_CTX_new();
if (ctx == NULL) {
ret = HAL_ERR_BAD_ALLOC;
goto err;
}
do {
ret = CurveSetConstPara(&curvePara);
if (ret != HAL_SUCCESS) {
break;
}
ret = CurveHashToPointCalcB(hash, &curvePara, b, ctx);
if (ret != HAL_SUCCESS) {
break;
}
ret = CurveHashToPointCalcA(b, &curvePara, a, ctx);
if (ret != HAL_SUCCESS) {
break;
}
ret = CurveHashToPointCalcC(a, b, &curvePara, c, ctx);
if (ret != HAL_SUCCESS) {
break;
}
if (BN_bn2bin(c, point->data) <= 0) {
ret = HAL_FAILED;
}
} while (0);
err:
CurveFreeConstPara(&curvePara);
BN_free(a);
BN_free(b);
BN_free(c);
BN_CTX_free(ctx);
return ret;
}
static int32_t EndianSwap(struct HksBlob *data)
{
if (data->data == NULL)
return HAL_ERR_NULL_PTR;
if (data->size == 0)
return HAL_ERR_NULL_PTR;
int32_t end = data->size - 1;
const int32_t start = 0;
/* count the middle index of array */
int32_t cnt = data->size / 2; // 2 used to calculate half of the data size
for (int32_t i = 0; i < cnt; i++) {
uint8_t tmp;
tmp = data->data[start + i];
data->data[start + i] = data->data[end - i];
data->data[end - i] = tmp;
}
return HAL_SUCCESS;
}
int32_t OpensslHashToPoint(const struct HksBlob *hash, struct HksBlob *point)
{
int32_t ret = HAL_FAILED;
uint8_t *copyData = HcMalloc(hash->size, 0);
if (copyData == NULL) {
LOGE("malloc size %u failed", hash->size);
return HKS_ERROR_MALLOC_FAIL;
}
struct HksBlob hashCopy = { hash->size, copyData};
do {
if (memcpy_s(hashCopy.data, hashCopy.size, hash->data, hash->size) != EOK) {
break;
}
hashCopy.data[hashCopy.size - 1] &= 0x3f; /* RFC 8032 */
ret = EndianSwap(&hashCopy);
if (ret != HAL_SUCCESS) {
LOGE("swap endian before convert failed");
break;
}
ret = CurveHashToPoint(&hashCopy, point);
if (ret != HAL_SUCCESS) {
LOGE("curve hash to point failed");
break;
}
ret = EndianSwap(point);
if (ret != HAL_SUCCESS) {
LOGE("swap endian after convert failed");
break;
}
} while (0);
HcFree(hashCopy.data);
return ret;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,166 @@
/*
* 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 "hc_condition.h"
#ifdef __cplusplus
extern "C" {
#endif
int Wait(pthread_cond_t* cond, HcMutex* mutex)
{
if (cond == NULL || mutex == NULL) {
return -1;
}
return -pthread_cond_wait(cond, &mutex->mutex);
}
void Notify(pthread_cond_t* cond)
{
if (cond == NULL) {
return;
}
pthread_cond_signal(cond);
}
int HcCondWaitWithoutLock(struct HcConditionT* hcCond)
{
if (hcCond == NULL || hcCond->mutex == NULL) {
return -1;
}
if (hcCond->notified) {
hcCond->notified = HC_FALSE;
return 0;
} else {
int ret;
hcCond->waited = HC_TRUE;
ret = Wait(&hcCond->cond, hcCond->mutex);
hcCond->waited = HC_FALSE;
hcCond->notified = HC_FALSE;
return ret;
}
}
void HcCondNotifyWithoutLock(struct HcConditionT* hcCond)
{
if (hcCond == NULL || hcCond->mutex == NULL) {
return;
}
if (!hcCond->waited) {
hcCond->notified = HC_TRUE;
} else {
hcCond->notified = HC_FALSE;
}
Notify(&hcCond->cond);
}
int HcCondWait(struct HcConditionT* hcCond)
{
if (hcCond == NULL) {
return -1;
}
if (hcCond->mutex == NULL) {
return -1;
}
hcCond->mutex->lock(hcCond->mutex);
if (hcCond->notified) {
hcCond->notified = HC_FALSE;
hcCond->mutex->unlock(hcCond->mutex);
return 0;
} else {
int ret;
hcCond->waited = HC_TRUE;
ret = Wait(&hcCond->cond, hcCond->mutex);
hcCond->waited = HC_FALSE;
hcCond->notified = HC_FALSE;
hcCond->mutex->unlock(hcCond->mutex);
return ret;
}
}
void HcCondNotify(struct HcConditionT* hcCond)
{
if (hcCond == NULL || hcCond->mutex == NULL) {
return;
}
hcCond->mutex->lock(hcCond->mutex);
if (!hcCond->waited) {
hcCond->notified = HC_TRUE;
} else {
hcCond->notified = HC_FALSE;
}
Notify(&hcCond->cond);
hcCond->mutex->unlock(hcCond->mutex);
}
int32_t InitHcCond(HcCondition* hcCond, HcMutex* mutex)
{
if (hcCond == NULL) {
return -1;
}
hcCond->notified = HC_FALSE;
hcCond->waited = HC_FALSE;
hcCond->wait = HcCondWait;
hcCond->notify = HcCondNotify;
hcCond->waitWithoutLock = HcCondWaitWithoutLock;
hcCond->notifyWithoutLock = HcCondNotifyWithoutLock;
pthread_condattr_t attr;
pthread_condattr_init(&attr);
pthread_cond_init(&hcCond->cond, &attr);
pthread_condattr_destroy(&attr);
if (mutex != NULL) {
hcCond->mutex = mutex;
hcCond->innerMutex = HC_FALSE;
} else {
hcCond->mutex = (HcMutex*)HcMalloc(sizeof(HcMutex), 0);
if (hcCond->mutex != NULL) {
int32_t res;
res = InitHcMutex(hcCond->mutex);
if (res != 0) {
HcFree(hcCond->mutex);
hcCond->mutex = NULL;
return res;
}
hcCond->innerMutex = HC_TRUE;
} else {
return -1;
}
}
return 0;
}
void DestroyHcCond(HcCondition* hcCond)
{
if (hcCond == NULL) {
return;
}
if (hcCond->innerMutex && hcCond->mutex) {
DestroyHcMutex(hcCond->mutex);
HcFree(hcCond->mutex);
hcCond->mutex = NULL;
}
pthread_cond_destroy(&hcCond->cond);
}
#ifdef __cplusplus
}
#endif

201
hals/src/linux/hc_file.c Normal file
View File

@ -0,0 +1,201 @@
/*
* 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 "hc_file.h"
#include "securec.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "hc_log.h"
#include "hc_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_FILE_PATH_SIZE 256
#define MAX_FOLDER_NAME_SIZE 128
typedef struct {
FileIdEnum fileId;
const char *filePath;
} FileDefInfo;
static char g_groupPath[MAX_FILE_PATH_SIZE] = { 0 };
static FileDefInfo g_fileDefInfo[FILE_ID_LAST] = {
{ FILE_ID_GROUP, "/data/data/deviceauth/hcgroup.dat" },
};
void SetFilePath(FileIdEnum fileId, const char *path)
{
if (path == NULL) {
LOGE("Invalid path param");
return;
}
if (sprintf_s(g_groupPath, MAX_FILE_PATH_SIZE, "%s", path) != -1) {
g_fileDefInfo[fileId].filePath = g_groupPath;
}
}
static int32_t CreateDirectory(const char *filePath)
{
int32_t ret;
errno_t eno;
char *chPtr = NULL;
char dirCache[MAX_FOLDER_NAME_SIZE];
chPtr = (char *)filePath;
while ((chPtr = strchr(chPtr, '/')) != NULL) {
unsigned long len = (unsigned long)((uintptr_t)chPtr - (uintptr_t)filePath);
if (len == 0ul) {
chPtr++;
continue;
}
eno = memcpy_s(dirCache, sizeof(dirCache), filePath, len);
if (eno != EOK) {
LOGE("memory copy failed");
return -1;
}
dirCache[len] = 0;
if (access(dirCache, F_OK) != 0) {
ret = mkdir(dirCache, S_IRWXU);
if (ret != 0) {
LOGE("make dir failed, err code %d", ret);
return -1;
}
}
chPtr++;
}
return 0;
}
static FILE *HcFileOpenRead(int fileId, const char *path)
{
(void)fileId;
return fopen(path, "rb");
}
static FILE *HcFileOpenWrite(int32_t fileId, const char *path)
{
(void)fileId;
if (access(path, F_OK) != 0) {
int32_t ret = CreateDirectory(path);
if (ret != 0) {
return NULL;
}
}
return fopen(path, "w+");
}
int HcFileOpen(int fileId, int mode, FileHandle *file)
{
if (fileId < 0 || fileId >= FILE_ID_LAST || file == NULL) {
return -1;
}
if (mode == MODE_FILE_READ) {
file->pfd = HcFileOpenRead(fileId, g_fileDefInfo[fileId].filePath);
} else {
file->pfd = HcFileOpenWrite(fileId, g_fileDefInfo[fileId].filePath);
}
if (file->pfd == NULL) {
return -1;
} else {
return 0;
}
}
int HcFileSize(FileHandle file)
{
FILE *fp = (FILE *)file.pfd;
if (fp != NULL) {
if (fseek(fp, 0L, SEEK_END) != 0) {
return -1;
}
int size = ftell(fp);
if (fseek(fp, 0L, SEEK_SET) != 0) {
return -1;
}
return size;
} else {
return -1;
}
}
int HcFileRead(FileHandle file, void *dst, int dstSize)
{
FILE *fp = (FILE *)file.pfd;
if (fp == NULL || dstSize < 0 || dst == NULL) {
return -1;
}
char *dstBuffer = (char *)dst;
int total = 0;
while (total < dstSize) {
int readCount = fread(dstBuffer + total, 1, dstSize - total, fp);
if ((readCount < 0) || (readCount > (dstSize - total))) {
return -1;
}
if (readCount == 0) {
return total;
}
total += readCount;
}
return total;
}
int HcFileWrite(FileHandle file, const void *src, int srcSize)
{
FILE *fp = (FILE *)file.pfd;
if (fp == NULL || srcSize < 0 || src == NULL) {
return -1;
}
const char *srcBuffer = (const char *)src;
int total = 0;
while (total < srcSize) {
int writeCount = fwrite(srcBuffer + total, 1, srcSize - total, fp);
if (writeCount < 0 || writeCount > (srcSize - total)) {
return -1;
}
total += writeCount;
}
return total;
}
void HcFileClose(FileHandle file)
{
FILE *fp = (FILE *)file.pfd;
if (fp == NULL) {
return;
}
fclose(fp);
}
void HcFileRemove(int fileId)
{
if (fileId >= FILE_ID_LAST) {
LOGE("Invalid fileId:%d", fileId);
return;
}
unlink(g_fileDefInfo[fileId].filePath);
}
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,45 @@
/*
* 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 "hc_init_protection.h"
#include <stdbool.h>
static bool g_isInitialized = false;
int CheckInit()
{
if (g_isInitialized) {
return FINISH_INIT;
}
return CONTINUE_INIT;
}
int CheckDestroy()
{
if (!g_isInitialized) {
return FINISH_DESTROY;
}
return CONTINUE_DESTROY;
}
void SetInitStatus()
{
g_isInitialized = true;
}
void SetDeInitStatus()
{
g_isInitialized = false;
}

62
hals/src/linux/hc_mutex.c Normal file
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.
*/
#include "hc_mutex.h"
#ifdef __cplusplus
extern "C" {
#endif
int MutexLock(HcMutex* mutex)
{
if (mutex == NULL) {
return -1;
}
return -pthread_mutex_lock(&mutex->mutex);
}
void MutexUnlock(HcMutex* mutex)
{
if (mutex == NULL) {
return;
}
pthread_mutex_unlock(&mutex->mutex);
}
int32_t InitHcMutex(struct HcMutexT* mutex)
{
if (mutex == NULL) {
return -1;
}
int res = pthread_mutex_init(&mutex->mutex, NULL);
if (res != 0) {
return res;
}
mutex->lock = MutexLock;
mutex->unlock = MutexUnlock;
return res;
}
void DestroyHcMutex(struct HcMutexT* mutex)
{
if (mutex == NULL) {
return;
}
pthread_mutex_destroy(&mutex->mutex);
}
#ifdef __cplusplus
}
#endif

154
hals/src/linux/hc_thread.c Normal file
View File

@ -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 "hc_thread.h"
#include "hc_error.h"
#include "hc_log.h"
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_THREAD_STACK_SIZE (8 * 1024 * 1024)
void* StaticThreadFunc(void* args)
{
HcThread* thread = (HcThread*)args;
if (thread == NULL) {
return NULL;
}
if (thread->threadFunc) {
thread->threadFunc(args);
}
thread->threadLock.lock(&thread->threadLock);
thread->running = HC_FALSE;
thread->threadWaitObj.notifyWithoutLock(&thread->threadWaitObj);
thread->threadLock.unlock(&thread->threadLock);
return 0;
}
int Start(struct HcThreadT* thread)
{
if (thread == NULL) {
return HAL_ERR_NULL_PTR;
}
thread->threadLock.lock(&thread->threadLock);
if (thread->running) {
thread->threadLock.unlock(&thread->threadLock);
return 0;
}
thread->running = HC_TRUE;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (thread->stackSize > 0 && thread->stackSize <= MAX_THREAD_STACK_SIZE) {
pthread_attr_setstacksize(&attr, thread->stackSize);
}
int result = pthread_create(&thread->thread, &attr, StaticThreadFunc, thread);
pthread_attr_destroy(&attr);
if (result != 0) {
LOGE("pthread_create failed.");
thread->running = HC_FALSE;
}
thread->threadLock.unlock(&thread->threadLock);
return result;
}
void Join(struct HcThreadT* thread)
{
if (thread == NULL) {
return;
}
thread->threadLock.lock(&thread->threadLock);
if (thread->running) {
thread->threadWaitObj.waitWithoutLock(&thread->threadWaitObj);
}
thread->threadLock.unlock(&thread->threadLock);
}
void BizWait(struct HcThreadT* thread)
{
if (thread == NULL) {
return;
}
thread->bizWaitObj.wait(&thread->bizWaitObj);
}
void BizNotify(struct HcThreadT* thread)
{
if (thread == NULL) {
return;
}
thread->bizWaitObj.notify(&thread->bizWaitObj);
}
int32_t InitThread(HcThread* thread, ThreadFunc func, size_t stackSize, const char* threadName)
{
if (thread == NULL) {
return -1;
}
thread->threadFunc = func;
thread->start = Start;
thread->wait = BizWait;
thread->notify = BizNotify;
thread->join = Join;
thread->stackSize = stackSize;
thread->running = HC_FALSE;
thread->name = CreateString();
if (StringSetPointer(&thread->name, threadName) != HC_TRUE) {
return -1;
}
int32_t res = InitHcMutex(&thread->threadLock);
if (res != 0) {
DeleteString(&thread->name);
return res;
}
res = InitHcCond(&thread->threadWaitObj, &thread->threadLock);
if (res != 0) {
DeleteString(&thread->name);
DestroyHcMutex(&thread->threadLock);
return res;
}
res = InitHcCond(&thread->bizWaitObj, NULL);
if (res != 0) {
DeleteString(&thread->name);
DestroyHcMutex(&thread->threadLock);
DestroyHcCond(&thread->threadWaitObj);
}
return res;
}
void DestroyThread(HcThread* thread)
{
if (thread == NULL) {
return;
}
DestroyHcCond(&thread->bizWaitObj);
DestroyHcCond(&thread->threadWaitObj);
DestroyHcMutex(&thread->threadLock);
DeleteString(&thread->name);
}
#ifdef __cplusplus
}
#endif

57
hals/src/linux/hc_time.c Executable file
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.
*/
#include "hc_time.h"
#include <stdio.h>
#include <time.h>
#include "hc_log.h"
#ifdef __cplusplus
extern "C" {
#endif
int64_t HcGetCurTime()
{
struct timespec start;
int res = clock_gettime(CLOCK_MONOTONIC, &start);
if (res != 0) {
LOGE("clock_gettime failed, res:%d", res);
return -1;
}
return start.tv_sec;
}
int64_t HcGetIntervalTime(int64_t startTime)
{
if (startTime < 0) {
LOGE("Start time is invalid");
return -1;
}
struct timespec end;
int res = clock_gettime(CLOCK_MONOTONIC, &end);
if (res != 0) {
LOGE("clock_gettime failed, res:%d", res);
return -1;
}
if (end.tv_sec < startTime) {
LOGE("End time is invalid");
return -1;
}
return (end.tv_sec - startTime);
}
#ifdef __cplusplus
}
#endif

56
hals/src/linux/hc_types.c Executable file
View File

@ -0,0 +1,56 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hc_types.h"
#include "hc_log.h"
#include "securec.h"
#ifdef __cplusplus
extern "C" {
#endif
void* HcMalloc(uint32_t size, char val)
{
if (size == 0) {
LOGE("Malloc size is invalid.");
return NULL;
}
void* addr = malloc(size);
if (addr != NULL) {
(void)memset_s(addr, size, val, size);
}
return addr;
}
void HcFree(void* addr)
{
if (addr != NULL) {
free(addr);
}
}
uint32_t HcStrlen(const char *str)
{
if (str == NULL) {
return 0;
}
const char *p = str;
while (*p++ != '\0') {}
return p - str - 1;
}
#ifdef __cplusplus
}
#endif

View File

@ -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.
*/
#include "hc_init_protection.h"
#include <stdbool.h>
#include <stdlib.h>
#include "hc_log.h"
#include "hc_thread.h"
#include "ohos_init.h"
static HcMutex g_countMutex;
static int g_singleCount = 0;
int CheckInit()
{
g_countMutex.lock(&g_countMutex);
if (g_singleCount < 0) {
g_singleCount = 0;
} else if (g_singleCount > 0) {
g_singleCount++;
g_countMutex.unlock(&g_countMutex);
return FINISH_INIT;
}
g_countMutex.unlock(&g_countMutex);
return CONTINUE_INIT;
}
int CheckDestroy()
{
g_countMutex.lock(&g_countMutex);
if (g_singleCount == 0) {
g_countMutex.unlock(&g_countMutex);
return FINISH_DESTROY;
}
if (g_singleCount < 0) {
g_singleCount = 0;
g_countMutex.unlock(&g_countMutex);
return FINISH_DESTROY;
}
if (g_singleCount > 1) {
g_singleCount--;
g_countMutex.unlock(&g_countMutex);
return FINISH_DESTROY;
}
g_countMutex.unlock(&g_countMutex);
return CONTINUE_DESTROY;
}
void SetInitStatus()
{
g_countMutex.lock(&g_countMutex);
g_singleCount = 1;
g_countMutex.unlock(&g_countMutex);
return;
}
void SetDeInitStatus()
{
g_countMutex.lock(&g_countMutex);
g_singleCount = 0;
g_countMutex.unlock(&g_countMutex);
return;
}
void InitSecurityDevAuth()
{
int32_t res = InitHcMutex(&g_countMutex);
if (res != 0) {
LOGE("When init security auth, init mutex failed");
}
}
SYS_SERVICE_INIT(InitSecurityDevAuth);
void DestroySecurityDevAuth()
{
DestroyHcMutex(&g_countMutex);
}

554
hals/src/liteos/L0/huks_adapter.c Executable file
View File

@ -0,0 +1,554 @@
/*
* 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 "huks_adapter.h"
#include "common_util.h"
#include "hc_error.h"
#include "hc_file.h"
#include "hc_log.h"
#include "hks_api.h"
#include "hks_param.h"
#include "hks_type.h"
static int32_t BaseCheckParams(const Uint8Buff **inParams, const char **paramTags, uint32_t len)
{
for (uint32_t i = 0; i < len; i++) {
CHECK_PTR_RETURN_ERROR_CODE(inParams[i], paramTags[i]);
CHECK_PTR_RETURN_ERROR_CODE(inParams[i]->val, paramTags[i]);
CHECK_LEN_ZERO_RETURN_ERROR_CODE(inParams[i]->length, paramTags[i]);
}
return HAL_SUCCESS;
}
static int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam *inParam,
const uint32_t inParamNum)
{
struct HksParamSet *paramSet = NULL;
int32_t ret = HksInitParamSet(&paramSet);
if (ret != HKS_SUCCESS) {
LOGE("init param set failed, ret = %d", ret);
return HAL_ERR_INIT_PARAM_SET_FAILED;
}
ret = HksAddParams(paramSet, inParam, inParamNum);
if (ret != HKS_SUCCESS) {
LOGE("add param failed, ret = %d", ret);
HksFreeParamSet(&paramSet);
return HAL_ERR_ADD_PARAM_FAILED;
}
ret = HksBuildParamSet(&paramSet);
if (ret != HKS_SUCCESS) {
LOGE("build param set failed, ret = %d", ret);
HksFreeParamSet(&paramSet);
return HAL_ERR_BUILD_PARAM_SET_FAILED;
}
*out = paramSet;
return HAL_SUCCESS;
}
static int32_t InitHks()
{
int32_t res = HksInitialize();
if (res == HKS_SUCCESS) {
return HAL_SUCCESS;
}
if ((res != HKS_ERROR_INVALID_KEY_FILE) && (res != HKS_ERROR_CRYPTO_ENGINE_ERROR) &&
(res != HKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL)) {
LOGE("Hks: Init hks failed, res: %d.", res);
return HAL_ERR_INIT_FAILED;
}
LOGD("Hks: The local hks file needs to be refreshed!");
LOGI("Start to delete local database file!");
HcFileRemove(FILE_ID_GROUP);
LOGI("Delete local database file successfully!");
res = HksRefreshKeyInfo();
if (res != HKS_SUCCESS) {
LOGE("Hks: HksRefreshKeyInfo failed, res: %d.", res);
return HAL_ERR_INIT_FAILED;
}
res = HksInitialize();
if (res != HKS_SUCCESS) {
LOGE("Hks: Init hks failed, res: %d.", res);
return HAL_ERR_INIT_FAILED;
}
return HAL_SUCCESS;
}
static int32_t Sha256(const Uint8Buff *message, Uint8Buff *hash)
{
CHECK_PTR_RETURN_ERROR_CODE(message, "message");
CHECK_PTR_RETURN_ERROR_CODE(message->val, "message->val");
CHECK_LEN_ZERO_RETURN_ERROR_CODE(message->length, "message->length");
CHECK_PTR_RETURN_ERROR_CODE(hash, "hash");
CHECK_PTR_RETURN_ERROR_CODE(hash->val, "hash->val");
CHECK_LEN_EQUAL_RETURN(hash->length, SHA256_LEN, "hash->length");
struct HksBlob srcBlob = { message->length, message->val };
struct HksBlob hashBlob = { hash->length, hash->val };
struct HksParamSet *paramSet = NULL;
struct HksParam digestParam[] = {
{
.tag = HKS_TAG_DIGEST,
.uint32Param = HKS_DIGEST_SHA256
}
};
int32_t ret = ConstructParamSet(&paramSet, digestParam, CAL_ARRAY_SIZE(digestParam));
if (ret != HAL_SUCCESS) {
LOGE("construct param set failed, ret = %d", ret);
return ret;
}
ret = HksHash(paramSet, &srcBlob, &hashBlob);
if (ret != HKS_SUCCESS || hashBlob.size != SHA256_LEN) {
HksFreeParamSet(&paramSet);
return HAL_FAILED;
}
HksFreeParamSet(&paramSet);
return HAL_SUCCESS;
}
static int32_t GenerateRandom(Uint8Buff *rand)
{
CHECK_PTR_RETURN_ERROR_CODE(rand, "rand");
CHECK_PTR_RETURN_ERROR_CODE(rand->val, "rand->val");
CHECK_LEN_ZERO_RETURN_ERROR_CODE(rand->length, "rand->length");
struct HksBlob randBlob = { rand->length, rand->val };
int32_t ret = HksGenerateRandom(NULL, &randBlob);
if (ret != HKS_SUCCESS) {
LOGE("Generate random failed, ret: %d", ret);
return HAL_FAILED;
}
return HAL_SUCCESS;
}
static int32_t CheckKeyExist(const Uint8Buff *keyAlias)
{
CHECK_PTR_RETURN_ERROR_CODE(keyAlias, "keyAlias");
CHECK_PTR_RETURN_ERROR_CODE(keyAlias->val, "keyAlias->val");
CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyAlias->length, "keyAlias->length");
struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
int32_t ret = HksKeyExist(&keyAliasBlob, NULL);
if (ret != HKS_SUCCESS) {
LOGE("Check key exist failed, ret = %d", ret);
return HAL_FAILED;
}
return HAL_SUCCESS;
}
static int32_t DeleteKey(const Uint8Buff *keyAlias)
{
CHECK_PTR_RETURN_ERROR_CODE(keyAlias, "keyAlias");
CHECK_PTR_RETURN_ERROR_CODE(keyAlias->val, "keyAlias->val");
CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyAlias->length, "keyAlias->length");
struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
int32_t ret = HksDeleteKey(&keyAliasBlob, NULL);
if (ret == HKS_ERROR_NOT_EXIST) {
LOGI("Key not exists.");
return HAL_SUCCESS;
}
if (ret != HKS_SUCCESS) {
LOGE("Delete key failed, ret = %d", ret);
return HAL_FAILED;
}
return HAL_SUCCESS;
}
static int32_t ComputeHmac(const Uint8Buff *key, const Uint8Buff *message, Uint8Buff *outHmac, bool isAlias)
{
const Uint8Buff *inParams[] = { key, message, outHmac };
const char *paramTags[] = {"key", "message", "outHmac"};
int32_t ret = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
if (ret != HAL_SUCCESS) {
return ret;
}
CHECK_LEN_EQUAL_RETURN(outHmac->length, HMAC_LEN, "outHmac->length");
struct HksBlob keyBlob = { key->length, key->val };
struct HksBlob srcBlob = { message->length, message->val };
struct HksBlob hmacBlob = { outHmac->length, outHmac->val };
struct HksParamSet *paramSet = NULL;
struct HksParam hmacParam[] = {
{
.tag = HKS_TAG_PURPOSE,
.uint32Param = HKS_KEY_PURPOSE_MAC
}, {
.tag = HKS_TAG_DIGEST,
.uint32Param = HKS_DIGEST_SHA256
}, {
.tag = HKS_TAG_IS_KEY_ALIAS,
.boolParam = isAlias
}
};
ret = ConstructParamSet(&paramSet, hmacParam, CAL_ARRAY_SIZE(hmacParam));
if (ret != HAL_SUCCESS) {
LOGE("construct param set failed, ret = %d", ret);
return ret;
}
ret = HksMac(&keyBlob, paramSet, &srcBlob, &hmacBlob);
if (ret != HKS_SUCCESS || hmacBlob.size != HMAC_LEN) {
LOGE("Hmac failed, ret: %d", ret);
HksFreeParamSet(&paramSet);
return HAL_FAILED;
}
HksFreeParamSet(&paramSet);
return HAL_SUCCESS;
}
static int32_t ComputeHkdf(const Uint8Buff *baseKey, const Uint8Buff *salt, const Uint8Buff *keyInfo,
Uint8Buff *outHkdf, bool isAlias)
{
const Uint8Buff *inParams[] = { baseKey, salt, outHkdf };
const char *paramTags[] = { "baseKey", "salt", "outHkdf" };
int32_t ret = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
if (ret != HAL_SUCCESS) {
return ret;
}
struct HksBlob srcKeyBlob = { baseKey->length, baseKey->val };
struct HksBlob saltBlob = { salt->length, salt->val };
struct HksBlob keyInfoBlob = { 0, NULL };
if (keyInfo != NULL) {
keyInfoBlob.size = keyInfo->length;
keyInfoBlob.data = keyInfo->val;
}
struct HksBlob derivedKeyBlob = { outHkdf->length, outHkdf->val };
struct HksParamSet *paramSet = NULL;
struct HksParam hkdfParam[] = {
{
.tag = HKS_TAG_PURPOSE,
.uint32Param = HKS_KEY_PURPOSE_DERIVE
}, {
.tag = HKS_TAG_ALGORITHM,
.uint32Param = HKS_ALG_HKDF
}, {
.tag = HKS_TAG_DIGEST,
.uint32Param = HKS_DIGEST_SHA256
}, {
.tag = HKS_TAG_SALT,
.blob = saltBlob
}, {
.tag = HKS_TAG_INFO,
.blob = keyInfoBlob
}, {
.tag = HKS_TAG_IS_KEY_ALIAS,
.boolParam = isAlias
}
};
ret = ConstructParamSet(&paramSet, hkdfParam, CAL_ARRAY_SIZE(hkdfParam));
if (ret != HAL_SUCCESS) {
return ret;
}
ret = HksDeriveKey(paramSet, &srcKeyBlob, &derivedKeyBlob);
if (ret != HKS_SUCCESS) {
LOGE("Key derivation failed, ret: %d", ret);
HksFreeParamSet(&paramSet);
return HAL_FAILED;
}
HksFreeParamSet(&paramSet);
return HAL_SUCCESS;
}
static int32_t CheckAesGcmEncryptParam(const Uint8Buff *key, const Uint8Buff *plain, const GcmParam *encryptInfo,
Uint8Buff *outCipher)
{
const Uint8Buff *inParams[] = { key, plain, outCipher };
const char* paramTags[] = { "key", "plain", "outCipher" };
int32_t ret = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
if (ret != HAL_SUCCESS) {
return ret;
}
CHECK_PTR_RETURN_ERROR_CODE(encryptInfo, "encryptInfo");
CHECK_PTR_RETURN_ERROR_CODE(encryptInfo->aad, "aad");
CHECK_LEN_ZERO_RETURN_ERROR_CODE(encryptInfo->aadLen, "aadLen");
CHECK_PTR_RETURN_ERROR_CODE(encryptInfo->nonce, "nonce");
CHECK_LEN_LOWER_RETURN(encryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen");
CHECK_LEN_LOWER_RETURN(outCipher->length, plain->length + HKS_AE_TAG_LEN, "outCipher");
return HAL_SUCCESS;
}
static int32_t AesGcmEncrypt(const Uint8Buff *key, const Uint8Buff *plain,
const GcmParam *encryptInfo, bool isAlias, Uint8Buff *outCipher)
{
int32_t ret = CheckAesGcmEncryptParam(key, plain, encryptInfo, outCipher);
if (ret != HAL_SUCCESS) {
return ret;
}
struct HksBlob keyBlob = { key->length, key->val };
struct HksBlob plainBlob = { plain->length, plain->val };
struct HksBlob cipherBlob = { outCipher->length, outCipher->val };
struct HksParamSet *paramSet = NULL;
struct HksParam encryptParam[] = {
{
.tag = HKS_TAG_PURPOSE,
.uint32Param = HKS_KEY_PURPOSE_ENCRYPT
}, {
.tag = HKS_TAG_ALGORITHM,
.uint32Param = HKS_ALG_AES
}, {
.tag = HKS_TAG_BLOCK_MODE,
.uint32Param = HKS_MODE_GCM
}, {
.tag = HKS_TAG_PADDING,
.uint32Param = HKS_PADDING_NONE
}, {
.tag = HKS_TAG_NONCE,
.blob = { encryptInfo->nonceLen, encryptInfo->nonce }
}, {
.tag = HKS_TAG_ASSOCIATED_DATA,
.blob = { encryptInfo->aadLen, encryptInfo->aad }
}, {
.tag = HKS_TAG_IS_KEY_ALIAS,
.boolParam = isAlias
}
};
ret = ConstructParamSet(&paramSet, encryptParam, CAL_ARRAY_SIZE(encryptParam));
if (ret != HAL_SUCCESS) {
LOGE("construct param set failed, ret = %d", ret);
return ret;
}
ret = HksEncrypt(&keyBlob, paramSet, &plainBlob, &cipherBlob);
if (ret != HKS_SUCCESS) {
LOGE("Aes-gcm encrypt failed, ret: %d", ret);
HksFreeParamSet(&paramSet);
return HAL_FAILED;
}
HksFreeParamSet(&paramSet);
return HAL_SUCCESS;
}
static int32_t CheckAesGcmDecryptParam(const Uint8Buff *key, const Uint8Buff *cipher, const GcmParam *decryptInfo,
Uint8Buff *outPlain)
{
const Uint8Buff *inParams[] = { key, cipher, outPlain };
const char *paramTags[] = { "key", "cipher", "outPlain" };
int32_t ret = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
if (ret != HAL_SUCCESS) {
return ret;
}
CHECK_PTR_RETURN_ERROR_CODE(decryptInfo, "decryptInfo");
CHECK_PTR_RETURN_ERROR_CODE(decryptInfo->aad, "aad");
CHECK_LEN_ZERO_RETURN_ERROR_CODE(decryptInfo->aadLen, "aadLen");
CHECK_PTR_RETURN_ERROR_CODE(decryptInfo->nonce, "nonce");
CHECK_LEN_LOWER_RETURN(decryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen");
CHECK_LEN_LOWER_RETURN(outPlain->length, cipher->length - HKS_AE_TAG_LEN, "outPlain");
return HAL_SUCCESS;
}
static int32_t AesGcmDecrypt(const Uint8Buff *key, const Uint8Buff *cipher,
const GcmParam *decryptInfo, bool isAlias, Uint8Buff *outPlain)
{
int32_t ret = CheckAesGcmDecryptParam(key, cipher, decryptInfo, outPlain);
if (ret != HAL_SUCCESS) {
return ret;
}
struct HksBlob keyBlob = { key->length, key->val };
struct HksBlob cipherBlob = { cipher->length, cipher->val };
struct HksBlob plainBlob = { outPlain->length, outPlain->val };
struct HksParamSet *paramSet = NULL;
struct HksParam decryptParam[] = {
{
.tag = HKS_TAG_PURPOSE,
.uint32Param = HKS_KEY_PURPOSE_DECRYPT
}, {
.tag = HKS_TAG_ALGORITHM,
.uint32Param = HKS_ALG_AES
}, {
.tag = HKS_TAG_BLOCK_MODE,
.uint32Param = HKS_MODE_GCM
}, {
.tag = HKS_TAG_PADDING,
.uint32Param = HKS_PADDING_NONE
}, {
.tag = HKS_TAG_NONCE,
.blob = { decryptInfo->nonceLen, decryptInfo->nonce }
}, {
.tag = HKS_TAG_ASSOCIATED_DATA,
.blob = { decryptInfo->aadLen, decryptInfo->aad }
}, {
.tag = HKS_TAG_IS_KEY_ALIAS,
.boolParam = isAlias
}
};
ret = ConstructParamSet(&paramSet, decryptParam, CAL_ARRAY_SIZE(decryptParam));
if (ret != HAL_SUCCESS) {
LOGE("construct param set failed, ret = %d", ret);
return ret;
}
ret = HksDecrypt(&keyBlob, paramSet, &cipherBlob, &plainBlob);
if (ret != HKS_SUCCESS) {
LOGE("Aes-gcm decrypt failed, ret: %d", ret);
HksFreeParamSet(&paramSet);
return HAL_FAILED;
}
HksFreeParamSet(&paramSet);
return HAL_SUCCESS;
}
static int32_t CheckImportAsymmetricKeyParam(const Uint8Buff *keyAlias, const Uint8Buff *authToken,
const Uint8Buff *authId, const int32_t userType, const int32_t pairType)
{
const Uint8Buff *inParams[] = { keyAlias, authToken, authId };
const char *paramTags[] = { "keyAlias", "authToken", "authId" };
int32_t ret = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
if (ret != HAL_SUCCESS) {
return ret;
}
CHECK_LEN_HIGHER_RETURN(pairType, PAIR_TYPE_END - 1, "pairType");
return HAL_SUCCESS;
}
static int32_t ConstructImportAsymmetricKeyParam(struct HksParamSet **paramSet, uint32_t keyLen, uint32_t roleInfo,
const struct HksBlob *authIdBlob)
{
struct HksParam importParam[] = {
{
.tag = HKS_TAG_ALGORITHM,
.uint32Param = HKS_ALG_AES
}, {
.tag = HKS_TAG_KEY_SIZE,
.uint32Param = keyLen * BITS_PER_BYTE
}, {
.tag = HKS_TAG_PADDING,
.uint32Param = HKS_PADDING_NONE
}, {
.tag = HKS_TAG_KEY_AUTH_ID,
.blob = *authIdBlob
}, {
.tag = HKS_TAG_IS_ALLOWED_WRAP,
.boolParam = false
}, {
.tag = HKS_TAG_PURPOSE,
.uint32Param = HKS_KEY_PURPOSE_MAC
}, {
.tag = HKS_TAG_KEY_ROLE,
.uint32Param = roleInfo
}, {
.tag = HKS_TAG_BLOCK_MODE,
.uint32Param = HKS_MODE_GCM
}, {
.tag = HKS_TAG_DIGEST,
.uint32Param = HKS_DIGEST_SHA256
}
};
int ret = ConstructParamSet(paramSet, importParam, CAL_ARRAY_SIZE(importParam));
if (ret != HAL_SUCCESS) {
LOGE("construct decrypt param set failed, ret = %d", ret);
return ret;
}
return ret;
}
static int32_t ImportAsymmetricKey(const Uint8Buff *keyAlias, const Uint8Buff *authToken, const ExtraInfo *exInfo)
{
int32_t ret = CheckImportAsymmetricKeyParam(keyAlias, authToken, &exInfo->authId, exInfo->userType,
exInfo->pairType);
if (ret != HAL_SUCCESS) {
return ret;
}
struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
struct HksBlob pubKeyBlob = { authToken->length, authToken->val };
struct HksBlob authIdBlob = { exInfo->authId.length, exInfo->authId.val };
union KeyRoleInfoUnion roleInfoUnion;
roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType;
roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType;
roleInfoUnion.roleInfoStruct.reserved1 = (uint8_t)0;
roleInfoUnion.roleInfoStruct.reserved2 = (uint8_t)0;
struct HksParamSet *paramSet = NULL;
ret = ConstructImportAsymmetricKeyParam(&paramSet, authToken->length, roleInfoUnion.roleInfo, &authIdBlob);
if (ret != HAL_SUCCESS) {
LOGE("construct param set failed, ret = %d", ret);
return ret;
}
ret = HksImportKey(&keyAliasBlob, paramSet, &pubKeyBlob);
if (ret != HKS_SUCCESS) {
LOGE("HksImportKey failed, ret: %d", ret);
HksFreeParamSet(&paramSet);
return ret;
}
HksFreeParamSet(&paramSet);
return HAL_SUCCESS;
}
static const AlgLoader g_huksLoader = {
InitHks,
Sha256,
GenerateRandom,
ComputeHmac,
ComputeHkdf,
ImportAsymmetricKey,
CheckKeyExist,
DeleteKey,
AesGcmEncrypt,
AesGcmDecrypt,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
const AlgLoader *GetRealLoaderInstance()
{
return &g_huksLoader;
}

View File

@ -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.
*/
#include "hc_init_protection.h"
#include <stdbool.h>
#include <stdlib.h>
static bool g_isInitialized = false;
int CheckInit()
{
if (g_isInitialized) {
return FINISH_INIT;
}
return CONTINUE_INIT;
}
int CheckDestroy()
{
if (!g_isInitialized) {
return FINISH_DESTROY;
}
return CONTINUE_DESTROY;
}
void SetInitStatus()
{
g_isInitialized = true;
}
void SetDeInitStatus()
{
g_isInitialized = false;
}

View File

@ -0,0 +1,58 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hc_condition.h"
int HcCondWait(struct HcConditionT* hcCond)
{
if (hcCond == NULL) {
return -1;
}
return sem_wait(&hcCond->sem);
}
void HcCondNotify(struct HcConditionT* hcCond)
{
if (hcCond == NULL) {
return;
}
sem_post(&hcCond->sem);
}
int32_t InitHcCond(HcCondition* hcCond, HcMutex* mutex)
{
(void)mutex;
if (hcCond == NULL) {
return -1;
}
hcCond->wait = HcCondWait;
hcCond->notify = HcCondNotify;
hcCond->waitWithoutLock = HcCondWait;
hcCond->notifyWithoutLock = HcCondNotify;
// init the signal value to zero
return sem_init(&hcCond->sem, 0, 0);
}
void DestroyHcCond(HcCondition* hcCond)
{
if (hcCond == NULL) {
return;
}
sem_destroy(&hcCond->sem);
}

215
hals/src/liteos/hc_file.c Executable file
View File

@ -0,0 +1,215 @@
/*
* 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 "hc_file.h"
#include <errno.h>
#include <fcntl.h>
#include <securec.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "common_defs.h"
#include "hc_error.h"
#include "hc_log.h"
#define MAX_FILE_PATH_SIZE 256
#define MAX_FOLDER_NAME_SIZE 128
#define GET_FOLDER_OK 0
#define GET_FOLDER_FAILED (-1)
#define GET_FILE_OK 1
#define DEFAULT_FILE_PERMISSION 0666
typedef struct {
FileIdEnum fileId;
const char* filePath;
} FileDefInfo;
static FileDefInfo g_fileDefInfo[FILE_ID_LAST] = {
{ FILE_ID_GROUP, "user/Hichain/hcgroup.dat" }
};
static char g_groupPath[MAX_FILE_PATH_SIZE] = { 0 };
void SetFilePath(FileIdEnum fileId, const char *path)
{
if (path == NULL) {
LOGE("Invalid path param");
return;
}
if (sprintf_s(g_groupPath, MAX_FILE_PATH_SIZE, "%s", path) != -1) {
g_fileDefInfo[fileId].filePath = g_groupPath;
}
}
int GetNextFolder(const char* filePath, int* beginPos, char* dst, int size)
{
int pos = (*beginPos);
while (1) {
char c = filePath[pos++];
if (c == '\0') {
if (memcpy_s(dst, size, filePath, pos - 1) != EOK) {
return GET_FOLDER_FAILED;
}
dst[pos - 1] = '\0';
(*beginPos) = pos;
return GET_FILE_OK;
} else if (c == '/') {
if (memcpy_s(dst, size, filePath, pos - 1) != EOK) {
return GET_FOLDER_FAILED;
}
dst[pos - 1] = '\0';
(*beginPos) = pos;
return GET_FOLDER_OK;
} else {
if (pos >= size) {
(*beginPos) = pos;
return GET_FOLDER_FAILED;
}
}
}
}
int HcFileOpenRead(const char* path)
{
return open(path, O_RDONLY);
}
static int IsFileValid(const char *path)
{
struct stat fileStat;
int32_t ret = stat(path, &fileStat);
if (ret == -1) {
if (errno == ENOENT) {
return HAL_ERR_FILE_NOT_EXIST;
} else {
LOGE("file stat failed, errno = 0x%x", errno);
return HAL_ERR_FILE;
}
}
return 0;
}
int HcFileOpenWrite(const char* path)
{
char filePath[MAX_FOLDER_NAME_SIZE + 1];
int beginPos = 0;
while (1) {
int ret = GetNextFolder(path, &beginPos, filePath, sizeof(filePath));
if (ret == GET_FOLDER_OK) {
if (IsFileValid(filePath) == 0) {
continue;
}
if (mkdir(filePath, DEFAULT_FILE_PERMISSION) != 0) {
return -1;
}
} else if (ret == GET_FOLDER_FAILED) {
return -1;
} else {
int fd = open(filePath, O_RDWR | O_CREAT);
if (fd == -1) {
LOGE("file stat failed, errno = 0x%x", errno);
}
return fd;
}
}
}
int HcFileOpen(int fileId, int mode, FileHandle* file)
{
if (fileId < 0 || fileId >= FILE_ID_LAST || file == NULL) {
return -1;
}
if (mode == MODE_FILE_READ) {
file->fd = HcFileOpenRead(g_fileDefInfo[fileId].filePath);
} else {
file->fd = HcFileOpenWrite(g_fileDefInfo[fileId].filePath);
}
if (file->fd == -1) {
return -1;
}
return 0;
}
int HcFileSize(FileHandle file)
{
int fp = file.fd;
int size = lseek(fp, 0, SEEK_END);
(void)lseek(fp, 0, SEEK_SET);
return size;
}
int HcFileRead(FileHandle file, void* dst, int dstSize)
{
int fp = file.fd;
if (fp == -1 || dstSize < 0 || dst == NULL) {
return -1;
}
char *dstBuffer = (char *)dst;
int total = 0;
while (total < dstSize) {
int readCount = read(fp, dstBuffer + total, dstSize - total);
if (readCount < 0 || readCount > (dstSize - total)) {
LOGE("read errno :%x", errno);
return -1;
}
if (readCount == 0) {
LOGE("read errno :%x", errno);
return total;
}
total += readCount;
}
return total;
}
int HcFileWrite(FileHandle file, const void *src, int srcSize)
{
int fp = file.fd;
if (fp == -1 || srcSize < 0 || src == NULL) {
return -1;
}
const char* srcBuffer = (const char*)src;
int total = 0;
while (total < srcSize) {
int writeCount = write(fp, srcBuffer + total, srcSize - total);
if (writeCount < 0 || writeCount > (srcSize - total)) {
return -1;
}
total += writeCount;
}
return total;
}
void HcFileClose(FileHandle file)
{
int fp = file.fd;
if (fp == 0) {
return;
}
close(fp);
}
void HcFileRemove(int fileId)
{
if (fileId >= FILE_ID_LAST) {
LOGE("Invalid fileId:%d", fileId);
return;
}
unlink(g_fileDefInfo[fileId].filePath);
}

View File

@ -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.
*/
#include "hc_mutex.h"
int MutexLock(HcMutex* mutex)
{
if (mutex == NULL) {
return -1;
}
return -pthread_mutex_lock(&mutex->mutex);
}
void MutexUnlock(HcMutex* mutex)
{
if (mutex == NULL) {
return;
}
pthread_mutex_unlock(&mutex->mutex);
}
int32_t InitHcMutex(struct HcMutexT* mutex)
{
if (mutex == NULL) {
return -1;
}
int res = pthread_mutex_init(&mutex->mutex, NULL);
if (res != 0) {
return res;
}
mutex->lock = MutexLock;
mutex->unlock = MutexUnlock;
return 0;
}
void DestroyHcMutex(struct HcMutexT* mutex)
{
if (mutex == NULL) {
return;
}
pthread_mutex_destroy(&mutex->mutex);
}

143
hals/src/liteos/hc_thread.c Normal file
View File

@ -0,0 +1,143 @@
/*
* 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 "hc_thread.h"
#define MAX_THREAD_STACK_SIZE (8 * 1024 * 1024)
void *StaticThreadFunc(void *args)
{
HcThread *thread = (HcThread*)args;
if (thread == NULL) {
return NULL;
}
if (thread->threadFunc) {
thread->threadFunc(args);
}
thread->threadLock.lock(&thread->threadLock);
thread->running = HC_FALSE;
thread->threadWaitObj.notifyWithoutLock(&thread->threadWaitObj);
thread->threadLock.unlock(&thread->threadLock);
return NULL;
}
int Start(struct HcThreadT *thread)
{
if (thread == NULL) {
return -1;
}
thread->threadLock.lock(&thread->threadLock);
if (thread->running) {
thread->threadLock.unlock(&thread->threadLock);
return 0;
}
thread->running = HC_TRUE;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if (thread->stackSize > 0 && thread->stackSize <= MAX_THREAD_STACK_SIZE) {
pthread_attr_setstacksize(&attr, thread->stackSize);
}
int result = pthread_create(&thread->thread, &attr, StaticThreadFunc, thread);
pthread_attr_destroy(&attr);
if (result != 0) {
thread->running = HC_FALSE;
}
thread->threadLock.unlock(&thread->threadLock);
return result;
}
void Join(struct HcThreadT *thread)
{
if (thread == NULL) {
return;
}
if (thread->running) {
thread->threadWaitObj.waitWithoutLock(&thread->threadWaitObj);
}
void *status = NULL;
pthread_join(thread->thread, &status);
}
void BizWait(struct HcThreadT *thread)
{
if (thread == NULL) {
return;
}
thread->bizWaitObj.wait(&thread->bizWaitObj);
}
void BizNotify(struct HcThreadT *thread)
{
if (thread == NULL) {
return;
}
thread->bizWaitObj.notify(&thread->bizWaitObj);
}
int32_t InitThread(HcThread *thread, ThreadFunc func, size_t stackSize, const char *threadName)
{
if (thread == NULL) {
return -1;
}
thread->threadFunc = func;
thread->start = Start;
thread->wait = BizWait;
thread->notify = BizNotify;
thread->join = Join;
thread->stackSize = stackSize;
thread->running = HC_FALSE;
thread->name = CreateString();
if (StringSetPointer(&thread->name, threadName) != HC_TRUE) {
return -1;
}
int32_t res = InitHcMutex(&thread->threadLock);
if (res != 0) {
DeleteString(&thread->name);
return res;
}
res = InitHcCond(&thread->threadWaitObj, &thread->threadLock);
if (res != 0) {
DeleteString(&thread->name);
DestroyHcMutex(&thread->threadLock);
return res;
}
res = InitHcCond(&thread->bizWaitObj, NULL);
if (res != 0) {
DeleteString(&thread->name);
DestroyHcMutex(&thread->threadLock);
DestroyHcCond(&thread->threadWaitObj);
}
return res;
}
void DestroyThread(HcThread *thread)
{
if (thread == NULL) {
return;
}
DestroyHcCond(&thread->bizWaitObj);
DestroyHcCond(&thread->threadWaitObj);
DestroyHcMutex(&thread->threadLock);
DeleteString(&thread->name);
}

49
hals/src/liteos/hc_time.c Executable file
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.
*/
#include "hc_time.h"
#include <stdio.h>
#include <time.h>
#include "hc_log.h"
int64_t HcGetCurTime()
{
struct timespec start;
int res = clock_gettime(CLOCK_MONOTONIC, &start);
if (res != 0) {
LOGE("clock_gettime failed, res:%d", res);
return -1;
}
return start.tv_sec;
}
int64_t HcGetIntervalTime(int64_t startTime)
{
if (startTime < 0) {
LOGE("Start time is invalid");
return -1;
}
struct timespec end;
int res = clock_gettime(CLOCK_MONOTONIC, &end);
if (res != 0) {
LOGE("clock_gettime failed, res:%d", res);
return -1;
}
if (end.tv_sec < startTime) {
LOGE("End time is invalid");
return -1;
}
return (end.tv_sec - startTime);
}

51
hals/src/liteos/hc_types.c Executable file
View File

@ -0,0 +1,51 @@
/*
* 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 "hc_types.h"
#include <stdlib.h>
#include <string.h>
#include "hc_log.h"
#include "ohos_mem_pool.h"
void *HcMalloc(uint32_t size, char val)
{
if (size == 0) {
LOGE("Malloc size is invalid.");
return NULL;
}
void* addr = OhosMalloc(MEM_TYPE_HICHAIN, size);
if (addr != NULL) {
(void)memset_s(addr, size, val, size);
}
return addr;
}
void HcFree(void* addr)
{
if (addr != NULL) {
OhosFree(addr);
}
}
uint32_t HcStrlen(const char *str)
{
if (str == NULL) {
return 0;
}
const char *p = str;
while (*p++ != '\0') {}
return p - str - 1;
}

View File

@ -0,0 +1,166 @@
/*
* 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 DEVICE_AUTH_H
#define DEVICE_AUTH_H
#include <stdint.h>
#include <stdbool.h>
#if defined(_LINUX) || defined(_UNIX)
#define DEVICE_AUTH_API_PUBLIC __attribute__ ((visibility("default")))
#else
#define DEVICE_AUTH_API_PUBLIC
#endif
#define FIELD_GROUP_ID "groupId"
#define FIELD_GROUP_TYPE "groupType"
#define FIELD_GROUP_NAME "groupName"
#define FIELD_PEER_DEVICE_ID "peerDeviceId"
#define FIELD_IS_ADMIN "isAdmin"
#define FIELD_CREDENTIAL_TYPE "credentialType"
#define FIELD_IS_FORCE_DELETE "isForceDelete"
#define FIELD_IS_IGNORE_CHANNEL "isIgnoreChannel"
#define FIELD_CONNECT_PARAMS "connectParams"
#define FIELD_ADD_ID "addId"
#define FIELD_DELETE_ID "deleteId"
#define FIELD_APP_ID "appId"
#define FIELD_SERVICE_TYPE "serviceType"
#define FIELD_PEER_AUTH_STATE "peerAuthState"
#define FIELD_IS_DEVICE_LEVEL "isDeviceLevel"
#define FIELD_ALTERNATIVE "alternative"
#define FIELD_PEER_UDID "peerUdid"
#define FIELD_PEER_CONN_DEVICE_ID "peerConnDeviceId"
#define FIELD_KEY_LENGTH "keyLength"
#define FIELD_IS_CLIENT "isClient"
#define FIELD_SESSION_KEY "sessionKey"
#define FIELD_AUTH_FORM "authForm"
#define FIELD_CONFIRMATION "confirmation"
#define FIELD_GROUP_OWNER "groupOwner"
#define FIELD_PEER_AUTH_ID "peerAuthId"
#define FIELD_PEER_USER_TYPE "peerUserType"
#define FIELD_PEER_USER_ID "peerUserId"
#define FIELD_SERVICE_PKG_NAME "servicePkgName"
#define FIELD_USER_TYPE "userType"
#define FIELD_USER_ID "userId"
#define FIELD_DEVICE_ID "deviceId"
#define FIELD_UID_HASH "uidHash"
#define FIELD_PIN_CODE "pinCode"
#define FIELD_AUTH_ID "authId"
#define FIELD_GROUP_VISIBILITY "groupVisibility"
#define FIELD_EXPIRE_TIME "expireTime"
#define FIELD_IS_DELETE_ALL "isDeleteAll"
typedef enum {
GROUP_CREATE = 0,
GROUP_DISBAND = 1,
MEMBER_INVITE = 2,
MEMBER_JOIN = 3,
MEMBER_DELETE = 4,
ACCOUNT_BIND = 5
} GroupOperationCode;
typedef enum {
CREDENTIAL_SAVE = 0,
CREDENTIAL_CLEAR = 1,
CREDENTIAL_UPDATE = 2,
CREDENTIAL_QUERY = 3,
} CredentialCode;
typedef enum {
DEVICE_TYPE_ACCESSORY = 0,
DEVICE_TYPE_CONTROLLER = 1,
DEVICE_TYPE_PROXY = 2
} UserType;
#define REQUEST_REJECTED 0x80000005
#define REQUEST_ACCEPTED 0x80000006
#define REQUEST_WAITING 0x80000007
typedef struct {
void (*onGroupCreated)(const char *groupInfo);
void (*onGroupDeleted)(const char *groupInfo);
void (*onDeviceBound)(const char *peerUdid, const char *groupInfo);
void (*onDeviceUnBound)(const char *peerUdid, const char *groupInfo);
void (*onDeviceNotTrusted)(const char *peerUdid);
void (*onLastGroupDeleted)(const char *peerUdid, int groupType);
void (*onTrustedDeviceNumChanged)(int curTrustedDeviceNum);
} DataChangeListener;
typedef struct {
bool (*onTransmit)(int64_t requestId, const uint8_t *data, uint32_t dataLen);
void (*onSessionKeyReturned)(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen);
void (*onFinish)(int64_t requestId, int operationCode, const char *returnData);
void (*onError)(int64_t requestId, int operationCode, int errorCode, const char *errorReturn);
char *(*onRequest)(int64_t requestId, int operationCode, const char *reqParams);
} DeviceAuthCallback;
typedef struct {
int32_t (*processData)(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
const DeviceAuthCallback *gaCallback);
int32_t (*queryTrustedDeviceNum)(void);
bool (*isTrustedDevice)(const char *udid);
int32_t (*getAuthState)(int64_t authReqId, const char *groupId, const char *peerUdid,
uint8_t *out, uint32_t *outLen);
int32_t (*authDevice)(int64_t authReqId, const char *authParams, const DeviceAuthCallback *gaCallback);
void (*informDeviceDisconnection)(const char *udid);
} GroupAuthManager;
typedef struct {
int32_t (*regCallback)(const char *appId, const DeviceAuthCallback *callback);
int32_t (*unRegCallback)(const char *appId);
int32_t (*regDataChangeListener)(const char *appId, const DataChangeListener *listener);
int32_t (*unRegDataChangeListener)(const char *appId);
int32_t (*createGroup)(int64_t requestId, const char *appId, const char *createParams);
int32_t (*deleteGroup)(int64_t requestId, const char *appId, const char *disbandParams);
int32_t (*addMemberToGroup)(int64_t requestId, const char *appId, const char *addParams);
int32_t (*deleteMemberFromGroup)(int64_t requestId, const char *appId, const char *deleteParams);
int32_t (*processData)(int64_t requestId, const uint8_t *data, uint32_t dataLen);
int32_t (*confirmRequest)(int64_t requestId, const char *appId, const char *confirmParams);
int32_t (*bindPeer)(int64_t requestId, const char *appId, const char *bindParams);
int32_t (*unbindPeer)(int64_t requestId, const char *appId, const char *unBindParams);
int32_t (*processLiteData)(int64_t requestId, const char *appId, const uint8_t *data, uint32_t dataLen);
int32_t (*authKeyAgree)(int64_t requestId, const char *appId, const char *buildParams);
int32_t (*processKeyAgreeData)(int64_t requestId, const char *appId, const uint8_t *data, uint32_t dataLen);
int32_t (*processCredential)(int operationCode, const char *reqJsonStr, char **returnJsonStr);
int32_t (*getRegisterInfo)(char **returnRegisterInfo);
int32_t (*getLocalConnectInfo)(char **returnInfo);
int32_t (*addGroupManager)(const char *appId, const char *groupId, const char *managerAppId);
int32_t (*addGroupFriend)(const char *appId, const char *groupId, const char *friendAppId);
int32_t (*deleteGroupManager)(const char *appId, const char *groupId, const char *managerAppId);
int32_t (*deleteGroupFriend)(const char *appId, const char *groupId, const char *friendAppId);
int32_t (*getGroupManagers)(const char *appId, const char *groupId, char **returnManagers, uint32_t *returnSize);
int32_t (*getGroupFriends)(const char *appId, const char *groupId, char **returnFriends, uint32_t *returnSize);
int32_t (*getGroupInfoById)(const char *appId, const char *groupId, char **returnGroupInfo);
int32_t (*getGroupInfo)(const char *appId, const char *queryParams, char **returnGroupVec, uint32_t *groupNum);
int32_t (*getJoinedGroups)(const char *appId, int groupType, char **returnGroupVec, uint32_t *groupNum);
int32_t (*getRelatedGroups)(const char *appId, const char *peerDeviceId, char **returnGroupVec, uint32_t *groupNum);
int32_t (*getDeviceInfoById)(const char *appId, const char *deviceId, const char *groupId, char **returnDeviceInfo);
int32_t (*getTrustedDevices)(const char *appId, const char *groupId, char **returnDevInfoVec, uint32_t *deviceNum);
bool (*isDeviceInGroup)(const char *appId, const char *groupId, const char *deviceId);
void (*destroyInfo)(char **returnInfo);
} DeviceGroupManager;
#ifdef __cplusplus
extern "C" {
#endif
DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService();
DEVICE_AUTH_API_PUBLIC void DestroyDeviceAuthService();
DEVICE_AUTH_API_PUBLIC const GroupAuthManager *GetGaInstance();
DEVICE_AUTH_API_PUBLIC const DeviceGroupManager *GetGmInstance();
#ifdef __cplusplus
}
#endif
#endif

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.
*/
#ifndef DEVICE_AUTH_DEFINES_H
#define DEVICE_AUTH_DEFINES_H
#define HC_GROUP_FRIEND_MAX_NUM 100 /* Visibility is 1, friend list is available, and max is 100 */
#define HC_GROUP_MANAGER_MAX_NUM 10 /* manager max number is 10, it includes owner and other managers */
enum {
/* common error code, 0x00000000 ~ 0x00000FFF */
HC_SUCCESS = 0x00000000,
HC_ERROR = 0x00000001,
HC_ERR_INVALID_PARAMS = 0x00000002,
HC_ERR_INVALID_LEN = 0x00000003,
HC_ERR_NULL_PTR = 0x00000004,
HC_ERR_ALLOC_MEMORY = 0x00000005,
HC_ERR_MEMORY_COPY = 0x00000006,
HC_HEX_CONVERT_FAILED = 0x00000007,
HC_ERR_NOT_SUPPORT = 0x00000008,
HC_ERR_TIME_OUT = 0x00000009,
HC_ERR_CASE = 0x0000000A,
HC_ERR_BAD_TIMING = 0x0000000B,
HC_ERR_PEER_ERROR = 0x0000000C,
/* error code for huks adapter , 0x00001000 ~ 0x00001FFF */
HC_ERR_KEY_NOT_EXIST = 0x00001001,
HC_ERR_GENERATE_KEY_FAILED = 0x000010002,
HC_ERR_INVALID_PUBLIC_KEY = 0x00001003,
HC_ERR_VERIFY_FAILED = 0x00001004,
HC_ERR_HASH_FAIL = 0x00001005,
/* error code for json util , 0x00002000 ~ 0x00002FFF */
HC_ERR_JSON_FAIL = 0x00002001,
HC_ERR_JSON_CREATE = 0x00002002,
HC_ERR_JSON_GET = 0x00002003,
HC_ERR_JSON_ADD = 0x00002004,
HC_ERR_PACKAGE_JSON_TO_STRING_FAIL = 0x00002005,
/* error code for ipc, 0x00003000 ~ 0x00003FFF */
HC_ERR_IPC_INTERNAL_FAILED = 0x00003001,
HC_ERR_IPC_UNKNOW_OPCODE = 0x00003002,
HC_ERR_IPC_CALL_DATA_LENGTH = 0x00003003,
HC_ERR_IPC_METHOD_ID_INVALID = 0x00003004,
HC_ERR_IPC_BAD_MESSAGE_LENGTH = 0x00003005,
HC_ERR_IPC_BAD_VAL_LENGTH = 0x00003006,
HC_ERR_IPC_BAD_PARAM_NUM = 0x00003007,
HC_ERR_IPC_BAD_MSG_TYPE = 0x00003008,
HC_ERR_IPC_GET_SERVICE = 0x00003009,
HC_ERR_IPC_GET_PROXY = 0x0000300A,
HC_ERR_IPC_INIT = 0x0000300B,
HC_ERR_IPC_BUILD_PARAM = 0x0000300C,
HC_ERR_IPC_PROC_FAILED = 0x0000300D,
HC_ERR_IPC_UNKNOW_REPLAY = 0x0000300E,
HC_ERR_IPC_OUT_DATA_NUM = 0x0000300F,
HC_ERR_IPC_OUT_DATA = 0x00003010,
/* error code for module , 0x00004000 ~ 0x00004FFF */
HC_ERR_MODULE_NOT_FOUNT = 0x00004001,
HC_ERR_UNSUPPORTED_METHOD = 0x00004002,
HC_ERR_UNSUPPORTED_VERSION = 0x00004003,
HC_ERR_UNSUPPORTED_CURVE = 0x00004004,
HC_ERR_BAD_MESSAGE = 0x00004005,
HC_ERR_PROOF_NOT_MATCH = 0x00004006,
HC_ERR_INIT_TASK_FAIL = 0x00004007,
HC_ERR_TASK_IS_NULL = 0x00004008,
HC_ERR_TASK_ID_IS_NOT_MATCH = 0x00004009,
HC_ERR_INVALID_ALG = 0x0000400A,
HC_ERR_IGNORE_MSG = 0x0000400B,
HC_ERR_LOCAL_IDENTITY_NOT_EXIST = 0x0000400C,
/* error code for group , 0x00005000 ~ 0x00005FFF */
HC_ERR_ACCESS_DENIED = 0x00005001,
HC_ERR_CALLBACK_NOT_FOUND = 0x00005002,
HC_ERR_SERVICE_NEED_RESTART = 0x00005003,
HC_ERR_NO_CANDIDATE_GROUP = 0x00005004,
HC_ERR_TRANSMIT_FAIL = 0x00005005,
HC_ERR_REQUEST_EXIST = 0x00005006,
HC_ERR_REQUEST_NOT_FOUND = 0x00005007,
HC_ERR_SESSION_NOT_EXIST = 0x00005008,
HC_ERR_SESSION_ID_CONFLICT = 0x00005009,
HC_ERR_REQ_REJECTED = 0x0000500A,
HC_ERR_SERVER_CONFIRM_FAIL = 0x0000500B,
HC_ERR_CREATE_SESSION_FAIL = 0x0000500C,
HC_ERR_SESSION_IS_FULL = 0x0000500D,
/* error code for database , 0x00006000 ~ 0x00006FFF */
HC_ERR_DB = 0x00006001,
HC_ERR_BEYOND_LIMIT = 0x00006002,
HC_ERR_SAVE_DB_FAILED = 0x00006003,
HC_ERR_FRIEND_NOT_EXIST = 0x00006004,
HC_ERR_MANAGER_NOT_EXIST = 0x00006005,
HC_ERR_GROUP_DUPLICATE = 0x00006006,
HC_ERR_GROUP_NOT_EXIST = 0x00006007,
HC_ERR_DEVICE_NOT_EXIST = 0x00006008,
HC_ERR_DEVICE_DUPLICATE = 0x00006009,
HC_ERR_LOST_DATA = 0x0000600A,
/* error code for broadcast , 0x00007000 ~ 0x00007FFF */
HC_ERR_LISTENER_NOT_EXIST = 0x000070012,
/* error code for channel , 0x00008000 ~ 0x00008FFF */
HC_ERR_CHANNEL_NOT_EXIST = 0x000080012,
HC_ERR_SOFT_BUS = 0x00008002,
/* error code used on DAS service */
INVALID_PARAMETERS = 0xF0000001,
EXCEED_AUTHORITY = 0xF0000002,
TIMEOUT = 0xF0000003,
NOT_REGISTERED = 0xF0000004,
NOT_TRUST_PEER = 0xF0000005,
NOT_TRUST_CONTROLLER = 0xF0000006,
NOT_TRUST_ACCESSORY = 0xF0000007,
OVER_MAX_TRUST_NUM = 0xF0000008,
CONNECTION_INTERRUPTED = 0xF0000009,
UNSUPPORTED_VERSION = 0xF000000A,
BAD_PAYLOAD = 0xF000000B,
ALGORITHM_UNSUPPORTED = 0xF000000C,
PROOF_MISMATCH = 0xF000000D,
UNKOWN = 0xF0000000,
};
#endif

19
ohos.build Executable file
View File

@ -0,0 +1,19 @@
{
"subsystem": "security",
"parts": {
"deviceauth_standard": {
"variants": [
"phone",
"wearable"
],
"module_list": [
"//base/security/deviceauth:deviceauth_build",
"//base/security/deviceauth:deviceauth_service_build",
"//base/security/deviceauth:deviceauth_sdk_build"
],
"test_list": [
"//base/security/deviceauth:deviceauth_test_build"
]
}
}
}

125
services/BUILD.gn Normal file
View File

@ -0,0 +1,125 @@
# 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("//base/security/deviceauth/hals/deviceauth_hals.gni")
import("//build/ohos.gni")
import("deviceauth.gni")
ohos_static_library("deviceauth") {
subsystem_name = "security"
part_name = "deviceauth_standard"
include_dirs = inc_path
include_dirs += hals_inc_path
include_dirs += [
"//third_party/cJSON",
"//utils/native/base/include",
]
sources = deviceauth_files
cflags = [ "-DHILOG_ENABLE" ]
cflags += build_flags
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${hals_path}:${hal_module_name}",
"//third_party/cJSON:cjson_static",
"//utils/native/base:utils",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
}
ohos_prebuilt_etc("auth_service.rc") {
source = "${frameworks_path}/src/deviceauth_service.rc"
relative_install_dir = "init"
subsystem_name = "security"
part_name = "deviceauth_standard"
}
group("etc") {
deps = [ ":auth_service.rc" ]
}
ohos_executable("deviceauth_service") {
subsystem_name = "security"
part_name = "deviceauth_standard"
install_enable = true
include_dirs = inc_path
include_dirs += hals_inc_path
include_dirs += [
"//third_party/cJSON",
"//utils/native/base/include",
]
sources = deviceauth_ipc_files
sources += [ "${frameworks_path}/src/ipc_service.c" ]
cflags = [ "-DHILOG_ENABLE" ]
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
":auth_service.rc",
":deviceauth",
"${hals_path}:${hal_module_name}",
"//third_party/cJSON:cjson_static",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
}
ohos_shared_library("deviceauth_sdk") {
subsystem_name = "security"
part_name = "deviceauth_standard"
include_dirs = inc_path
include_dirs += hals_inc_path
include_dirs += [
"//third_party/cJSON",
"//utils/native/base/include",
]
sources = deviceauth_ipc_files
sources += [ "${frameworks_path}/src/ipc_sdk.c" ]
cflags = [ "-DHILOG_ENABLE" ]
cflags += build_flags
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${hals_path}:${hal_module_name}",
"//third_party/cJSON:cjson_static",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
}

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 BROADCAST_MANAGER_H
#define BROADCAST_MANAGER_H
#include "database.h"
#include "device_auth.h"
typedef struct {
void (*postOnGroupCreated)(const GroupInfo *groupInfo);
void (*postOnGroupDeleted)(const GroupInfo *groupInfo);
void (*postOnDeviceBound)(const char *peerUdid, const GroupInfo *groupInfo);
void (*postOnDeviceUnBound)(const char *peerUdid, const GroupInfo *groupInfo);
void (*postOnDeviceNotTrusted)(const char *peerUdid);
void (*postOnLastGroupDeleted)(const char *peerUdid, int groupType);
void (*postOnTrustedDeviceNumChanged)(int curTrustedDeviceNum);
} Broadcaster;
bool IsBroadcastSupported();
int32_t InitBroadcastManager();
void DestroyBroadcastManager();
Broadcaster *GetBroadcaster();
int32_t AddListener(const char *appId, const DataChangeListener *listener);
int32_t RemoveListener(const char *appId);
#endif

View File

@ -0,0 +1,31 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CALLBACK_MANAGER_H
#define CALLBACK_MANAGER_H
#include "device_auth.h"
bool ProcessTransmitCallback(int64_t requestId, const uint8_t *data, uint32_t dataLen,
const DeviceAuthCallback *callback);
char *ProcessRequestCallback(int64_t requestId, int operationCode, const char *reqParams,
const DeviceAuthCallback *callback);
void ProcessFinishCallback(int64_t requestId, int operationCode, const char *returnData,
const DeviceAuthCallback *callback);
void ProcessSessionKeyCallback(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen,
const DeviceAuthCallback *callback);
void ProcessErrorCallback(int64_t requestId, int operationCode, int errorCode, const char *errorReturn,
const DeviceAuthCallback *callback);
#endif

View File

@ -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 CHANNEL_MANAGER_H
#define CHANNEL_MANAGER_H
#include "device_auth.h"
#include "common_defs.h"
#include "json_utils.h"
int32_t InitChannelManager(void (*onChannelOpened)(int64_t, int64_t, const char *, uint32_t, bool),
void (*onChannelClosed)(int64_t, int64_t),
void (*onMsgReceived)(int64_t, const uint8_t *, uint32_t),
void (*onServiceDied)());
void DestroyChannelManager();
/* Channel operation interfaces */
ChannelType GetChannelType(const DeviceAuthCallback *callback);
bool CanFindValidChannel(ChannelType channelType, const CJson *jsonParams, const DeviceAuthCallback *callback);
int32_t OpenChannel(ChannelType channelType, const CJson *jsonParams, int64_t requestId, int64_t *returnChannelId);
void CloseChannel(ChannelType channelType, int64_t channelId);
int32_t SendMsg(ChannelType channelType, int64_t requestId, int64_t channelId,
const DeviceAuthCallback *callback, const char *data);
void SetAuthResult(ChannelType channelType, int64_t channelId);
int32_t GetLocalConnectInfo(char **returnLocalConnectInfo);
#endif

View File

@ -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 SOFT_BUS_CHANNEL_H
#define SOFT_BUS_CHANNEL_H
#include <stdint.h>
#include <stdbool.h>
typedef struct {
int32_t (*openChannel)(const char *connectParams, int64_t requestId, int64_t *returnChannelId);
void (*closeChannel)(int64_t channelId);
int32_t (*sendMsg)(int64_t channelId, const uint8_t *data, uint32_t dataLen);
void (*setAuthResult)(int64_t channelId);
char *(*getLocalAuthInfo)();
} SoftBus;
int32_t InitSoftBusChannelModule(void (*onChannelOpened)(int64_t, int64_t, const char *, uint32_t, bool),
void (*onChannelClosed)(int64_t, int64_t),
void (*onMsgReceived)(int64_t, const uint8_t *, uint32_t),
void (*onServiceDied)());
void DestroySoftBusChannelModule();
SoftBus *GetSoftBusInstance();
bool IsSoftBusChannelSupported();
#endif

View File

@ -0,0 +1,242 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMMON_DEFS_H
#define COMMON_DEFS_H
#include "device_auth.h"
#include "device_auth_defines.h"
#include "json_utils.h"
#define FIELD_ADD_TYPE "addType"
#define FIELD_ADD_ID "addId"
#define FIELD_ADD_KEY "addKey"
#define FIELD_AUTH_DATA "authData"
#define FIELD_AUTH_RETURN "authReturn"
#define FIELD_AUTH_ID "authId"
#define FIELD_AUTH_PK "authPk"
#define FIELD_ADD_AUTH_INFO "addAuthInfo"
#define FIELD_ADD_RETURN "addReturn"
#define FIELD_APP_ID "appId"
#define FIELD_BIND_SESSION_TYPE "bindSessionType"
#define FIELD_CHALLENGE "challenge"
#define FIELD_CHANNEL_ID "channelId"
#define FIELD_CONN_DEVICE_ID "connDeviceId"
#define FIELD_CONNECT_PARAMS "connectParams"
#define FIELD_CURRENT_VERSION "currentVersion"
#define FIELD_DELETE_ID "deleteId"
#define FIELD_ENC_AUTH_TOKEN "encAuthToken"
#define FIELD_ENC_RESULT "encResult"
#define FIELD_ENC_DATA "encData"
#define FIELD_EPK "epk"
#define FIELD_EPK_LEN "epkLen"
#define FIELD_EX_AUTH_INFO "exAuthInfo"
#define FIELD_EXPIRE_TIME "expireTime"
#define FIELD_ERROR_CODE "errorCode"
#define FIELD_GROUP_INFO "groupInfo"
#define FIELD_GROUP_MANAGERS "groupManagers"
#define FIELD_GROUP_NAME "groupName"
#define FIELD_GROUP_OP "groupOp"
#define FIELD_GROUP_TYPE "groupType"
#define FIELD_GROUP_VISIBILITY "groupVisibility"
#define FIELD_IS_ADMIN "isAdmin"
#define FIELD_IS_ACCOUNT_BIND "isAccountBind"
#define FIELD_IS_FORCE_DELETE "isForceDelete"
#define FIELD_IS_CREDENTIAL_EXISTS "isCredentialExists"
#define FIELD_KCF_DATA "kcfData"
#define FIELD_KEY_TYPE "keyType"
#define FIELD_MESSAGE "message"
#define FIELD_GROUP_ERROR_MSG "groupErrorMsg"
#define FIELD_MIN_VERSION "minVersion"
#define FIELD_GROUP_AND_MODULE_VERSION "groupAndModuleVersion"
#define FIELD_NONCE "nonce"
#define FIELD_OPERATION_CODE "operationCode"
#define FIELD_OPERATION_PARAMS "operationParams"
#define FIELD_OWNER_ID "ownerId"
#define FIELD_OWNER_NAME "ownerName"
#define FIELD_PERMISSION "Permission"
#define FIELD_PAYLOAD "payload"
#define FIELD_PEER_DEVICE_ID "peerDeviceId"
#define FIELD_PIN_CODE "pinCode"
#define FIELD_PUBLIC_KEY "publicKey"
#define FIELD_PK_INFO "pkInfo"
#define FIELD_PKG_NAME "pkgName"
#define FIELD_SELF_AUTH_ID "selfAuthId"
#define FIELD_SELF_DEVICE_ID "selfDeviceId"
#define FIELD_REQUEST_ID "requestId"
#define FIELD_RECEIVED_DATA "receivedData"
#define FIELD_RETURN_CODE "returnCode"
#define FIELD_RETURN_DATA "returnData"
#define FIELD_RETURN_CODE_MAC "returnCodeMac"
#define FIELD_RMV_TYPE "rmvType"
#define FIELD_RMV_ID "rmvId"
#define FIELD_RMV_AUTH_INFO "rmvAuthInfo"
#define FIELD_RMV_RETURN "rmvReturn"
#define FIELD_SALT "salt"
#define FIELD_ISO_SALT "isoSalt"
#define FIELD_SEED "seed"
#define FIELD_SELF_TYPE "selfType"
#define FIELD_SEND_TO_PEER "sendToPeer"
#define FIELD_SEND_TO_SELF "sendToSelf"
#define FIELD_SHARED_USER_ID_LIST "sharedUserIdList"
#define FIELD_SUPPORT_256_MOD "support256mod"
#define FIELD_TOKEN "token"
#define FIELD_IS_UUID "uuIdAsDeviceId"
#define FIELD_VERSION "version"
#define FIELD_MK_AGREE_MSG "mkaMsg"
#define AUTH_FORM_INVALID_TYPE -1
#define AUTH_FORM_ACCOUNT_UNRELATED 0
#define AUTH_FORM_IDENTICAL_ACCOUNT 1
#define AUTH_FORM_ACROSS_ACCOUNT 2
#define INVALID_MODULE_TYPE -1
#define GROUP_ERR_MSG 0x8080
/* GroupVisibility */
#define ALL_GROUP_VISIBILITY -2
#define GROUP_VISIBILITY_PRIVATE 0
#define GROUP_VISIBILITY_ALLOW_LIST 1
#define GROUP_VISIBILITY_SIGNATURE 2
#define GROUP_VISIBILITY_SYSTEM 4
#define GROUP_VISIBILITY_PRIVILEGE 8
#define GROUP_VISIBILITY_PUBLIC -1
#define CLIENT 1
#define SERVER 0
#define CREATE_KEY_PAIR 1
#define DELETE_KEY_PAIR 2
/* DefaultValue */
#define DEFAULT_MEMORY_SIZE 64
#define DEFAULT_USER_ID 0
#define DEFAULT_REQUEST_ID 0
#define DEFAULT_CHANNEL_ID -1
#define DEFAULT_EXPIRE_TIME 90
#define GROUP_MANAGER_PACKAGE_NAME "com.huawei.devicegroupmanage"
#define DEFAULT_RETURN_KEY_LENGTH 32
#define ERR_AUTH_FORM 0
#define MAX_BUFFER_LEN 1024
#define MAX_AUTH_ID_LEN 256
typedef enum {
ALL_GROUP = 0,
IDENTICAL_ACCOUNT_GROUP = 1,
PEER_TO_PEER_GROUP = 256,
COMPATIBLE_GROUP = 512,
ACROSS_ACCOUNT_AUTHORIZE_GROUP = 1282
} GroupType;
typedef enum {
NO_CHANNEL = 1,
SERVICE_CHANNEL = 2,
SOFT_BUS = 3,
} ChannelType;
typedef enum {
SYMMETRIC = 0,
ASYMMETRIC = 1,
} CredentialType;
#define MAX_IN_PARAM_LEN 4096
#define CHECK_PTR_RETURN_NULL(ptr, paramTag) \
do { \
if ((ptr) == NULL) { \
LOGE("%s is null ptr", (paramTag)); \
return NULL; \
} \
} while (0)
#define CHECK_PTR_RETURN_ERROR_CODE(ptr, paramTag) \
do { \
if ((ptr) == NULL) { \
LOGE("%s is null ptr", (paramTag)); \
return HC_ERR_NULL_PTR; \
} \
} while (0)
#define CHECK_PTR_RETURN_NONE(ptr, paramTag) \
do { \
if ((ptr) == NULL) { \
LOGE("%s is null ptr", (paramTag)); \
return; \
} \
} while (0)
#define GOTO_IF_ERR(x) do { \
int32_t res = x; \
if ((res) != HC_SUCCESS) { \
goto err; \
} \
} while (0)
#define GOTO_ERR_AND_SET_RET(x, res) do { \
res = x; \
if ((res) != HC_SUCCESS) { \
goto err; \
} \
} while (0)
#define RETURN_IF_ERR(x) do { \
int32_t res = x; \
if ((res) != HC_SUCCESS) { \
return res; \
} \
} while (0)
typedef struct AuthModuleBaseT {
int moduleType;
int (*createTask)(int *, const CJson *in, CJson *out);
int (*processTask)(int, const CJson *in, CJson *out, int *status);
void (*destroyTask)(int);
void (*destroyModule)(struct AuthModuleBaseT *module);
} AuthModuleBase;
typedef enum {
DAS_MODULE = 0x0001,
TCIS_MODULE = 0x0010,
} EnumModuleType;
typedef enum {
CONTINUE = 0,
IGNORE_MSG = 1,
FINISH,
} TaskStatus;
typedef enum {
CODE_NULL = 0,
OP_BIND = 1,
AUTHENTICATE = 2,
ADD_AUTH_INFO = 3,
REMOVE_AUTH_INFO = 4,
OP_UNBIND = 5,
AUTH_KEY_AGREEMENT = 6,
REGISTER = 7,
SECURE_CLONE = 8,
} OperationCode;
typedef struct {
int64_t requestId;
int32_t type;
int64_t sessionId;
} RequestInfo;
typedef struct {
char *appId;
DeviceAuthCallback *callback;
} CallbackEntry;
#endif

View File

@ -0,0 +1,121 @@
/*
* 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 DATABASE_H
#define DATABASE_H
#include "hc_string.h"
#include "hc_tlv_parser.h"
#include "hc_vector.h"
#define MAX_EXPIRE_TIME 90
DECLARE_HC_VECTOR(StringVector, HcString)
DECLARE_HC_VECTOR(Int64Vector, int64_t)
typedef struct {
HcString name; /* group name */
HcString id; /* group id */
int32_t type; /* including identical account group(1), peer to peer group(256), across account group(1282) */
int32_t visibility; /* visibility of the group */
int32_t expireTime; /* the time of group expired, unit day, user config */
int64_t userId; /* user account id */
Int64Vector sharedUserIdVec; /* shared user account id vector */
StringVector managers; /* group manager vector, group manager can add and delete members, index 0 is the owner */
StringVector friends; /* group friend vector, group friend can query group information */
} TrustedGroupEntry;
DECLARE_HC_VECTOR(TrustedGroupTable, TrustedGroupEntry*)
typedef struct {
TrustedGroupEntry* groupEntry;
HcString udid; /* unique device id */
HcString authId; /* id by service defined for authentication */
HcString serviceType; /* compatible with previous versions, the value is the same as groupId */
HcParcel ext; /* for caching extern data, user data */
uint8_t credential; /* 1 - asymmetrical, 2 - symmetrical */
uint8_t devType; /* 0 - accessory, 1 - controller, 2 - proxy */
int64_t userId; /* user account id */
uint64_t lastTm; /* accessed time of the device of the auth information, absolute time */
} TrustedDeviceEntry;
DECLARE_HC_VECTOR(TrustedDeviceTable, TrustedDeviceEntry)
typedef struct {
DECLARE_TLV_STRUCT(9)
TlvString name;
TlvString id;
TlvUint32 type;
TlvInt32 visibility;
TlvInt32 expireTime;
TlvInt64 userId;
TlvBuffer sharedUserIdVec;
TlvBuffer managers;
TlvBuffer friends;
} TlvGroupElement;
DECLEAR_INIT_FUNC(TlvGroupElement)
DECLARE_TLV_VECTOR(TlvGroupVec, TlvGroupElement)
typedef struct {
uint8_t credential;
uint8_t devType;
int64_t userId;
uint64_t lastTm;
} DevAuthFixedLenInfo;
DECLARE_TLV_FIX_LENGTH_TYPE(TlvDevAuthFixedLenInfo, DevAuthFixedLenInfo)
DECLEAR_INIT_FUNC(TlvDevAuthFixedLenInfo)
typedef struct {
DECLARE_TLV_STRUCT(6)
TlvString groupId;
TlvString udid;
TlvString authId;
TlvString serviceType;
TlvBuffer ext;
TlvDevAuthFixedLenInfo info;
} TlvDevAuthElement;
DECLEAR_INIT_FUNC(TlvDevAuthElement)
DECLARE_TLV_VECTOR(TlvDevAuthVec, TlvDevAuthElement)
typedef struct {
DECLARE_TLV_STRUCT(3)
TlvInt32 version;
TlvGroupVec groups;
TlvDevAuthVec deviceAuthInfos;
} HCDataBaseV1;
DECLEAR_INIT_FUNC(HCDataBaseV1)
typedef struct {
HcString name; /* group name */
HcString id; /* group id */
HcString ownerName; /* group owner name */
int32_t type; /* group type, 0 - invalid, 1 - the same account, 2 - different account, 3 - none account(p2p) */
int32_t visibility; /* visibility of the group */
int32_t expireTime; /* the time of group expired, unit day, user config */
int64_t userId; /* user account id */
int64_t sharedUserId; /* shared user account id */
} GroupInfo;
DECLARE_HC_VECTOR(GroupInfoVec, void *)
typedef struct {
HcString udid; /* unique device id */
HcString authId; /* id by service defined for authentication */
uint8_t credential; /* 1 - asymmetrical, 2 - symmetrical */
uint8_t devType; /* 0 - accessory, 1 - controller, 2 - proxy */
int64_t userId; /* user account id */
HcString groupId; /* map the device authentication data for group */
HcString serviceType; /* compatible with previous versions, the value is the same as groupId */
} DeviceInfo;
DECLARE_HC_VECTOR(DeviceInfoVec, void *)
#endif

View File

@ -0,0 +1,107 @@
/*
* 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 DATABASE_MANAGER_H
#define DATABASE_MANAGER_H
#include <stdint.h>
#include <stdbool.h>
#include "broadcast_manager.h"
#include "common_defs.h"
#include "common_util.h"
#include "device_auth_defines.h"
#define HC_TRUST_DEV_ENTRY_MAX_NUM 101
#define HC_TRUST_GROUP_ENTRY_MAX_NUM 100
typedef struct {
int32_t type; /* group type */
int32_t visibility; /* group visibility */
char *udid; /* unique device id */
char *authId; /* id by service defined for authentication */
} GroupQueryParams;
#ifdef __cplusplus
extern "C" {
#endif
int32_t InitDatabase();
void DestroyDatabase();
Int64Vector CreateInt64Vector();
void DestroyInt64Vector(Int64Vector *obj);
int32_t AddGroup(const GroupInfo *addParams);
int32_t DelGroupByGroupId(const char *groupId);
int32_t AddTrustedDevice(const DeviceInfo *deviceInfo, const Uint8Buff *ext);
int32_t DelTrustedDevice(const char *udid, const char *groupId);
int32_t DelTrustedDeviceByAuthId(const char *authId, const char *groupId);
int32_t DeleteUserIdExpiredGroups(int64_t curUserId);
int32_t DeleteAllAccountGroup(void);
int32_t ChangeSharedUserIdVec(Int64Vector *sharedUserIdList);
int32_t GetLocalDevUdid(char **udid);
void DestroyUdid(char **udid);
void RegisterBroadcaster(const Broadcaster *broadcaster);
void DeregisterBroadcaster();
void RegGenerateGroupIdFunc(int32_t (*generateGroupId)(int64_t userId, int64_t sharedUserId, char **returnGroupId));
void DeregGenerateGroupIdFunc();
int32_t GetTrustedDevNumber();
int32_t GetGroupEntryByGroupId(const char *groupId, GroupInfo *returnGroupInfo);
int32_t GetGroupEntry(const char *groupId, const char *udid, GroupInfo *returnGroupInfo);
int32_t GetDeviceInfoForDevAuth(const char *udid, const char *groupId, DeviceInfo *deviceInfo);
int32_t GetDeviceInfoByAuthId(const char *authId, const char *groupId, DeviceInfo *deviceInfo);
int32_t GetJoinedGroupInfoVecByDevId(const GroupQueryParams *params, GroupInfoVec *vec);
int32_t GetGroupNumberByOwner(const char *ownerName);
int32_t GetCurDeviceNumByGroupId(const char *groupId);
int32_t CompareVisibility(const char *groupId, int groupVisibility);
bool IsGroupOwner(const char *groupId, const char *appId);
bool IsGroupAccessible(const char *groupId, const char *appId);
bool IsGroupEditAllowed(const char *groupId, const char *appId);
bool IsGroupExist(const char *ownerName, const char *groupName);
bool IsIdenticalGroupExist();
bool IsAcrossAccountGroupExist();
bool IsGroupExistByGroupId(const char *groupId);
bool IsTrustedDeviceExist(const char *udid);
bool IsTrustedDeviceInGroup(const char *groupId, const char *udid);
bool IsTrustedDeviceInGroupByAuthId(const char *groupId, const char *authId);
int32_t GetJoinedGroups(int groupType, GroupInfoVec *groupInfoVec);
int32_t GetGroupInfo(int groupType, const char *groupId, const char *groupName, const char *groupOwner,
GroupInfoVec *groupInfoVec);
int32_t GetRelatedGroups(const char *peerAuthId, GroupInfoVec *groupInfoVec);
int32_t GetTrustedDevices(const char *peerAuthId, DeviceInfoVec *deviceInfoVec);
int32_t AddGroupManager(const char *groupId, const char *managerAppId);
int32_t RemoveGroupManager(const char *groupId, const char *managerAppId);
int32_t GetGroupManagers(const char *groupId, CJson *returnManagers);
int32_t AddGroupFriend(const char *groupId, const char *friendAppId);
int32_t RemoveGroupFriend(const char *groupId, const char *friendAppId);
int32_t GetGroupFriends(const char *groupId, CJson *returnFriends);
GroupInfo *CreateGroupInfoStruct();
DeviceInfo *CreateDeviceInfoStruct();
void DestroyGroupInfoStruct(GroupInfo *groupInfo);
void DestroyDeviceInfoStruct(DeviceInfo *deviceInfo);
void CreateGroupInfoVecStruct(GroupInfoVec *vec);
void DestroyGroupInfoVecStruct(GroupInfoVec *vec);
void CreateDeviceInfoVecStruct(DeviceInfoVec *vec);
void DestroyDeviceInfoVecStruct(DeviceInfoVec *vec);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,395 @@
/*
* 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_defs.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_mutex.h"
#include "securec.h"
typedef struct {
char *appId;
DataChangeListener *listener;
} ListenerEntry;
DECLARE_HC_VECTOR(ListenerEntryVec, ListenerEntry)
IMPLEMENT_HC_VECTOR(ListenerEntryVec, ListenerEntry, 1)
static ListenerEntryVec g_listenerEntryVec;
static HcMutex *g_broadcastMutex = NULL;
static int32_t AddGroupId(const GroupInfo *groupInfo, CJson *message)
{
if (AddStringToJson(message, FIELD_GROUP_ID, StringGet(&groupInfo->id)) != HC_SUCCESS) {
LOGE("Failed to add groupId to message!");
return HC_ERR_JSON_FAIL;
}
return HC_SUCCESS;
}
static int32_t AddGroupType(const GroupInfo *groupInfo, CJson *message)
{
if (AddIntToJson(message, FIELD_GROUP_TYPE, groupInfo->type) != HC_SUCCESS) {
LOGE("Failed to add groupType to message!");
return HC_ERR_JSON_FAIL;
}
return HC_SUCCESS;
}
static int32_t AddGroupName(const GroupInfo *groupInfo, CJson *message)
{
if (AddStringToJson(message, FIELD_GROUP_NAME, StringGet(&groupInfo->name)) != HC_SUCCESS) {
LOGE("Failed to add groupName to message!");
return HC_ERR_JSON_FAIL;
}
return HC_SUCCESS;
}
static int32_t AddGroupOwner(const GroupInfo *groupInfo, CJson *message)
{
if (AddStringToJson(message, FIELD_GROUP_OWNER, StringGet(&groupInfo->ownerName)) != HC_SUCCESS) {
LOGE("Failed to add groupOwner to message!");
return HC_ERR_JSON_FAIL;
}
return HC_SUCCESS;
}
static int32_t AddGroupVisibility(const GroupInfo *groupInfo, CJson *message)
{
if (AddIntToJson(message, FIELD_GROUP_VISIBILITY, groupInfo->visibility) != HC_SUCCESS) {
LOGE("Failed to add groupVisibility to message!");
return HC_ERR_JSON_FAIL;
}
return HC_SUCCESS;
}
static int32_t GenerateMessage(const GroupInfo *groupInfo, char **returnGroupInfo)
{
CJson *message = CreateJson();
if (message == NULL) {
LOGE("Failed to allocate message memory!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t result;
if (((result = AddGroupId(groupInfo, message)) != HC_SUCCESS) ||
((result = AddGroupType(groupInfo, message)) != HC_SUCCESS) ||
((result = AddGroupName(groupInfo, message)) != HC_SUCCESS) ||
((result = AddGroupOwner(groupInfo, message)) != HC_SUCCESS) ||
((result = AddGroupVisibility(groupInfo, message)) != HC_SUCCESS)) {
FreeJson(message);
return result;
}
char *messageStr = PackJsonToString(message);
FreeJson(message);
if (messageStr == NULL) {
LOGE("Failed to convert json to string!");
return HC_ERR_JSON_FAIL;
}
*returnGroupInfo = messageStr;
return HC_SUCCESS;
}
static void PostOnGroupCreated(const GroupInfo *groupInfo)
{
if (groupInfo == NULL) {
LOGE("The groupEntry is NULL!");
return;
}
char *messageStr = NULL;
if (GenerateMessage(groupInfo, &messageStr) != HC_SUCCESS) {
return;
}
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (entry->listener != NULL) && (entry->listener->onGroupCreated != NULL)) {
LOGI("[Broadcaster]: Ready to broadcast the message to the listener! [AppId]: %s", entry->appId);
entry->listener->onGroupCreated(messageStr);
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
FreeJsonString(messageStr);
}
static void PostOnGroupDeleted(const GroupInfo *groupInfo)
{
if (groupInfo == NULL) {
LOGE("The groupEntry is NULL!");
return;
}
char *messageStr = NULL;
if (GenerateMessage(groupInfo, &messageStr) != HC_SUCCESS) {
return;
}
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (entry->listener != NULL) && (entry->listener->onGroupDeleted != NULL)) {
LOGI("[Broadcaster]: Ready to broadcast the message to the listener! [AppId]: %s", entry->appId);
entry->listener->onGroupDeleted(messageStr);
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
FreeJsonString(messageStr);
}
static void PostOnDeviceBound(const char *peerUdid, const GroupInfo *groupInfo)
{
if ((peerUdid == NULL) || (groupInfo == NULL)) {
LOGE("The peerUdid or groupEntry is NULL!");
return;
}
char *messageStr = NULL;
if (GenerateMessage(groupInfo, &messageStr) != HC_SUCCESS) {
return;
}
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (entry->listener != NULL) && (entry->listener->onDeviceBound != NULL)) {
LOGI("[Broadcaster]: Ready to broadcast the message to the listener! [AppId]: %s", entry->appId);
entry->listener->onDeviceBound(peerUdid, messageStr);
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
FreeJsonString(messageStr);
}
static void PostOnDeviceUnBound(const char *peerUdid, const GroupInfo *groupInfo)
{
if ((peerUdid == NULL) || (groupInfo == NULL)) {
LOGE("The peerUdid or groupEntry is NULL!");
return;
}
char *messageStr = NULL;
if (GenerateMessage(groupInfo, &messageStr) != HC_SUCCESS) {
return;
}
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (entry->listener != NULL) && (entry->listener->onDeviceUnBound != NULL)) {
LOGI("[Broadcaster]: Ready to broadcast the message to the listener! [AppId]: %s", entry->appId);
entry->listener->onDeviceUnBound(peerUdid, messageStr);
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
FreeJsonString(messageStr);
}
static void PostOnDeviceNotTrusted(const char *peerUdid)
{
if (peerUdid == NULL) {
LOGE("The peerUdid is NULL!");
return;
}
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (entry->listener != NULL) && (entry->listener->onDeviceNotTrusted != NULL)) {
LOGI("[Broadcaster]: Ready to broadcast the message to the listener! [AppId]: %s", entry->appId);
entry->listener->onDeviceNotTrusted(peerUdid);
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
}
static void PostOnLastGroupDeleted(const char *peerUdid, int groupType)
{
if (peerUdid == NULL) {
LOGE("The peerUdid is NULL!");
return;
}
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (entry->listener != NULL) && (entry->listener->onLastGroupDeleted != NULL)) {
LOGI("[Broadcaster]: Ready to broadcast the message to the listener! [AppId]: %s, [GroupType]: %d",
entry->appId, groupType);
entry->listener->onLastGroupDeleted(peerUdid, groupType);
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
}
static void PostOnTrustedDeviceNumChanged(int curTrustedDeviceNum)
{
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (entry->listener != NULL) && (entry->listener->onTrustedDeviceNumChanged != NULL)) {
LOGI("[Broadcaster]: Ready to broadcast the message to the listener! [AppId]: %s", entry->appId);
entry->listener->onTrustedDeviceNumChanged(curTrustedDeviceNum);
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
}
static int32_t UpdateListenerIfExist(const char *appId, const DataChangeListener *listener)
{
uint32_t index;
ListenerEntry *entry = NULL;
g_broadcastMutex->lock(g_broadcastMutex);
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if ((entry != NULL) && (strcmp(entry->appId, appId) == 0)) {
if (memcpy_s(entry->listener, sizeof(DataChangeListener),
listener, sizeof(DataChangeListener)) != HC_SUCCESS) {
g_broadcastMutex->unlock(g_broadcastMutex);
LOGE("Failed to copy listener!");
return HC_ERR_MEMORY_COPY;
}
g_broadcastMutex->unlock(g_broadcastMutex);
return HC_SUCCESS;
}
}
g_broadcastMutex->unlock(g_broadcastMutex);
return HC_ERR_LISTENER_NOT_EXIST;
}
static int32_t AddListenerIfNotExist(const char *appId, const DataChangeListener *listener)
{
uint32_t appIdLen = HcStrlen(appId) + 1;
char *copyAppId = (char *)HcMalloc(appIdLen, 0);
if (copyAppId == NULL) {
LOGE("Failed to allocate copyAppId memory!");
return HC_ERR_ALLOC_MEMORY;
}
if (strcpy_s(copyAppId, appIdLen, appId) != HC_SUCCESS) {
LOGE("Failed to copy appId!");
HcFree(copyAppId);
return HC_ERR_MEMORY_COPY;
}
DataChangeListener *copyListener = (DataChangeListener *)HcMalloc(sizeof(DataChangeListener), 0);
if (copyListener == NULL) {
LOGE("Failed to allocate saveCallback memory!");
HcFree(copyAppId);
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(copyListener, sizeof(DataChangeListener),
listener, sizeof(DataChangeListener)) != HC_SUCCESS) {
LOGE("Failed to copy listener!");
HcFree(copyAppId);
HcFree(copyListener);
return HC_ERR_MEMORY_COPY;
}
ListenerEntry entry;
entry.appId = copyAppId;
entry.listener = copyListener;
g_broadcastMutex->lock(g_broadcastMutex);
g_listenerEntryVec.pushBack(&g_listenerEntryVec, &entry);
g_broadcastMutex->unlock(g_broadcastMutex);
LOGI("[End]: Service register listener successfully!");
return HC_SUCCESS;
}
static Broadcaster g_broadcaster = {
.postOnGroupCreated = PostOnGroupCreated,
.postOnGroupDeleted = PostOnGroupDeleted,
.postOnDeviceBound = PostOnDeviceBound,
.postOnDeviceUnBound = PostOnDeviceUnBound,
.postOnDeviceNotTrusted = PostOnDeviceNotTrusted,
.postOnLastGroupDeleted = PostOnLastGroupDeleted,
.postOnTrustedDeviceNumChanged = PostOnTrustedDeviceNumChanged
};
bool IsBroadcastSupported()
{
return true;
}
int32_t InitBroadcastManager()
{
if (g_broadcastMutex == NULL) {
g_broadcastMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0);
if (g_broadcastMutex == NULL) {
LOGE("Failed to allocate broadcast mutex memory!");
return HC_ERR_ALLOC_MEMORY;
}
if (InitHcMutex(g_broadcastMutex) != HC_SUCCESS) {
LOGE("Init mutex failed");
HcFree(g_broadcastMutex);
g_broadcastMutex = NULL;
return HC_ERROR;
}
}
g_listenerEntryVec = CREATE_HC_VECTOR(ListenerEntryVec)
LOGI("[Broadcaster]: Init broadcast manager module successfully!");
return HC_SUCCESS;
}
void DestroyBroadcastManager()
{
uint32_t index;
ListenerEntry *entry = NULL;
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if (entry != NULL) {
HcFree(entry->appId);
HcFree(entry->listener);
}
}
DESTROY_HC_VECTOR(ListenerEntryVec, &g_listenerEntryVec)
if (g_broadcastMutex != NULL) {
DestroyHcMutex(g_broadcastMutex);
HcFree(g_broadcastMutex);
g_broadcastMutex = NULL;
}
}
Broadcaster *GetBroadcaster()
{
return &g_broadcaster;
}
int32_t AddListener(const char *appId, const DataChangeListener *listener)
{
if ((appId == NULL) || (listener == NULL)) {
LOGE("The input appId or listener is NULL!");
return HC_ERR_INVALID_PARAMS;
}
if (UpdateListenerIfExist(appId, listener) == HC_SUCCESS) {
LOGI("The listener associated with the appId already exists, so we choose to update the listener!");
return HC_SUCCESS;
}
return AddListenerIfNotExist(appId, listener);
}
int32_t RemoveListener(const char *appId)
{
if (appId == NULL) {
LOGE("The input appId is NULL!");
return HC_ERR_INVALID_PARAMS;
}
uint32_t index;
ListenerEntry *entry = NULL;
FOR_EACH_HC_VECTOR(g_listenerEntryVec, index, entry) {
if (strcmp(entry->appId, appId) == 0) {
HcFree(entry->appId);
HcFree(entry->listener);
ListenerEntry tempEntry;
HC_VECTOR_POPELEMENT(&g_listenerEntryVec, &tempEntry, index);
LOGI("[End]: Service deregister listener successfully!");
return HC_SUCCESS;
}
}
LOGI("[End]: Although the listener does not exist, we still believe it is correct to deregister the listener!");
return HC_SUCCESS;
}

View File

@ -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 "broadcast_manager.h"
#include "device_auth_defines.h"
#include "hc_log.h"
bool IsBroadcastSupported()
{
return false;
}
int32_t InitBroadcastManager()
{
return HC_SUCCESS;
}
void DestroyBroadcastManager()
{
return;
}
Broadcaster *GetBroadcaster()
{
return NULL;
}
int32_t AddListener(const char *appId, const DataChangeListener *listener)
{
(void)appId;
(void)listener;
LOGE("Broadcast manager is not supported!");
return HC_ERR_NOT_SUPPORT;
}
int32_t RemoveListener(const char *appId)
{
(void)appId;
LOGE("Broadcast manager is not supported!");
return HC_ERR_NOT_SUPPORT;
}

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.
*/
#include "callback_manager.h"
#include "hc_log.h"
bool ProcessTransmitCallback(int64_t requestId, const uint8_t *data, uint32_t dataLen,
const DeviceAuthCallback *callback)
{
LOGI("[OnTransmit]: We're going to notify the service! [RequestId]: %lld, [DataLen]: %d", requestId, dataLen);
if ((callback != NULL) && (callback->onTransmit != NULL)) {
if (callback->onTransmit(requestId, data, dataLen)) {
LOGI("[OnTransmit]: We notify the service successfully! [RequestId]: %lld, [DataLen]: %d",
requestId, dataLen);
return true;
}
LOGE("[OnTransmit]: An error occurs when the service channel sends data! [RequestId]: %lld, [DataLen]: %d",
requestId, dataLen);
return false;
}
LOGE("[OnTransmit]: Currently, the service callback is NULL! [RequestId]: %lld, [DataLen]: %d", requestId, dataLen);
return false;
}
void ProcessSessionKeyCallback(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen,
const DeviceAuthCallback *callback)
{
const char *isSessionKeyExist = (sessionKeyLen > 0) ? "true" : "false";
LOGI("[OnSessionKeyReturned]: We're going to notify the service! [RequestId]: %lld, [IsSessionKeyExist]: %s",
requestId, isSessionKeyExist);
if ((callback != NULL) && (callback->onSessionKeyReturned != NULL)) {
(void)callback->onSessionKeyReturned(requestId, sessionKey, sessionKeyLen);
LOGI("[OnSessionKeyReturned]: We notify the service successfully! [RequestId]: %lld, [IsSessionKeyExist]: %s",
requestId, isSessionKeyExist);
return;
}
LOGE("[OnSessionKeyReturned]: Currently, the service callback is NULL! [RequestId]: %lld, [IsSessionKeyExist]: %s",
requestId, isSessionKeyExist);
}
void ProcessFinishCallback(int64_t requestId, int operationCode, const char *returnData,
const DeviceAuthCallback *callback)
{
LOGI("[OnFinish]: We're going to notify the service! [RequestId]: %lld, [OperationCode]: %d",
requestId, operationCode);
if ((callback != NULL) && (callback->onFinish != NULL)) {
callback->onFinish(requestId, operationCode, returnData);
LOGI("[End]: [OnFinish]: We notify the service successfully! [RequestId]: %lld, [OperationCode]: %d",
requestId, operationCode);
return;
}
LOGE("[End]: [OnFinish]: Currently, the service callback is NULL! [RequestId]: %lld, [OperationCode]: %d",
requestId, operationCode);
}
void ProcessErrorCallback(int64_t requestId, int operationCode, int errorCode, const char *errorReturn,
const DeviceAuthCallback *callback)
{
LOGI("[OnError]: We're going to notify the service! [RequestId]: %lld, [OperationCode]: %d, [errorCode]: %d",
requestId, operationCode, errorCode);
if ((callback != NULL) && (callback->onError != NULL)) {
callback->onError(requestId, operationCode, errorCode, errorReturn);
LOGI("[End]: [OnError]: We notify the service successfully! "
"[RequestId]: %lld, [OperationCode]: %d, [errorCode]: %d", requestId, operationCode, errorCode);
return;
}
LOGE("[End]: [OnError]: Currently, the service callback is NULL! "
"[RequestId]: %lld, [OperationCode]: %d, [errorCode]: %d", requestId, operationCode, errorCode);
}
char *ProcessRequestCallback(int64_t requestId, int operationCode, const char *reqParams,
const DeviceAuthCallback *callback)
{
LOGI("[OnRequest]: We're going to notify the service! [RequestId]: %lld, [OperationCode]: %d",
requestId, operationCode);
if ((callback != NULL) && (callback->onRequest != NULL)) {
char *returnData = callback->onRequest(requestId, operationCode, reqParams);
LOGI("[OnRequest]: We notify the service successfully! [RequestId]: %lld, [OperationCode]: %d",
requestId, operationCode);
return returnData;
}
LOGE("[OnRequest]: Currently, the service callback is NULL! [RequestId]: %lld, [OperationCode]: %d",
requestId, operationCode);
return NULL;
}

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