update openharmony 1.0.1

This commit is contained in:
mamingshuai
2021-03-11 18:45:51 +08:00
parent d110d2cd61
commit 3f130bf3ff
50 changed files with 1217 additions and 425 deletions
-13
View File
@@ -1,13 +0,0 @@
### 该问题是怎么引起的?
### 重现步骤
### 报错信息
-15
View File
@@ -1,15 +0,0 @@
### 相关的Issue
### 原因(目的、解决的问题等)
### 描述(做了什么,变更了什么)
### 测试用例(新增、改动、可能影响的功能)
+64 -57
View File
@@ -16,67 +16,62 @@ import("//build/lite/ndk/ndk.gni")
if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "linux") {
config("softbus_lite_config") {
include_dirs = [
"//foundation/communication/services/softbus_lite/discovery/coap/include",
"//foundation/communication/services/softbus_lite/os_adapter/include",
"//foundation/communication/interfaces/kits/softbus_lite/discovery",
"//foundation/communication/softbus_lite/discovery/coap/include",
"//foundation/communication/softbus_lite/os_adapter/include",
"//foundation/communication/softbus_lite/interfaces/kits/discovery",
"//third_party/cJSON",
"//third_party/bounds_checking_function/include",
"//foundation/communication/services/softbus_lite/discovery/discovery_service/include",
"//foundation/communication/services/softbus_lite/authmanager/include",
"//base/startup/interfaces/kits/syspara_lite",
"//foundation/communication/services/softbus_lite/trans_service/include/libdistbus",
"//foundation/communication/services/softbus_lite/trans_service/include/utils",
"//foundation/communication/services/softbus_lite/trans_service/source/libdistbus",
"//foundation/communication/services/softbus_lite/trans_service/source/utils",
"//foundation/communication/softbus_lite/discovery/discovery_service/include",
"//foundation/communication/softbus_lite/authmanager/include",
"//base/startup/syspara_lite/interfaces/kits",
"//foundation/communication/softbus_lite/trans_service/include/libdistbus",
"//foundation/communication/softbus_lite/trans_service/include/utils",
"//foundation/communication/softbus_lite/trans_service/source/libdistbus",
"//foundation/communication/softbus_lite/trans_service/source/utils",
"//kernel/liteos_a/lib/libsec/include",
"//foundation/communication/interfaces/kits/softbus_lite/transport",
"//base/security/interfaces/innerkits/hichainsdk_lite",
"//foundation/communication/softbus_lite/interfaces/kits/transport",
"//base/security/deviceauth/interfaces/innerkits/deviceauth_lite",
"//third_party/mbedtls/include",
"//base/security/frameworks/hichainsdk_lite/source/huks_adapter/",
"//base/security/interfaces/kits/iam_lite",
"//base/security/deviceauth/frameworks/deviceauth_lite/source/huks_adapter/",
"//base/security/permission/interfaces/kits/permission_lite",
]
if (ohos_kernel_type == "liteos_a") {
include_dirs += [ "//third_party/wpa_supplicant/wpa_supplicant-2.9/src/" ]
}
defines = [
"_GNU_SOURCE",
"_SCANTY_MEMORY_",
]
defines += [ "SOFTBUS_DEBUG" ]
include_dirs += [
"//kernel/liteos_a/kernel/include",
"//kernel/liteos_a/arch/arm/arm/include",
"//kernel/liteos_a/kernel/include",
"//kernel/liteos_a/kernel/common",
"//kernel/liteos_a/platform/board/hi3516dv300/include",
"//kernel/liteos_a/platform/include",
"//kernel/liteos_a/kernel/base/include",
"//kernel/liteos_a/kernel/include",
]
include_dirs += []
}
softbus_lite_sources = [
"//foundation/communication/services/softbus_lite/authmanager/source/auth_conn.c",
"//foundation/communication/services/softbus_lite/authmanager/source/auth_interface.c",
"//foundation/communication/services/softbus_lite/authmanager/source/bus_manager.c",
"//foundation/communication/services/softbus_lite/authmanager/source/msg_get_deviceid.c",
"//foundation/communication/services/softbus_lite/authmanager/source/wifi_auth_manager.c",
"//foundation/communication/services/softbus_lite/discovery/coap/source/coap_adapter.c",
"//foundation/communication/services/softbus_lite/discovery/coap/source/coap_discover.c",
"//foundation/communication/services/softbus_lite/discovery/coap/source/coap_socket.c",
"//foundation/communication/services/softbus_lite/discovery/coap/source/json_payload.c",
"//foundation/communication/services/softbus_lite/discovery/coap/source/nstackx_common.c",
"//foundation/communication/services/softbus_lite/discovery/coap/source/nstackx_device.c",
"//foundation/communication/services/softbus_lite/discovery/discovery_service/source/coap_service.c",
"//foundation/communication/services/softbus_lite/discovery/discovery_service/source/common_info_manager.c",
"//foundation/communication/services/softbus_lite/discovery/discovery_service/source/discovery_service.c",
"//foundation/communication/services/softbus_lite/os_adapter/source/L1/os_adapter.c",
"//foundation/communication/services/softbus_lite/trans_service/source/libdistbus/auth_conn_manager.c",
"//foundation/communication/services/softbus_lite/trans_service/source/libdistbus/tcp_session.c",
"//foundation/communication/services/softbus_lite/trans_service/source/libdistbus/tcp_session_manager.c",
"//foundation/communication/services/softbus_lite/trans_service/source/libdistbus/trans_lock.c",
"//foundation/communication/services/softbus_lite/trans_service/source/utils/aes_gcm.c",
"//foundation/communication/services/softbus_lite/trans_service/source/utils/message.c",
"//foundation/communication/services/softbus_lite/trans_service/source/utils/tcp_socket.c",
"//foundation/communication/softbus_lite/authmanager/source/auth_conn.c",
"//foundation/communication/softbus_lite/authmanager/source/auth_interface.c",
"//foundation/communication/softbus_lite/authmanager/source/bus_manager.c",
"//foundation/communication/softbus_lite/authmanager/source/msg_get_deviceid.c",
"//foundation/communication/softbus_lite/authmanager/source/wifi_auth_manager.c",
"//foundation/communication/softbus_lite/discovery/coap/source/coap_adapter.c",
"//foundation/communication/softbus_lite/discovery/coap/source/coap_discover.c",
"//foundation/communication/softbus_lite/discovery/coap/source/coap_socket.c",
"//foundation/communication/softbus_lite/discovery/coap/source/json_payload.c",
"//foundation/communication/softbus_lite/discovery/coap/source/nstackx_common.c",
"//foundation/communication/softbus_lite/discovery/coap/source/nstackx_device.c",
"//foundation/communication/softbus_lite/discovery/discovery_service/source/coap_service.c",
"//foundation/communication/softbus_lite/discovery/discovery_service/source/common_info_manager.c",
"//foundation/communication/softbus_lite/discovery/discovery_service/source/discovery_service.c",
"//foundation/communication/softbus_lite/os_adapter/source/L1/os_adapter.c",
"//foundation/communication/softbus_lite/trans_service/source/libdistbus/auth_conn_manager.c",
"//foundation/communication/softbus_lite/trans_service/source/libdistbus/tcp_session.c",
"//foundation/communication/softbus_lite/trans_service/source/libdistbus/tcp_session_manager.c",
"//foundation/communication/softbus_lite/trans_service/source/libdistbus/trans_lock.c",
"//foundation/communication/softbus_lite/trans_service/source/utils/aes_gcm.c",
"//foundation/communication/softbus_lite/trans_service/source/utils/message.c",
"//foundation/communication/softbus_lite/trans_service/source/utils/tcp_socket.c",
]
cflags = [ "-Wall" ]
@@ -86,34 +81,46 @@ if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "linux") {
sources = softbus_lite_sources
public_configs = [ ":softbus_lite_config" ]
public_deps = [
"//base/security/frameworks/hichainsdk_lite/source:hichainsdk",
"//base/security/services/iam_lite/pms_client:pms_client",
"//base/security/deviceauth/frameworks/deviceauth_lite/source:hichainsdk",
"//base/security/permission/services/permission_lite/pms_client:pms_client",
"//build/lite/config/component/cJSON:cjson_shared",
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/cJSON:cjson_shared",
]
if (ohos_kernel_type == "liteos_a") {
public_deps +=
[ "//third_party/wpa_supplicant/wpa_supplicant-2.9:wpa_supplicant" ]
}
out_dir = rebase_path(root_build_dir)
ldflags = [ "-L${out_dir}" ]
if (ohos_kernel_type == "liteos_a") {
ldflags += [ "-lwpa_client" ]
}
}
ndk_lib("softbus_ndk") {
lib_extension = ".so"
deps = [ ":softbus_lite" ]
head_files = [
"//foundation/communication/interfaces/kits/softbus_lite/transport",
"//foundation/communication/interfaces/kits/softbus_lite/discovery",
"//foundation/communication/softbus_lite/interfaces/kits/transport",
"//foundation/communication/softbus_lite/interfaces/kits/discovery",
]
}
} else {
ndk_lib("discovery_ndk") {
deps = [
"//foundation/communication/services/softbus_lite/discovery:discovery",
]
deps = [ "//foundation/communication/softbus_lite/discovery:discovery" ]
head_files =
[ "//foundation/communication/interfaces/kits/softbus_lite/discovery" ]
[ "//foundation/communication/softbus_lite/interfaces/kits/discovery" ]
}
ndk_lib("trans_service_ndk") {
deps = [ "//foundation/communication/services/softbus_lite/trans_service:trans_service" ]
deps = [
"//foundation/communication/softbus_lite/trans_service:trans_service",
]
head_files =
[ "//foundation/communication/interfaces/kits/softbus_lite/transport" ]
[ "//foundation/communication/softbus_lite/interfaces/kits/transport" ]
}
}
Executable → Regular
View File
+60
View File
@@ -0,0 +1,60 @@
# Intelligent Soft Bus<a name="EN-US_TOPIC_0000001051344287"></a>
- [Overview](#section11660541593)
- [Directory Structure](#section1464106163817)
- [Constraints](#section1718733212019)
- [Usage](#section167037358130)
- [Repositories Involved](#section4499619123117)
## Overview<a name="section11660541593"></a>
The use of different communication modes \(such as USB, WLAN, and Bluetooth\) varies greatly and is complex. In addition, the convergence, sharing, and conflicts between communication links cannot be resolved, and communication security is difficult to guarantee. The distributed communication subsystem manages unified distributed communication between near-field devices and provides device discovery and data transmission APIs that apply to all links. Currently, the following features are available:
- Service publishing: After a service is published, peripheral devices can discover and use it.
- Data transmission: A session is established based on the service name and device ID to transmit data between services.
- Security: Communication data is encrypted.
You can use APIs of the distributed communication subsystem to implement fast and secure communication between devices without caring about management of communication details, thereby achieving cross-platform development.
## Directory Structure<a name="section1464106163817"></a>
```
/foundation/communication/softbus_lite/
├── authmanager # Device authentication mechanism and device knowledge library management
├── discovery # Device discovery based on CoAP
├── os_adapter # OS adaption code
└── trans_service # Authentication and transmission channels
```
## Constraints<a name="section1718733212019"></a>
**Language**: C
**Networking**: Devices must be in the same LAN.
**Operating system**: OpenHarmony
## Usage<a name="section167037358130"></a>
1. **Device discovery**
When using device discovery, ensure that the device to perform a discovery and the device to discover are in the same LAN and the devices can receive packets from each other.
a. After a device sends a discovery request, it uses Constrained Application Protocol \(CoAP\) to send a broadcast packet in the LAN.
b. The discovered device uses the **PublishService** API to publish services. After receiving the broadcast packet, the device sends a CoAP unicast packet to the device that performs the discovery.
c. After receiving the packet, the device that performs the discovery updates device information.
**2. Transmission**
The soft bus provides unified session-based transmission. Services can receive and send data or obtain basic attributes through **sessionId**. Currently, services can determine whether to accept a received session based on the service requirements and session attributes. Currently, sessions cannot be enabled.
## Repositories Involved<a name="section4499619123117"></a>
communication\_softbus\_lite
communication\_ipc\_lite
communication\_wifi\_aware
+60
View File
@@ -0,0 +1,60 @@
# 分布式软总线子系统<a name="ZH-CN_TOPIC_0000001051344287"></a>
- [简介](#section11660541593)
- [目录](#section1464106163817)
- [约束](#section1718733212019)
- [使用](#section167037358130)
- [涉及仓](#section4499619123117)
## 简介<a name="section11660541593"></a>
设备通信方式多种多样\(USB/WIFI/BT等\),不同通信方式使用差异很大且繁琐,同时通信链路的融合共享和冲突无法处理,通信安全问题也不好保证。本项目致力于实现近场设备间统一的分布式通信能力管理,提供不区分链路的设备发现和传输接口。目前实现能力包含:
- 服务发布:服务发布后周边的设备可以发现并使用服务。
- 数据传输:根据服务的名称和设备ID建立一个会话,就可以实现服务间的传输功能。
- 安全:提供通信数据的加密能力。
开发者通过使用项目的API实现设备间高速安全的通信,不用关心通信细节管理,进而实现业务开发的跨平台能力。
## 目录<a name="section1464106163817"></a>
```
/foundation/communication/softbus_lite/
├── authmanager #提供设备认证机制和设备知识库管理。
├── discovery #提供基于coap协议的设备发现机制。
├── os_adapter #提供操作系统接口适配层
└── trans_service #提供认证和传输通道。
```
## 约束<a name="section1718733212019"></a>
**语言限制:**C语言。
**组网环境:**必须确保设备在同一个局域网中。
**操作系统限制:**OpenHarmony操作系统。
## 使用<a name="section167037358130"></a>
1. **设备发现**
用户使用发现功能时,需要保证发现端设备与被发现端设备在同一个局域网内,并且互相能收到对方以下流程的报文。
(1)发现端设备,发起discover请求后,使用coap协议在局域网内发送广播。
(2)被发现端设备使用PublishService接口发布服务,接收端收到广播后,发送coap协议单播给发现端。
(3)发现端设备收到报文会更新设备信息。
**2. 传输**
软总线提供统一的基于Session的传输功能,业务可以通过sessionId收发数据或获取其相关基本属性。当前本项目只实现被动接收Session连接的功能,业务可根据自身需要及Session自身属性判断是否接受此Session,如不接受,可以主动拒绝此连接。本项目暂未提供打开Session的相关能力。
## 涉及仓<a name="section4499619123117"></a>
communication\_softbus\_lite
communication\_ipc\_lite
communication\_wifi\_aware
+7 -7
View File
@@ -21,12 +21,12 @@ if (ohos_kernel_type == "liteos_m") {
include_dirs = [
"include",
"//foundation/communication/services/softbus_lite/discovery/discovery_service/include",
"//foundation/communication/services/softbus_lite/os_adapter/include",
"//base/security/interfaces/innerkits/hichainsdk_lite",
"//foundation/communication/services/softbus_lite/trans_service/include/utils",
"//foundation/communication/services/softbus_lite/trans_service/include/libdistbus",
"//foundation/communication/interfaces/kits/softbus_lite/transport",
"//foundation/communication/softbus_lite/discovery/discovery_service/include",
"//foundation/communication/softbus_lite/os_adapter/include",
"//foundation/communication/softbus_lite/trans_service/include/utils",
"//foundation/communication/softbus_lite/trans_service/include/libdistbus",
"//foundation/communication/softbus_lite/interfaces/kits/transport",
"//base/security/deviceauth/interfaces/innerkits/deviceauth_lite",
"//third_party/cJSON",
"$ohos_third_party_dir/mbedtls/include",
]
@@ -45,6 +45,6 @@ if (ohos_kernel_type == "liteos_m") {
output_name = "authmanager"
sources = authmanager_sources
public_configs = [ ":authmanager_config" ]
public_deps = [ "//third_party/cJSON:cjson_shared" ]
public_deps = [ "//build/lite/config/component/cJSON:cjson_shared" ]
}
}
-1
View File
@@ -18,7 +18,6 @@
#include "auth_conn.h"
#define AUTH_PIN_DEFAULT "softbus"
#define AUTH_DEFAULT_ID "default"
#define AUTH_DEFAULT_ID_LEN 7
#define AUTH_SESSION_KEY_LEN 16
View File
Executable → Regular
View File
+2 -7
View File
@@ -152,13 +152,8 @@ static void AuthGetProtocolParams(const struct session_identity *identity, int32
struct hc_pin *hcPin, struct operation_parameter *para)
{
(void)operationCode;
SOFTBUS_PRINT("[AUTH] AuthGetProtocolParams operationCode = %d\n", operationCode);
if (identity == NULL || hcPin == NULL || para == NULL) {
return;
}
hcPin->length = strlen(AUTH_PIN_DEFAULT);
if (memcpy_s(hcPin->pin, sizeof(hcPin->pin), AUTH_PIN_DEFAULT, sizeof(AUTH_PIN_DEFAULT)) != EOK) {
(void)hcPin;
if (identity == NULL || para == NULL) {
return;
}
-1
View File
@@ -81,7 +81,6 @@ int StopBus(void)
if (g_busStartFlag == 0) {
return 0;
}
AuthMngDeInit();
StopListener();
View File
-3
View File
@@ -14,9 +14,6 @@
*/
#include "wifi_auth_manager.h"
#include <stdlib.h>
#include "aes_gcm.h"
#include "auth_conn.h"
#include "auth_conn_manager.h"
+7 -7
View File
@@ -20,13 +20,13 @@ if (ohos_kernel_type == "liteos_m") {
include_dirs = [
"coap/include",
"discovery_service/include",
"//foundation/communication/interfaces/kits/softbus_lite/discovery",
"//foundation/communication/services/softbus_lite/os_adapter/include",
"//foundation/communication/services/softbus_lite/authmanager/include",
"//foundation/communication/interfaces/kits/wifi_lite/wifiservice",
"//foundation/communication/softbus_lite/interfaces/kits/discovery",
"//foundation/communication/softbus_lite/os_adapter/include",
"//foundation/communication/softbus_lite/authmanager/include",
"//foundation/communication/wifi_lite/interfaces/wifiservice",
"//third_party/bounds_checking_function/include",
"//base/startup/interfaces/kits/syspara_lite",
"//base/security/interfaces/innerkits/hichainsdk_lite",
"//base/startup/syspara_lite/interfaces/kits",
"//base/security/deviceauth/interfaces/innerkits/deviceauth_lite",
"//third_party/cJSON",
"$ohos_third_party_dir/lwip_sack/include",
]
@@ -52,6 +52,6 @@ if (ohos_kernel_type == "liteos_m") {
target_type = "static_library"
sources = discovery_sources
public_configs = [ ":discovery_config" ]
public_deps = [ "//third_party/cJSON:cjson_shared" ]
public_deps = [ "//build/lite/config/component/cJSON:cjson_shared" ]
}
}
View File
View File
View File
View File
View File
+372 -110
View File
@@ -27,11 +27,10 @@
#include "lwip/netifapi.h"
#include "wifi_device.h"
#include "wifi_hotspot_config.h"
#include <los_task.h>
#include <cmsis_os.h>
#else
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sys/ioctl.h>
@@ -39,6 +38,11 @@
#include <sys/socket.h>
#include <sys/types.h>
#endif
#if defined(__LITEOS_A__)
#include "common/wpa_ctrl.h"
#endif
#include <securec.h>
#define WIFI_QUEUE_SIZE 5
@@ -53,11 +57,9 @@ int g_queryIpFlag = -1;
unsigned int g_wifiTaskStart = 0;
WIFI_PROC_FUNC g_wifiCallback = NULL;
#define WLAN "wlan0"
#define ETH "eth0"
intptr_t g_coapTaskId = -1;
#define COAP_DEFAULT_PRIO 11
#define TEN_MS (10 * 1000)
#define HUNDRED_MS (100 * 1000)
typedef struct CoapRequest {
const char *remoteUrl;
char *data;
@@ -65,8 +67,44 @@ typedef struct CoapRequest {
const char *remoteIp;
} CoapRequest;
intptr_t g_msgQueTaskId = -1;
unsigned int g_terminalFlag = 0;
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
#define WLAN_NAME "wlan0"
static WifiEvent g_coapEventHandler = {0};
static void CoapConnectionChangedHandler(int state, WifiLinkedInfo* info);
osThreadId_t g_coapTaskId = NULL;
osThreadId_t g_msgQueTaskId = NULL;
#else
#define WLAN "wlan0"
#define ETH "eth0"
intptr_t g_coapTaskId = -1;
intptr_t g_msgQueTaskId = -1;
intptr_t g_queryIpTaskId = -1;
unsigned int g_updateIpFlag = 0;
typedef void *(*Runnable)(void *argv);
typedef struct ThreadAttr ThreadAttr;
struct ThreadAttr {
const char *name;
uint32_t stackSize;
uint8_t priority;
uint8_t reserved1;
uint16_t reserved2;
};
int CreateThread(Runnable run, void *argv, const ThreadAttr *attr, unsigned int *threadId)
{
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);
pthread_attr_setstacksize(&threadAttr, (attr->stackSize | MIN_STACK_SIZE));
struct sched_param sched = {attr->priority};
pthread_attr_setschedparam(&threadAttr, &sched);
int errCode = pthread_create((pthread_t *)threadId, &threadAttr, run, argv);
return errCode;
}
#endif
static int CoapSendRequest(const CoapRequest *coapRequest)
{
if (coapRequest == NULL || coapRequest->remoteUrl == NULL) {
@@ -167,7 +205,7 @@ L_COAP_ERR:
return NSTACKX_EFAILED;
}
void PostServiceDiscover(COAP_Packet *pkt)
void PostServiceDiscover(const COAP_Packet *pkt)
{
char *remoteUrl = NULL;
DeviceInfo deviceInfo;
@@ -245,8 +283,6 @@ void RegisterWifiCallback(WIFI_PROC_FUNC callback)
g_wifiCallback = callback;
}
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
static WifiEvent g_coapEventHandler = {0};
void CoapHandleWifiEvent(unsigned int para)
{
if (g_wifiCallback != NULL) {
@@ -254,14 +290,9 @@ void CoapHandleWifiEvent(unsigned int para)
}
}
static void CoapConnectionChangedHandler(int state, WifiLinkedInfo* info)
{
(void)info;
CoapWriteMsgQueue(state);
}
void CoapWriteMsgQueue(int state)
{
SOFTBUS_PRINT("[DISCOVERY] CoapWriteMsgQueue\n");
AddressEventHandler handler;
handler.handler = CoapHandleWifiEvent;
handler.state = state;
@@ -297,13 +328,24 @@ int CoapDeinitWifiEvent(void)
{
unsigned int ret;
g_wifiTaskStart = 0;
if (g_msgQueTaskId != -1) {
ret = LOS_TaskDelete(g_msgQueTaskId);
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
if (g_msgQueTaskId != NULL) {
ret = osThreadTerminate(g_msgQueTaskId);
if (ret != 0) {
return -1;
}
g_msgQueTaskId = NULL;
}
#else
if (g_msgQueTaskId != -1) {
ret = pthread_join((pthread_t)g_msgQueTaskId, NULL);
if (ret != 0) {
SOFTBUS_PRINT("[DISCOVERY] pthread_join fail\n");
return -1;
}
g_msgQueTaskId = -1;
}
#endif
if (g_wifiQueueId != -1) {
ret = DeleteMsgQue(g_wifiQueueId);
@@ -312,19 +354,60 @@ int CoapDeinitWifiEvent(void)
}
g_wifiQueueId = -1;
}
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
WifiErrorCode error = UnRegisterWifiEvent(&g_coapEventHandler);
if (error != WIFI_SUCCESS) {
return -1;
}
g_coapEventHandler.OnWifiConnectionChanged = NULL;
#endif
return NSTACKX_EOK;
}
int CreateMsgQueThread(void)
{
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
if (g_msgQueTaskId != NULL) {
return NSTACKX_EOK;
}
osThreadAttr_t attr;
attr.name = "wifi_event";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
attr.priority = osPriorityNormal4; // COAP_DEFAULT_PRIO -> cmsis prio
g_msgQueTaskId = osThreadNew((osThreadFunc_t)CoapWifiEventThread, NULL, &attr);
if (NULL == g_msgQueTaskId) {
SOFTBUS_PRINT("[DISCOVERY]Task Create fail\n");
return NSTACKX_EOK;
}
#else
int ret;
if (g_msgQueTaskId != -1) {
return NSTACKX_EOK;
}
ThreadAttr attr = {"wifi_event", 0x800, 20, 0, 0};
ret = CreateThread((Runnable)CoapWifiEventThread, NULL, &attr, (unsigned int*)&g_msgQueTaskId);
if (ret != 0) {
SOFTBUS_PRINT("[DISCOVERY]Task Create fail\n");
return ret;
}
#endif
return NSTACKX_EOK;
}
int CoapInitWifiEvent(void)
{
SOFTBUS_PRINT("[DISCOVERY] CoapInitWifiEvent\n");
unsigned int ret;
if (g_wifiQueueId == -1) {
ret = CreateMsgQue("wifiQue",
ret = CreateMsgQue("/wifiQue",
WIFI_QUEUE_SIZE, (unsigned int*)&g_wifiQueueId,
0, sizeof(AddressEventHandler));
if (ret != 0) {
@@ -332,6 +415,8 @@ int CoapInitWifiEvent(void)
(void)CoapDeinitWifiEvent();
return ret;
}
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
g_coapEventHandler.OnWifiConnectionChanged = CoapConnectionChangedHandler;
WifiErrorCode error = RegisterWifiEvent(&g_coapEventHandler);
if (error != WIFI_SUCCESS) {
@@ -340,33 +425,24 @@ int CoapInitWifiEvent(void)
g_wifiQueueId = -1;
return error;
}
#endif
}
if (g_msgQueTaskId == -1) {
TSK_INIT_PARAM_S wifiEventTask;
wifiEventTask.pfnTaskEntry = (TSK_ENTRY_FUNC)CoapWifiEventThread;
wifiEventTask.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
wifiEventTask.pcName = "wifi_event";
wifiEventTask.usTaskPrio = COAP_DEFAULT_PRIO;
wifiEventTask.uwResved = LOS_TASK_STATUS_DETACHED;
ret = LOS_TaskCreate((unsigned int*)&g_msgQueTaskId, &wifiEventTask);
if (ret != 0) {
SOFTBUS_PRINT("[DISCOVERY]Task Create fail\n");
(void)CoapDeinitWifiEvent();
g_wifiQueueId = -1;
return ret;
}
}
return NSTACKX_EOK;
}
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
static void CoapConnectionChangedHandler(int state, WifiLinkedInfo* info)
{
(void)info;
CoapWriteMsgQueue(state);
}
void CoapGetWifiIp(char *ip, int length)
{
struct netif *netif = NULL;
int ret;
netif = netif_find(WLAN);
netif = netif_find(WLAN_NAME);
if (netif == NULL) {
return;
}
@@ -383,100 +459,260 @@ void CoapGetWifiIp(char *ip, int length)
return;
}
#else
typedef void *(*Runnable)(void *argv);
typedef struct ThreadAttr ThreadAttr;
struct ThreadAttr {
const char *name;
uint32_t stackSize;
uint8_t priority;
uint8_t reserved1;
uint16_t reserved2;
};
typedef enum {
STATUS_UP,
STATUS_DOWN
} InterfaceStatus;
int CreateThread(Runnable run, void *argv, const ThreadAttr *attr, unsigned int *threadId)
typedef struct {
char ip[NSTACKX_MAX_IP_STRING_LEN];
InterfaceStatus status;
int flag;
} InterfaceInfo;
void GetInterfaceInfo(int fd, const char* interfaceName, int length, InterfaceInfo *info)
{
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);
pthread_attr_setstacksize(&threadAttr, (attr->stackSize | MIN_STACK_SIZE));
struct sched_param sched = {attr->priority};
pthread_attr_setschedparam(&threadAttr, &sched);
int errCode = pthread_create((pthread_t *)threadId, &threadAttr, run, argv);
return errCode;
if (fd < 0 || info == NULL || interfaceName == NULL) {
return;
}
struct ifreq ifr;
memset_s(&ifr, sizeof(struct ifreq), 0, sizeof(struct ifreq));
int ret = strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), interfaceName, length);
if (ret != EOK) {
SOFTBUS_PRINT("[DISCOVERY] CoapGetWifiIp ifr.ifr_name cpy fail\n");
return;
}
if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
return;
}
if ((unsigned short int)ifr.ifr_flags & IFF_UP) {
info->status = STATUS_UP;
} else {
info->status = STATUS_DOWN;
info->ip[0] = '\0';
info->flag = 1;
return;
}
memset_s(&ifr, sizeof(struct ifreq), 0, sizeof(struct ifreq));
ret = strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), interfaceName, length);
if (ret != EOK) {
SOFTBUS_PRINT("[DISCOVERY] CoapGetWifiIp ifr.ifr_name cpy fail\n");
return;
}
if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) {
return;
}
ret = strcpy_s(info->ip, sizeof(info->ip),
inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr));
if (ret != EOK) {
SOFTBUS_PRINT("[DISCOVERY] CoapGetWifiIp cpy fail\n");
}
info->flag = 1;
return;
}
#define IP_LEN 16
int GetIpByInterfaceName(int fd, const char* interfaceName, int lenth, struct ifreq *ifr)
void CoapGetWifiIp(char *ip, int length)
{
if (ifr == NULL || interfaceName == NULL) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
return;
}
InterfaceInfo info = {0};
GetInterfaceInfo(fd, ETH, strlen(ETH) + 1, &info);
if (!info.flag) {
memset_s(&info, sizeof(info), 0, sizeof(info));
GetInterfaceInfo(fd, WLAN, strlen(WLAN) + 1, &info);
}
if (!info.flag) {
close(fd);
return;
}
if (strcpy_s(ip, length, info.ip) != EOK) {
SOFTBUS_PRINT("[DISCOVERY]copy ip to dst failed.\n");
}
close(fd);
}
#if defined(__LITEOS_A__)
static int CheckEthInfoAndNotify(InterfaceInfo *prev, const InterfaceInfo *new)
{
if (prev == NULL || new == NULL) {
return NSTACKX_EFAILED;
}
int ret = strncpy_s(ifr->ifr_name, sizeof(ifr->ifr_name), interfaceName, lenth);
if (ret != EOK) {
SOFTBUS_PRINT("[DISCOVERY] CoapGetWifiIp ifr->ifr_name cpy fail\n");
if (prev->flag == 0 || new->flag == 0) {
prev->status = new->status;
if (memcpy_s(prev->ip, sizeof(prev->ip), new->ip, sizeof(new->ip))) {
SOFTBUS_PRINT("[DISCOVERY]fail copy ip to prev.\n");
}
return NSTACKX_EFAILED;
}
ret = ioctl(fd, SIOCGIFADDR, ifr);
if (ret < 0) {
SOFTBUS_PRINT("[DISCOVERY] ioctl fail\n");
if (prev->status != new->status) {
if (new->status == STATUS_DOWN) {
SOFTBUS_PRINT("Eth disconnected.\r\n");
CoapWriteMsgQueue(CLEAR_IP_EVENT);
} else {
SOFTBUS_PRINT("Eth connected.\r\n");
CoapWriteMsgQueue(UPDATE_IP_EVENT);
}
prev->status = new->status;
if (memcpy_s(prev->ip, sizeof(prev->ip), new->ip, sizeof(new->ip))) {
SOFTBUS_PRINT("[DISCOVERY]fail copy ip to prev.\n");
}
}
return NSTACKX_EOK;
}
static int SendCtrlCommand(const char *cmd, struct wpa_ctrl *ctrlConn, char *reply, size_t *replyLen)
{
size_t len = *replyLen - 1;
wpa_ctrl_request(ctrlConn, cmd, strlen(cmd), reply, &len, 0);
if (len != 0 && strncmp(reply, "FAIL", strlen("FAIL"))) {
*replyLen = len;
return 0;
}
SOFTBUS_PRINT("send ctrl request [%s] failed.", cmd);
return -1;
}
#define WPA_CONNECTED "wpa_state=COMPLETED"
#define WPA_DISCONNECTED "wpa_state=SCANNING"
#define REPLY_LENGTH 512
void CheckWlanInfoAndNotify(int *prev, int first)
{
struct wpa_ctrl *ctrlConn = wpa_ctrl_open(WLAN);
char reply[REPLY_LENGTH] = {0};
if (ctrlConn == NULL) {
SOFTBUS_PRINT("open wpa control interface failed.");
return;
}
char *cmd = "STATUS";
size_t len = REPLY_LENGTH;
int ret = SendCtrlCommand(cmd, ctrlConn, reply, &len);
if (ret != 0) {
SOFTBUS_PRINT("reply:%s\n.", reply);
wpa_ctrl_close(ctrlConn);
return;
}
int status;
if (strstr(reply, WPA_CONNECTED)) {
status = UPDATE_IP_EVENT;
} else if (strstr(reply, WPA_DISCONNECTED)) {
status = CLEAR_IP_EVENT;
} else {
wpa_ctrl_close(ctrlConn);
return;
}
if (first) {
*prev = status;
wpa_ctrl_close(ctrlConn);
return;
}
if (*prev != status) {
CoapWriteMsgQueue(status);
}
*prev = status;
wpa_ctrl_close(ctrlConn);
return;
}
void CoapQueryIpHandle(unsigned int uwParam1, unsigned int uwParam2, unsigned int uwParam3, unsigned int uwParam4)
{
(void)uwParam1;
(void)uwParam2;
(void)uwParam3;
(void)uwParam4;
g_updateIpFlag = 1;
int fd = socket(AF_INET, SOCK_STREAM, 0);
InterfaceInfo ethInfo;
InterfaceInfo prevEthInfo;
memset_s(&prevEthInfo, sizeof(prevEthInfo), 0, sizeof(prevEthInfo));
GetInterfaceInfo(fd, ETH, strlen(ETH) + 1, &prevEthInfo);
int updateFlag;
int prevFlag;
CheckWlanInfoAndNotify(&prevFlag, 1);
while (g_updateIpFlag) {
usleep(HUNDRED_MS);
memset_s(&ethInfo, sizeof(ethInfo), 0, sizeof(ethInfo));
GetInterfaceInfo(fd, ETH, strlen(ETH) + 1, &ethInfo);
updateFlag = CheckEthInfoAndNotify(&prevEthInfo, &ethInfo);
if (updateFlag != -1) {
continue;
}
CheckWlanInfoAndNotify(&prevFlag, 0);
}
close(fd);
}
int CreateQueryIpThread(void)
{
if (g_queryIpTaskId != -1) {
return NSTACKX_EOK;
}
ThreadAttr attr = {"queryIp_task", 0x800, 20, 0, 0};
int error = CreateThread((Runnable)CoapQueryIpHandle, NULL, &attr, (unsigned int*)&g_queryIpTaskId);
if (error != 0) {
SOFTBUS_PRINT("[DISCOVERY] create task fail\n");
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
void CoapGetWifiIp(char *ip, int length)
void ExitQueryIpThread(void)
{
int ret;
struct ifreq ifr;
memset_s(&ifr, sizeof(struct ifreq), 0, sizeof(struct ifreq));
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
SOFTBUS_PRINT("[DISCOVERY] CoapGetWifiIp socket fail\n");
return;
g_updateIpFlag = 0;
if (g_queryIpTaskId != -1) {
int ret = pthread_join((pthread_t)g_queryIpTaskId, NULL);
if (ret != 0) {
SOFTBUS_PRINT("[DISCOVERY] ExitQueryIpThread pthread_join fail\n");
return;
}
}
ret = GetIpByInterfaceName(fd, ETH, strlen(ETH) + 1, &ifr);
if (ret != NSTACKX_EOK) {
SOFTBUS_PRINT("[DISCOVERY] fail to get eth Ip, tring to get wifi Ip.\n");
memset_s(&ifr, sizeof(struct ifreq), 0, sizeof(struct ifreq));
ret = GetIpByInterfaceName(fd, WLAN, strlen(WLAN) + 1, &ifr);
}
if (ret != NSTACKX_EOK) {
SOFTBUS_PRINT("[DISCOVERY] get ETH IP and WIFI IP failed.\n");
close(fd);
return;
}
ret = strcpy_s(ip, IP_LEN, inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr));
if (ret != EOK) {
SOFTBUS_PRINT("[DISCOVERY] CoapGetWifiIp cpy fail\n");
}
close(fd);
}
#endif
#endif
int CreateCoapListenThread(void)
{
g_terminalFlag = 1;
if (g_coapTaskId != -1) {
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
if (g_coapTaskId != NULL) {
return NSTACKX_EOK;
}
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
unsigned int ret;
TSK_INIT_PARAM_S listenTask;
listenTask.pfnTaskEntry = (TSK_ENTRY_FUNC)CoapReadHandle;
listenTask.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
listenTask.pcName = "coap_listen_task";
listenTask.usTaskPrio = COAP_DEFAULT_PRIO;
listenTask.uwResved = LOS_TASK_STATUS_DETACHED;
ret = LOS_TaskCreate((unsigned int*)&g_coapTaskId, &listenTask);
if (ret != 0) {
osThreadAttr_t attr;
attr.name = "coap_listen_task";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
attr.priority = osPriorityNormal4; // COAP_DEFAULT_PRIO -> cmsis prio
g_coapTaskId = osThreadNew((osThreadFunc_t)CoapReadHandle, NULL, &attr);
if (g_coapTaskId == NULL) {
g_terminalFlag = 0;
SOFTBUS_PRINT("[DISCOVERY] create task fail\n");
return NSTACKX_EFAILED;
}
#else
if (g_coapTaskId != -1) {
return NSTACKX_EOK;
}
ThreadAttr attr = {"coap_listen_task", 0x800, 20, 0, 0};
int error = CreateThread((Runnable)CoapReadHandle, NULL, &attr, (unsigned int*)&g_coapTaskId);
int error = CreateThread((Runnable)CoapReadHandle, NULL, &attr, (unsigned int *)&g_coapTaskId);
if (error != 0) {
g_terminalFlag = 0;
SOFTBUS_PRINT("[DISCOVERY] create task fail\n");
@@ -490,9 +726,9 @@ void ExitCoapListenThread(void)
{
g_terminalFlag = 0;
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
if (g_coapTaskId != -1) {
int ret = LOS_TaskDelete(g_coapTaskId);
if (ret != 0) {
if (g_coapTaskId != NULL) {
if (osThreadTerminate(g_coapTaskId) != 0) {
SOFTBUS_PRINT("[DISCOVERY] ExitCoapListenThread pthread_join fail\n");
return;
}
}
@@ -514,24 +750,34 @@ int CoapInitDiscovery(void)
SOFTBUS_PRINT("[DISCOVERY] Init socket fail\n");
return ret;
}
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
int rtn = CoapInitWifiEvent();
if (rtn != NSTACKX_EOK) {
ret = CoapInitWifiEvent();
if (ret != NSTACKX_EOK) {
SOFTBUS_PRINT("[DISCOVERY] Init wifi event fail\n");
return rtn;
return ret;
}
#if defined(__LITEOS_A__)
ret = CreateQueryIpThread();
if (ret != NSTACKX_EOK) {
SOFTBUS_PRINT("[DISCOVERY] Init query Ip fail\n");
return ret;
}
#endif
if (CreateMsgQueThread() != NSTACKX_EOK) {
return NSTACKX_EFAILED;
}
return CreateCoapListenThread();
}
int CoapDeinitDiscovery(void)
{
ExitCoapListenThread();
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
int rtn = CoapDeinitWifiEvent();
if (rtn != NSTACKX_EOK) {
if (rtn != NSTACKX_EOK) {
return NSTACKX_EFAILED;
}
#if defined(__LITEOS_A__)
ExitQueryIpThread();
#endif
CoapDeinitSocket();
return NSTACKX_EOK;
@@ -539,7 +785,23 @@ int CoapDeinitDiscovery(void)
#define GET_IP_TIMES 300
#define GET_IP_INFINITE (-1)
#define IP_MAX_LEN 15
#define IP_MIN_LEN 7
int CheckIpIsValid(const char *ip, int length)
{
if (ip == NULL || length < IP_MIN_LEN || length > IP_MAX_LEN) {
return -1;
}
if (strcmp(ip, "0.0.0.0") == 0) {
return -1;
}
int pos = length - 1;
if (ip[pos] == '1' && ip[pos - 1] == '.') {
return -1;
}
return 0;
}
void CoapGetIp(char *ip, int length, int finite)
{
if (ip == NULL || length != NSTACKX_MAX_IP_STRING_LEN) {
@@ -550,7 +812,7 @@ void CoapGetIp(char *ip, int length, int finite)
int count = finite ? GET_IP_TIMES : GET_IP_INFINITE;
while (g_queryIpFlag) {
CoapGetWifiIp(ip, length);
if (strcmp(ip, "0.0.0.0") != 0) {
if (CheckIpIsValid(ip, strlen(ip)) == 0) {
break;
}
-1
View File
@@ -18,7 +18,6 @@
#include "nstackx_error.h"
#include "os_adapter.h"
#include "securec.h"
typedef void (*TaskHandle)(void *arg);
SocketInfo g_socket = {0};
int g_serverFd = -1;
int g_clientFd = -1;
View File
View File
View File
View File
View File
View File
@@ -291,9 +291,7 @@ int InitLocalDeviceInfo(void)
return ERROR_FAIL;
}
}
#if defined(__LITEOS_A__) || defined(__LINUX__)
CoapGetIp(g_deviceInfo->deviceIp, NSTACKX_MAX_IP_STRING_LEN, 1);
#endif
g_deviceInfo->devicePort = -1;
g_deviceInfo->isAccountTrusted = 1;
+19 -20
View File
@@ -43,9 +43,10 @@ static int g_isServiceInit = 0;
PublishModule *g_publishModule = NULL;
char *g_capabilityData = NULL;
#define INVALID_SEM_ID 0xffffffff
unsigned long g_serviceSemId = INVALID_SEM_ID;
#define SOFTBUS_PERMISSION "ohos.permission.DISTRIBUTED_DATASYNC"
static int DoRegistService(int medium);
static MutexId g_discoveryMutex = NULL;
int GetDeviceType(const char *value)
{
if (value == NULL) {
@@ -253,9 +254,7 @@ int InitService(void)
DeinitService();
return ret;
}
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
CoapWriteMsgQueue(UPDATE_IP_EVENT);
#endif
ret = CoapRegisterDeviceInfo();
if (ret != ERROR_SUCCESS) {
SOFTBUS_PRINT("[DISCOVERY] InitService CoapRegisterDeviceInfo fail\n");
@@ -263,11 +262,6 @@ int InitService(void)
return ret;
}
g_isServiceInit = 1;
#if defined(__LITEOS_A__) || defined(__LINUX__)
if (BusManager(1) != ERROR_SUCCESS) {
SOFTBUS_PRINT("[DISCOVERY] InitService BusManager(1) fail\n");
}
#endif
SOFTBUS_PRINT("[DISCOVERY] InitService ok\n");
return ERROR_SUCCESS;
}
@@ -509,34 +503,39 @@ int PublishService(const char *moduleName, const struct PublishInfo *info, const
PublishCallback(info->publishId, PUBLISH_FAIL_REASON_NOT_SUPPORT_MEDIUM, NULL, cb);
return ERROR_INVALID;
}
if (g_serviceSemId == INVALID_SEM_ID) {
if (SemCreate(0, &g_serviceSemId) != 0) {
g_serviceSemId = INVALID_SEM_ID;
if (g_discoveryMutex == NULL) {
g_discoveryMutex = MutexInit();
if (g_discoveryMutex == NULL) {
PublishCallback(info->publishId, PUBLISH_FAIL_REASON_UNKNOWN, NULL, cb);
return ERROR_FAIL;
}
}
(void)SemWait(&g_serviceSemId);
MutexLock(g_discoveryMutex);
if (InitService() != ERROR_SUCCESS) {
SOFTBUS_PRINT("[DISCOVERY] PublishService InitService fail\n");
PublishCallback(info->publishId, PUBLISH_FAIL_REASON_UNKNOWN, NULL, cb);
(void)SemPost(&g_serviceSemId);
MutexUnlock(g_discoveryMutex);
return ERROR_FAIL;
}
PublishModule *findModule = AddPublishModule(moduleName, info);
if (findModule == NULL) {
SOFTBUS_PRINT("[DISCOVERY] PublishService AddPublishModule fail\n");
PublishCallback(info->publishId, PUBLISH_FAIL_REASON_UNKNOWN, NULL, cb);
(void)SemPost(&g_serviceSemId);
MutexUnlock(g_discoveryMutex);
return ERROR_FAIL;
}
int ret = ERROR_SUCCESS;
if (info->capability == NULL || info->capabilityData == NULL) {
(void)CoapRegisterDefualtService();
} else {
ret = DoRegistService(info->medium);
}
(void)SemPost(&g_serviceSemId);
MutexUnlock(g_discoveryMutex);
if (ret != ERROR_SUCCESS) {
PublishCallback(info->publishId, PUBLISH_FAIL_REASON_UNKNOWN, findModule, cb);
return ERROR_FAIL;
@@ -553,16 +552,16 @@ int UnPublishService(const char* moduleName, int publishId)
return ERROR_FAIL;
}
if (moduleName == NULL || publishId <= 0 || g_serviceSemId == INVALID_SEM_ID) {
if (moduleName == NULL || publishId <= 0 || g_discoveryMutex == NULL) {
SOFTBUS_PRINT("[DISCOVERY] UnPublishService invliad para\n");
return ERROR_INVALID;
}
(void)SemWait(&g_serviceSemId);
MutexLock(g_discoveryMutex);
PublishModule *findModule = FindExistModule(moduleName, publishId);
if (findModule == NULL) {
SOFTBUS_PRINT("[DISCOVERY] UnPublishService get module fail\n");
(void)SemPost(&g_serviceSemId);
MutexUnlock(g_discoveryMutex);
return ERROR_NONEXIST;
}
@@ -575,11 +574,11 @@ int UnPublishService(const char* moduleName, int publishId)
int ret = DoRegistService(medium);
if (ret != ERROR_SUCCESS) {
SOFTBUS_PRINT("[DISCOVERY] UnPublishService DoRegistService fail, error = %d\n", ret);
(void)SemPost(&g_serviceSemId);
MutexUnlock(g_discoveryMutex);
return ret;
}
(void)SemPost(&g_serviceSemId);
MutexUnlock(g_discoveryMutex);
SOFTBUS_PRINT("[DISCOVERY] UnPublishService ok\n");
return ret;
}
@@ -0,0 +1,291 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @addtogroup Softbus
* @{
*
* @brief Provides high-speed, secure communication between devices.
*
* This module implements unified distributed communication capability management between nearby devices,
* and provides link-independent device discovery and transmission interfaces to support service publishing
* and data transmission.
*
* @since 1.0
* @version 1.0
*/
/**
* @file discovery_service.h
*
* @brief Declares unified device service publishing interfaces.
*
* This file provides capabilities related to device service publishing, including publishing services,
* unpublishing services, and setting device parameters.
* After multiple nearby devices are discovered and networked, these interfaces can be used to perform
* service publishing-related operations. \n
*
* @since 1.0
* @version 1.0
*/
#ifndef _DISCOVERY_SERVICE_H
#define _DISCOVERY_SERVICE_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Enumerates media, such as Bluetooth, Wi-Fi and USB, used for publishing services.
*
* Currently, the media can only be set to coap.
*
*/
typedef enum {
/** Automatic medium selection */
AUTO = 0,
/** Bluetooth */
BLE = 1,
/** Wi-Fi */
COAP = 2,
/** USB */
USB = 3,
} ExchangeMedium;
/**
* @brief Enumerates frequencies for publishing services.
* This enumeration is involved only in Bluetooth and is not supported currently.
*/
typedef enum {
/** Low */
LOW = 0,
/** Medium */
MID = 1,
/** High */
HIGH = 2,
/** Super-high */
SUPER_HIGH = 3,
} ExchangeFreq;
/**
* @brief Enumerates the modes in which services are published.
* The publishing service supports the passive mode. Lite devices support the passive mode only.
*/
typedef enum {
/** Passive */
DISCOVER_MODE_PASSIVE = 0x55,
/** Proactive */
DISCOVER_MODE_ACTIVE = 0xAA
} DiscoverMode;
/**
* @brief Defines service provisioning information sent to a discovering device.
*
*/
typedef struct PublishInfo {
/** Service publishing ID */
int publishId;
/** Service publishing mode, which can be {@link DISCOVER_MODE_PASSIVE} or {@link DISCOVER_MODE_ACTIVE } */
int mode;
/** Service publishing medium */
ExchangeMedium medium;
/** Service publishing frequency */
ExchangeFreq freq;
/** Service publishing capabilities. For details, see {@link g_capabilityMap}. */
const char *capability;
/** Capability data for service publishing */
unsigned char *capabilityData;
/** Maximum length of the capability data for service publishing (2 bytes) */
unsigned int dataLen;
} PublishInfo;
/**
* @brief Enumerates failure reasons for publishing services.
*
* The failure reason is returned to the caller through the callback function.
*
*/
typedef enum {
/** Unsupported medium */
PUBLISH_FAIL_REASON_NOT_SUPPORT_MEDIUM = 1,
/** Invalid parameter */
PUBLISH_FAIL_REASON_PARAMETER_INVALID = 2,
/** Unknown reason */
PUBLISH_FAIL_REASON_UNKNOWN = 0xFF
} PublishFailReason;
/**
* @brief Enumerates supported capabilities published by a device.
*
*/
typedef enum {
/** MeeTime */
HICALL_CAPABILITY_BITMAP = 0,
/** Video reverse connection in the smart domain */
PROFILE_CAPABILITY_BITMAP = 1,
/** Gallery in Vision */
HOMEVISIONPIC_CAPABILITY_BITMAP = 2,
/** cast+ */
CASTPLUS_CAPABILITY_BITMAP,
/** Input method in Vision */
AA_CAPABILITY_BITMAP,
/** Device virtualization tool package */
DVKIT_CAPABILITY_BITMAP,
/** Distributed middleware */
DDMP_CAPABILITY_BITMAP
} DataBitMap;
/**
* @brief Defines the mapping between supported capabilities and bitmaps.
*
*/
typedef struct {
/** Bitmaps. For details, see {@link DataBitMap}. */
DataBitMap bitmap;
/** Capability. For details, see {@link g_capabilityMap}. */
char *capability;
} CapabilityMap;
static const CapabilityMap g_capabilityMap[] = {
{HICALL_CAPABILITY_BITMAP, (char *)"hicall"},
{PROFILE_CAPABILITY_BITMAP, (char *)"profile"},
{CASTPLUS_CAPABILITY_BITMAP, (char *)"castPlus"},
{HOMEVISIONPIC_CAPABILITY_BITMAP, (char *)"homevisionPic"},
{AA_CAPABILITY_BITMAP, (char *)"aaCapability"},
{DVKIT_CAPABILITY_BITMAP, (char *)"dvKit"},
{DDMP_CAPABILITY_BITMAP, (char *)"ddmpCapability"},
};
/**
* @brief Enumerates device types.
*
*/
typedef enum DeviceTypeEnum {
/** Unknown */
UNKOWN = 0x00,
/** Smartphone */
PHONE = 0x0E,
/** Tablet */
PAD = 0x11,
/** Smart TV */
TV = 0x9C,
/** PC */
PC = 0x0C,
/** Audio device */
AUDIO = 0x0A,
/** Vehicle-mounted device */
CAR = 0x83,
/** Light device L0 */
L0 = 0xF1,
/** Light device L1 */
L1 = 0xF2,
} DeviceType;
/**
* @brief Defines the mappings between the device type enumerations and device type names.
*
*/
typedef struct {
/** Name of a device type. Only names defined in {@link g_devMap} are supported. */
char *value;
/** Enumeration of a device type. Only enumerations defined in {@link g_devMap} are supported. */
DeviceType devType;
} DeviceMap;
static const DeviceMap g_devMap[] = {
{(char *)"PHONE", PHONE},
{(char *)"PAD", PAD},
{(char *)"TV", TV},
{(char *)"PC", PC},
{(char *)"AUDIO", AUDIO},
{(char *)"CAR", CAR},
{(char *)"L0", L0},
{(char *)"L1", L1}
};
/**
* @brief Defines the callbacks for successful and failed service publishing.
*
*/
typedef struct IPublishCallback {
/** Callback for successful publishing */
void (*onPublishSuccess)(int publishId);
/** Callback for failed publishing */
void (*onPublishFail)(int publishId, PublishFailReason reason);
} IPublishCallback;
/**
* @brief Enumerates device information, such as its indentity, type and name.
*
*/
typedef enum {
/** Device ID. The value contains a maximum of 64 characters. */
COMM_DEVICE_KEY_DEVID = 0,
/** Device type. Currently, only <b>ddmpCapability</b> is supported. */
COMM_DEVICE_KEY_DEVTYPE = 1,
/** Device name. The value contains a maximum of 63 characters. */
COMM_DEVICE_KEY_DEVNAME = 2,
/** Reserved */
COMM_DEVICE_KEY_MAX
} CommonDeviceKey;
/**
* @brief Defines the type and content of a device to set.
*
*/
typedef struct CommonDeviceInfo {
/** Device information type. For details, see {@link CommonDeviceKey}. */
CommonDeviceKey key;
/** Content to set */
const char *value;
} CommonDeviceInfo;
/**
* @brief Publishes a service to the discovering device in the LAN.
*
* The <b>publicId</b> and <b>moduleName</b> uniquely identify a service. A maximum of three services can be published.
*
* @param moduleName Indicates the pointer to the module name of the upper-layer service.
* The value contains a maximum of 63 bytes.
* @param info Indicates the pointer to the service to publish. For details, see {@link PublishInfo}.
* @param cb Indicates the pointer to the callback for service publishing. For details, see {@link IPublishCallback}.
* @return Returns <b>0</b> if the operation is successful; returns <b>-1</b> otherwise.
*/
int PublishService(const char *moduleName, const struct PublishInfo* info, const struct IPublishCallback *cb);
/**
* @brief Unpublishes a service based on the <b>publicId</b> and <b>moduleName</b>.
*
* @param moduleName Indicates the pointer to the module name of the upper-layer service.
* The value contains a maximum of 63 bytes.
* @param publishId Indicates the ID of the service to unpublish. The value must be greater than <b>0</b>.
* @return Returns <b>0</b> if the operation is successful; returns a non-zero value otherwise.
*
*/
int UnPublishService(const char *moduleName, int publishId);
/**
* @brief Sets common device information, such as its indentity, type and name.
*
* @param devInfo Indicates the pointer to the device information array.
* @param num Indicates the number of elements in the device information array.
* If the value is inconsistent with the length of the device information array, the program breaks down.
* @return Returns <b>0</b> if the operation is successful; returns a non-zero value otherwise.
* @see PublishService
*/
int SetCommonDeviceInfo(const struct CommonDeviceInfo *devInfo, unsigned int num);
#ifdef __cplusplus
}
#endif
#endif /* _DISCOVERY__SERVICE_H */
+184
View File
@@ -0,0 +1,184 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @addtogroup Softbus
* @{
*
* @brief Provides high-speed, secure communication between devices.
*
* This module implements unified distributed communication capability management between
* nearby devices, and provides link-independent device discovery and transmission interfaces
* to support service publishing and data transmission.
*
* @since 1.0
* @version 1.0
*/
/**
* @file session.h
*
* @brief Declares unified data transmission interfaces.
*
* This file provides data transmission capabilities, including creating and removing a session server,
* opening and closing sessions, receiving data, and querying basic session information. \n
* After multiple nearby devices are discovered and networked, these interfaces can be used to
* transmit data across devices. \n
*
* @since 1.0
* @version 1.0
*/
#ifndef SESSION_H
#define SESSION_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Defines session callbacks.
*
* When a session is opened or closed, or there is data to process, the related callback is invoked.
*
* @since 1.0
* @version 1.0
*/
struct ISessionListener {
/**
* @brief Called when a session is opened.
*
* This function can be used to verify the session or initialize resources related to the session.
*
* @param sessionId Indicates the session ID.
* @return Returns <b>0</b> if the session connection is accepted; returns a non-zero value
* otherwise (you do not need to call {@link CloseSession} to close the session).
* @since 1.0
* @version 1.0
*/
int (*onSessionOpened)(int sessionId);
/**
* @brief Called when a session is closed.
*
* This function can be used to release resources related to the session.
* You do not need to call {@link CloseSession}.
*
* @param sessionId Indicates the session ID.
* @since 1.0
* @version 1.0
*/
void (*onSessionClosed)(int sessionId);
/**
* @brief Called when data is received.
*
* This function is used to notify that data is received.
*
* @param sessionId Indicates the session ID.
* @param data Indicates the pointer to the data received.
* @param dataLen Indicates the length of the data received.
* @since 1.0
* @version 1.0
*/
void (*onBytesReceived)(int sessionId, const void *data, unsigned int dataLen);
};
/**
* @brief Creates a session server based on a module name and session name.
*
* A maximum of 18 session servers can be created.
*
* @param moduleName Indicates the pointer to the module name, which can be used to check whether the
* session server is in this module. The value cannot be empty and can contain a maximum of 64 characters.
* @param sessionName Indicates the pointer to the session name, which is the unique ID of the session server.
* The value cannot be empty and can contain a maximum of 64 characters.
* @param listener Indicates the pointer to the session callback structure, which cannot be empty.
* @return Returns <b>0</b> if the operation is successful; returns <b>-1</b> otherwise.
* @see RemoveSessionServer
* @since 1.0
* @version 1.0
*/
int CreateSessionServer(const char *mouduleName, const char *sessionName, struct ISessionListener *listener);
/**
* @brief Removes a session server based on a module name and session name.
*
* @param moduleName Indicates the pointer to the name of the registered module, which can be used to check
* whether the session server is in this module. The value cannot be empty and can contain a maximum of 64 characters.
* @param sessionName Indicates the pointer to the session name. The value cannot be empty and can contain
* a maximum of 64 characters.
* @return Returns <b>0</b> if the operation is successful; returns <b>-1</b> otherwise.
* @see CreateSessionServer
* @since 1.0
* @version 1.0
*/
int RemoveSessionServer(const char *mouduleName, const char *sessionName);
/**
* @brief Sends data based on a session ID.
*
* @param sessionId Indicates the session ID.
* @param data Indicates the pointer to the data to send, which cannot be <b>NULL</b>.
* @param len Indicates the length of the data to send. The maximum length cannot exceed 984 characters.
* @return Returns <b>0</b> if the function is called successfully; returns <b>-1</b> otherwise.
* @since 1.0
* @version 1.0
*/
int SendBytes(int sessionId, const unsigned char *data, unsigned int len);
/**
* @brief Obtains the session name registered by the local device based on the session ID.
*
* @param sessionId Indicates the session ID.
* @param sessionName Indicates the pointer to the buffer for storing the session name.
* @param len Indicates the length of the buffer.
* @return Returns <b>0</b> if the operation is successful; returns <b>-1</b> otherwise.
* @since 1.0
* @version 1.0
*/
int GetMySessionName(int sessionId, char *sessionName, unsigned int len);
/**
* @brief Obtains the session name registered by the peer device based on the session ID.
*
* @param sessionId Indicates the session ID.
* @param sessionName Indicates the pointer to the buffer for storing the session name.
* @param len Indicates the length of the buffer.
* @return Returns <b>0</b> if the operation is successful; returns <b>-1</b> otherwise.
* @since 1.0
* @version 1.0
*/
int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len);
/**
* @brief Obtains the peer device ID based on a session ID.
*
* @param sessionId Indicates the session ID.
* @param devId Indicates the pointer to the buffer for storing the device ID.
* @param len Indicates the length of the buffer.
* @return Returns <b>0</b> if the operation is successful; returns <b>-1</b> otherwise.
* @since 1.0
* @version 1.0
*/
int GetPeerDeviceId(int sessionId, char *devId, unsigned int len);
/**
* @brief Closes a connected session based on a session ID.
*
* @param sessionId Indicates the session ID.
* @since 1.0
* @version 1.0
*/
void CloseSession(int sessionId);
#ifdef __cplusplus
}
#endif
#endif // SESSION_H
+7 -5
View File
@@ -17,7 +17,7 @@
#include <stdint.h>
#include <stdio.h>
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
#include "los_sem.h"
#include <cmsis_os.h>
#else
#include "pms_interface.h"
#include "pms_types.h"
@@ -32,10 +32,12 @@
#ifdef __cplusplus
extern "C" {
#endif
int SemCreate(unsigned short count, unsigned long *semHandle);
int SemDelete(const unsigned long *semHandle);
int SemWait(const unsigned long *semHandle);
int SemPost(const unsigned long *semHandle);
typedef void *MutexId;
MutexId MutexInit(void);
void MutexLock(MutexId mutex);
void MutexUnlock(MutexId mutex);
void CloseSocket(int *fd);
int WriteMsgQue(unsigned int queueID,
const void *bufferAddr,
+27 -35
View File
@@ -13,46 +13,27 @@
* limitations under the License.
*/
#include "os_adapter.h"
#include <los_queue.h>
#include <los_task.h>
#include "lwip/sockets.h"
int SemCreate(unsigned short count, unsigned long *semHandle)
MutexId MutexInit(void)
{
if (semHandle == NULL) {
return -1;
}
int ret = LOS_SemCreate(count, (unsigned int*)semHandle);
if (ret == 0) {
return LOS_SemPost((unsigned int)*semHandle);
}
return ret;
return (MutexId)osMutexNew(NULL);
}
int SemDelete(const unsigned long *semHandle)
void MutexLock(MutexId mutex)
{
if (semHandle == NULL) {
return -1;
if (mutex == NULL) {
return;
}
return LOS_SemDelete((unsigned int)*semHandle);
osMutexAcquire(mutex, osWaitForever);
}
int SemWait(const unsigned long *semHandle)
void MutexUnlock(MutexId mutex)
{
if (semHandle == NULL) {
return -1;
if (mutex == NULL) {
return;
}
return LOS_SemPend((unsigned int)*semHandle, LOS_WAIT_FOREVER);
}
int SemPost(const unsigned long *semHandle)
{
if (semHandle == NULL) {
return -1;
}
return LOS_SemPost((unsigned int)*semHandle);
osMutexRelease(mutex);
}
void CloseSocket(int *fd)
@@ -72,23 +53,34 @@ int WriteMsgQue(unsigned int queueID, const void *bufferAddr, unsigned int buffe
if (bufferAddr == NULL) {
return -1;
}
return LOS_QueueWriteCopy(queueID, (void*)bufferAddr, bufferSize, LOS_NO_WAIT);
(void)bufferSize;
return osMessageQueuePut((osMessageQueueId_t)queueID, (VOID*)bufferAddr, 0, 0);
}
int CreateMsgQue(const char *queueName,
unsigned short len, unsigned int *queueID,
unsigned int flags, unsigned short maxMsgSize)
{
if (queueName == NULL || queueID == NULL) {
osMessageQueueId_t id;
if (queueID == NULL) {
return -1;
}
int ret = LOS_QueueCreate(queueName, len, queueID, flags, maxMsgSize);
return ret;
(void)queueName;
(void)flags;
id = osMessageQueueNew(len, maxMsgSize, NULL);
if (NULL == id) {
return -1;
}
*queueID = (unsigned int)id;
return 0;
}
int DeleteMsgQue(unsigned int queueID)
{
return LOS_QueueDelete(queueID);
return osMessageQueueDelete((osMessageQueueId_t)queueID);
}
int ReadMsgQue(unsigned int queueID,
@@ -97,7 +89,7 @@ int ReadMsgQue(unsigned int queueID,
if (bufferAddr == NULL || bufferSize == NULL) {
return -1;
}
return LOS_QueueReadCopy(queueID, bufferAddr, bufferSize, LOS_WAIT_FOREVER);
return osMessageQueueGet((osMessageQueueId_t)queueID, bufferAddr, NULL, osWaitForever);
}
int SoftBusCheckPermission(const char* permissionName)
+23 -33
View File
@@ -13,47 +13,35 @@
* limitations under the License.
*/
#include "os_adapter.h"
#include <errno.h>
#include <mqueue.h>
#include <pthread.h>
#include <unistd.h>
int SemCreate(unsigned short count, unsigned long *semHandle)
MutexId MutexInit(void)
{
if (semHandle == NULL) {
return -1;
pthread_mutex_t *mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
if (mutex == NULL) {
return NULL;
}
(void)count;
int ret = sem_init((sem_t *)semHandle, 1, 0);
if (ret == 0) {
return sem_post((sem_t *)semHandle);
}
return ret;
(void)pthread_mutex_init(mutex, NULL);
return (MutexId)mutex;
}
int SemDelete(const unsigned long *semHandle)
void MutexLock(MutexId mutex)
{
if (semHandle == NULL) {
return -1;
if (mutex == NULL) {
return;
}
return sem_destroy((sem_t *)semHandle);
pthread_mutex_lock((pthread_mutex_t *)mutex);
}
int SemWait(const unsigned long *semHandle)
void MutexUnlock(MutexId mutex)
{
if (semHandle == NULL) {
return -1;
if (mutex == NULL) {
return;
}
return sem_wait((sem_t *)semHandle);
}
int SemPost(const unsigned long *semHandle)
{
if (semHandle == NULL) {
return -1;
}
return sem_post((sem_t *)semHandle);
pthread_mutex_unlock((pthread_mutex_t *)mutex);
}
void CloseSocket(int *fd)
@@ -79,9 +67,7 @@ int CreateMsgQue(const char *queueName,
newAttr.mq_flags = flags;
newAttr.mq_maxmsg = len;
newAttr.mq_msgsize = maxMsgSize;
/* Owner read and write permission - 0600 */
mode_t mode = (S_IRUSR | S_IWUSR);
int mqd = mq_open(queueName, O_RDWR | O_CREAT, mode, &newAttr);
int mqd = mq_open(queueName, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR, &newAttr);
if (mqd < 0) {
return -1;
}
@@ -96,7 +82,11 @@ int WriteMsgQue(unsigned int queueID,
if (bufferAddr == NULL) {
return -1;
}
return mq_send(queueID, bufferAddr, bufferSize, 0);
int ret = mq_send(queueID, bufferAddr, bufferSize, 0);
if (ret != 0) {
return -1;
}
return 0;
}
int DeleteMsgQue(unsigned int queueID)
@@ -126,8 +116,8 @@ int SoftBusCheckPermission(const char* permissionName)
return -1;
}
if (CheckPermission(0, permissionName) != GRANTED) {
SOFTBUS_PRINT("[SOFTBUS] CheckPermission fail\n");
if (CheckSelfPermission(permissionName) != GRANTED) {
SOFTBUS_PRINT("[SOFTBUS] CheckSelfPermission fail\n");
return -1;
}
return 0;
-5
View File
@@ -1,5 +0,0 @@
详见:https://gitee.com/openharmony/docs/blob/master/readme/分布式通信子系统README.md
see: https://gitee.com/openharmony/docs/blob/master/docs-en/readme/distributed-communication-subsystem.md
更多文档:https://openharmony.gitee.com/openharmony/docs
+4 -4
View File
@@ -24,9 +24,9 @@ if (ohos_kernel_type == "liteos_m") {
"../authmanager/include",
"//kernel/liteos_a/lib/libsec/include",
"//third_party/cJSON",
"//foundation/communication/services/softbus_lite/discovery/discovery_service/include",
"//foundation/communication/services/softbus_lite/os_adapter/include",
"//foundation/communication/interfaces/kits/softbus_lite/transport",
"//foundation/communication/softbus_lite/discovery/discovery_service/include",
"//foundation/communication/softbus_lite/os_adapter/include",
"//foundation/communication/softbus_lite/interfaces/kits/transport",
"//third_party/bounds_checking_function/include",
"$ohos_third_party_dir/lwip_sack/include",
"$ohos_third_party_dir/mbedtls/include",
@@ -51,6 +51,6 @@ if (ohos_kernel_type == "liteos_m") {
output_name = "trans_service"
sources = trans_service_sources
public_configs = [ ":trans_service_config" ]
public_deps = [ "//third_party/cJSON:cjson_shared" ]
public_deps = [ "//build/lite/config/component/cJSON:cjson_shared" ]
}
}
View File
View File
View File
View File
+1
View File
@@ -16,6 +16,7 @@
#ifndef TCP_SOCKET_H
#define TCP_SOCKET_H
#include <stdint.h>
#include <sys/types.h>
#include <sys/uio.h>
+13 -16
View File
@@ -17,7 +17,7 @@
#include <arpa/inet.h>
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
#include <los_task.h>
#include <cmsis_os.h>
#include <lwip/sockets.h>
#else
#include <errno.h>
@@ -44,7 +44,7 @@ static int g_listenFd = -1;
static int g_dataFd = -1;
static int g_maxFd = -1;
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
static unsigned int g_uwTskLoID;
static osThreadId_t g_uwTskLoID;
#endif
static void RefreshMaxFd(int fd)
@@ -160,17 +160,17 @@ int StartListener(BaseListener *callback, const char *ip)
return -DBE_BAD_PARAM;
}
unsigned int ret;
TSK_INIT_PARAM_S serverTask;
osThreadAttr_t attr;
attr.name = "trans_auth_task";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
attr.priority = osPriorityNormal5; // LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO -> cmsis prio
serverTask.pfnTaskEntry = (TSK_ENTRY_FUNC)WaitProcess;
serverTask.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
serverTask.pcName = "trans_auth_task";
serverTask.usTaskPrio = LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO;
serverTask.uwResved = LOS_TASK_STATUS_DETACHED;
ret = LOS_TaskCreate(&g_uwTskLoID, &serverTask);
if (ret != 0) {
g_uwTskLoID = osThreadNew((osThreadFunc_t)WaitProcess, NULL, &attr);
if (NULL == g_uwTskLoID) {
SOFTBUS_PRINT("[TRANS] StartListener task create fail\n");
return -1;
}
@@ -205,9 +205,6 @@ ThreadId AuthCreate(Runnable run, const ThreadAttr *attr)
if (errCode != 0) {
return NULL;
}
if (attr->name != NULL) {
(void)pthread_setname_np(threadId, attr->name);
}
return (ThreadId)threadId;
}
@@ -254,4 +251,4 @@ void StopListener(void)
{
CloseAuthSessionFd(g_listenFd);
CloseAuthSessionFd(g_dataFd);
}
}
-2
View File
@@ -40,8 +40,6 @@ TcpSession *CreateTcpSession(void)
tcpSession->busVersion = 0;
tcpSession->routeType = 0;
tcpSession->isAccepted = false;
tcpSession->uid = -1;
tcpSession->pid = -1;
tcpSession->seqNumList = malloc(sizeof(List));
if (tcpSession->seqNumList == NULL) {
free(tcpSession);
-2
View File
@@ -37,8 +37,6 @@ typedef struct {
int busVersion;
int routeType;
bool isAccepted;
uid_t uid;
pid_t pid;
List *seqNumList;
} TcpSession;
+72 -62
View File
@@ -17,7 +17,7 @@
#include <arpa/inet.h>
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
#include <los_task.h>
#include <cmsis_os.h>
#else
#include <pthread.h>
#include "pms_interface.h"
@@ -158,6 +158,33 @@ static int InitSelectList(const TcpSessionMgr *tsm, fd_set *rfds, fd_set *except
return maxFd;
}
static int InitGSessionMgr(void)
{
if (g_sessionMgr != NULL) {
return 0;
}
g_sessionMgr = malloc(sizeof(TcpSessionMgr));
if (g_sessionMgr == NULL) {
return TRANS_FAILED;
}
(void)memset_s(g_sessionMgr, sizeof(TcpSessionMgr), 0, sizeof(TcpSessionMgr));
g_sessionMgr->listenFd = -1;
g_sessionMgr->isSelectLoopRunning = false;
for (int i = 0; i < MAX_SESSION_SUM_NUM; i++) {
g_sessionMgr->sessionMap_[i] = NULL;
}
for (int i = 0; i < MAX_SESSION_SERVER_NUM; i++) {
g_sessionMgr->serverListenerMap[i] = NULL;
}
return 0;
}
static bool RemoveSession(TcpSessionMgr *tsm, int sessionId)
{
if (tsm == NULL || sessionId < 0) {
@@ -206,18 +233,20 @@ static void CloseTransSession(int sessionId)
static int RemoveExceptSessionFd(const TcpSessionMgr *tsm, fd_set *exceptfds)
{
if (tsm == NULL || tsm->listenFd == -1 || exceptfds == NULL) {
return TRANS_FAILED;
}
if (FD_ISSET(tsm->listenFd, exceptfds)) {
return TRANS_FAILED;
}
if (GetTcpMgrLock() != 0) {
return TRANS_FAILED;
}
if (g_sessionMgr == NULL || g_sessionMgr->listenFd == -1 || exceptfds == NULL) {
ReleaseTcpMgrLock();
return TRANS_FAILED;
}
if (g_sessionMgr->listenFd >= 0 && FD_ISSET(g_sessionMgr->listenFd, exceptfds)) {
ReleaseTcpMgrLock();
return TRANS_FAILED;
}
int result = TRANS_FAILED;
for (int i = 0; i < MAX_SESSION_SUM_NUM; i++) {
if ((tsm->sessionMap_[i]) == NULL) {
@@ -713,7 +742,10 @@ static void SelectSessionLoop(TcpSessionMgr *tsm)
static int CreateSessionServerInner(const char* moduleName, const char* sessionName, struct ISessionListener *listener)
{
if (g_sessionMgr == NULL || listener == NULL || sessionName == NULL || moduleName == NULL) {
if (g_sessionMgr == NULL && InitGSessionMgr() != 0) {
return TRANS_FAILED;
}
if (listener == NULL || sessionName == NULL || moduleName == NULL) {
SOFTBUS_PRINT("[TRANS] CreateSessionServer invalid param\n");
return TRANS_FAILED;
}
@@ -795,18 +827,19 @@ int StartSelectLoop(TcpSessionMgr *tsm)
return 0;
}
unsigned int sessionLoopTaskId = 0;
TSK_INIT_PARAM_S serverTask;
memset_s(&serverTask, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S));
serverTask.pfnTaskEntry = (TSK_ENTRY_FUNC)SelectSessionLoop;
serverTask.usTaskPrio = LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO;
serverTask.pcName = "trans_session_task";
serverTask.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
serverTask.uwResved = LOS_TASK_STATUS_DETACHED;
serverTask.auwArgs[0] = (uintptr_t)tsm;
SOFTBUS_PRINT("[TRANS] StartSelectLoop create trans_session_task\n");
unsigned int ret = LOS_TaskCreate(&sessionLoopTaskId, &serverTask);
if (ret != 0) {
osThreadId_t sessionLoopTaskId;
osThreadAttr_t attr;
attr.name = "trans_session_task";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
attr.priority = osPriorityNormal5; // LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO -> cmsis prio
sessionLoopTaskId = osThreadNew((osThreadFunc_t)SelectSessionLoop, (void *)tsm, &attr);
if (NULL == sessionLoopTaskId) {
SOFTBUS_PRINT("[TRANS] StartSelectLoop TaskCreate fail\n");
return TRANS_FAILED;
}
@@ -837,22 +870,22 @@ ThreadId TcpCreate(Runnable run, void *argv, const ThreadAttr *attr)
ret = pthread_attr_init(&threadAttr);
if (ret != 0) {
return NULL;
SOFTBUS_PRINT("[TRANS] TcpCreate pthread attr init fail\n");
}
ret = pthread_attr_setstacksize(&threadAttr, (attr->stackSize | MIN_STACK_SIZE));
if (ret != 0) {
return NULL;
SOFTBUS_PRINT("[TRANS] TcpCreate pthread attr setstacksize fail\n");
}
struct sched_param sched = {attr->priority};
ret = pthread_attr_setschedparam(&threadAttr, &sched);
if (ret != 0) {
return NULL;
SOFTBUS_PRINT("[TRANS] TcpCreate pthread attr setschedparam fail\n");
}
ret = pthread_key_create(&g_localKey, NULL);
if (ret != 0) {
return NULL;
SOFTBUS_PRINT("[TRANS] TcpCreate pthread key create fail\n");
}
pthread_t threadId = 0;
@@ -860,12 +893,6 @@ ThreadId TcpCreate(Runnable run, void *argv, const ThreadAttr *attr)
if (ret != 0) {
return NULL;
}
if (attr->name != NULL) {
ret = pthread_setname_np(threadId, attr->name);
if (ret != 0) {
SOFTBUS_PRINT("[TRANS] TcpCreate setname fail\n");
}
}
return (ThreadId)threadId;
}
@@ -890,36 +917,20 @@ int StartSelectLoop(TcpSessionMgr *tsm)
int CreateTcpSessionMgr(bool asServer, const char* localIp)
{
if (g_sessionMgr != NULL || localIp == NULL) {
if (localIp == NULL) {
return TRANS_FAILED;
}
g_sessionMgr = malloc(sizeof(TcpSessionMgr));
if (g_sessionMgr == NULL) {
return TRANS_FAILED;
}
(void)memset_s(g_sessionMgr, sizeof(TcpSessionMgr), 0, sizeof(TcpSessionMgr));
g_sessionMgr->asServer = asServer;
g_sessionMgr->listenFd = -1;
g_sessionMgr->isSelectLoopRunning = false;
if (InitTcpMgrLock() != 0 || GetTcpMgrLock() != 0) {
FreeSessionMgr();
return TRANS_FAILED;
}
for (int i = 0; i < MAX_SESSION_SUM_NUM; i++) {
g_sessionMgr->sessionMap_[i] = NULL;
}
for (int i = 0; i < MAX_SESSION_SERVER_NUM; i++) {
g_sessionMgr->serverListenerMap[i] = NULL;
}
if (ReleaseTcpMgrLock() != 0) {
int ret = InitGSessionMgr();
if (ReleaseTcpMgrLock() != 0 || ret != 0) {
FreeSessionMgr();
return TRANS_FAILED;
}
g_sessionMgr->asServer = asServer;
int listenFd = OpenTcpServer(localIp, DEFAULT_TRANS_PORT);
if (listenFd < 0) {
SOFTBUS_PRINT("[TRANS] CreateTcpSessionMgr OpenTcpServer fail\n");
@@ -950,17 +961,14 @@ int RemoveTcpSessionMgr(void)
if (g_sessionMgr == NULL) {
return TRANS_FAILED;
}
CloseAllSession(g_sessionMgr);
if (GetTcpMgrLock() != 0) {
return TRANS_FAILED;
}
CloseAllSession(g_sessionMgr);
CloseFd(g_sessionMgr->listenFd);
g_sessionMgr->listenFd = -1;
if (g_sessionMgr != NULL) {
free(g_sessionMgr);
g_sessionMgr = NULL;
}
if (ReleaseTcpMgrLock() != 0) {
return TRANS_FAILED;
@@ -970,7 +978,7 @@ int RemoveTcpSessionMgr(void)
int CreateSessionServer(const char* moduleName, const char* sessionName, struct ISessionListener *listener)
{
if (g_sessionMgr == NULL || moduleName == NULL || sessionName == NULL || listener == NULL) {
if (moduleName == NULL || sessionName == NULL || listener == NULL) {
return TRANS_FAILED;
}
@@ -1020,7 +1028,7 @@ static unsigned char *TransPackBytes(TcpSession *session, const unsigned char *s
return NULL;
}
int allLen = sendDataLen + TRANS_PACKET_HEAD_SIZE + OVERHEAD_LEN + SESSION_KEY_INDEX_SIZE;
int allLen = sendDataLen + TRANS_PACKET_HEAD_SIZE + OVERHEAD_LEN;
if (allLen > RECIVED_BUFF_SIZE || allLen <= 0) {
return NULL;
}
@@ -1052,6 +1060,8 @@ static unsigned char *TransPackBytes(TcpSession *session, const unsigned char *s
int dataLen = sendDataLen + OVERHEAD_LEN;
ret += memcpy_s(buf + offset, allLen - offset, &dataLen, SIZE_OF_INT);
offset += SIZE_OF_INT;
cipherKey.keybits = GCM_KEY_BITS_LEN_256;
ret += memcpy_s(cipherKey.key, SESSION_KEY_LENGTH, session->sessionKey, SESSION_KEY_LENGTH);
ret += memcpy_s(cipherKey.iv, IV_LEN, randomIv, IV_LEN);
free(randomIv);
@@ -1067,11 +1077,11 @@ static unsigned char *TransPackBytes(TcpSession *session, const unsigned char *s
return NULL;
}
*bufLen = cipherLen + TRANS_PACKET_HEAD_SIZE + SESSION_KEY_INDEX_SIZE;
*bufLen = cipherLen + TRANS_PACKET_HEAD_SIZE;
return buf;
}
int SendBytes(int sessionfd, const void *buf, unsigned int size)
int SendBytes(int sessionfd, const unsigned char *buf, unsigned int size)
{
if (buf == NULL || sessionfd < 0 || size == 0 || size > SEND_BUFF_MAX_SIZE) {
return TRANS_FAILED;
@@ -1087,7 +1097,7 @@ int SendBytes(int sessionfd, const void *buf, unsigned int size)
}
int cipherLen = 0;
char *cipherBuf = (char *)TransPackBytes(session, (unsigned char *)buf, size, &cipherLen);
char *cipherBuf = (char *)TransPackBytes(session, buf, size, &cipherLen);
if (cipherBuf == NULL) {
return TRANS_FAILED;
}
+1 -1
View File
@@ -71,4 +71,4 @@ int ReleaseTcpMgrLock(void)
pthread_mutex_unlock(&g_sessionManagerLock);
#endif
return DBE_SUCCESS;
}
}
+1 -1
View File
@@ -20,4 +20,4 @@ int InitTcpMgrLock(void);
int GetTcpMgrLock(void);
int ReleaseTcpMgrLock(void);
#endif // TRANS_LOCK_H
#endif // TRANS_SERVICE_UTIL_H
-2
View File
@@ -14,8 +14,6 @@
*/
#include "message.h"
#include <stdio.h>
int GetJsonInt(const cJSON *root, const char *name, int *result)
{
if (root == NULL || name == NULL || result == NULL) {
+1 -12
View File
@@ -12,10 +12,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include "tcp_socket.h"
#include <arpa/inet.h>
#if defined(__LITEOS_M__) || defined(__LITEOS_RISCV__)
#include <lwip/sockets.h>
#else
@@ -26,7 +26,6 @@
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
@@ -74,10 +73,8 @@ int OpenTcpServer(const char *ip, uint16_t port)
errno = 0;
int rc = inet_pton(AF_INET, ip, &addr.sin_addr);
if (rc <= 0) {
SOFTBUS_PRINT("[TRANS] OpenTcpServer inet_pton fail, rc=%d:%s\n", rc, strerror(errno));
return -DBE_BAD_IP;
}
SOFTBUS_PRINT("[TRANS] OpenTcpServer inet_pton rc=%d\n", rc);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
@@ -85,18 +82,13 @@ int OpenTcpServer(const char *ip, uint16_t port)
errno = 0;
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
SOFTBUS_PRINT("[TRANS] OpenTcpServer socket fail, rc=%d:%s\n", rc, strerror(errno));
return -DBE_OPEN_SOCKET;
}
SOFTBUS_PRINT("[TRANS] OpenTcpServer fd=%d\n", fd);
SetServerOption(fd);
errno = 0;
rc = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
if (rc < 0) {
SOFTBUS_PRINT("[TRANS] OpenTcpServer bind fail, rc=%d:%s\n", rc, strerror(errno));
ShutDown(fd);
return -DBE_BIND_SOCKET;
}
@@ -111,7 +103,6 @@ int GetSockPort(int fd)
int rc = getsockname(fd, (struct sockaddr *)&addr, &addrLen);
if (rc != 0) {
SOFTBUS_PRINT("[TRANS] GetSockPort getsockname fail, fd=%d, rc=%d,%s", fd, rc, strerror(errno));
return rc;
}
return ntohs(addr.sin_port);
@@ -159,11 +150,9 @@ static int32_t TcpRecvMessages(int fd, char *buf, uint32_t len, int timeout, int
errno = 0;
int32_t rc = recv(fd, buf, len, flags);
if ((rc == -1) && (errno == EAGAIN)) {
SOFTBUS_PRINT("[TRANS] TcpRecvMessages recv fail, errno is eagain\n");
rc = 0;
} else if (rc <= 0) {
rc = -1;
SOFTBUS_PRINT("[TRANS] TcpRecvMessage recv fail, errno is %s\n", strerror(errno));
}
return rc;
}