diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md new file mode 100644 index 0000000000000000000000000000000000000000..7a44a95c9963726fb5e8452b245e8441787de5b2 --- /dev/null +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -0,0 +1,34 @@ +**Issue编号**: + +**描述**: + +**安全及低级编码自检:** + +- [ ] 【变量初始化】变量使用前保证赋有效初值 +- [ ] 【变量初始化】结构体预留字段也必须初始化为0,不允许出现随机值 +- [ ] 【变量初始化】指针变量必须显示初始化为空 +- [ ] 【内存和资源】涉及内存拷贝时合理校验目标内存大小,保证目标内存大于等于源内存 +- [ ] 【内存和资源】进行字符串操作时,如字符串复制、申请字符串内存等,需要考虑字符串结束符 +- [ ] 【内存和资源】cJSON指针在异常分支里均需考虑内存释放(cJSON_free/cJSON_Delete),防止内存泄漏 +- [ ] 【内存和资源】内存资源、文件句柄、管道资源、Socket句柄异常退出时要及时关闭 +- [ ] 【指针】malloc申请内存后必须判断是否为空 +- [ ] 【指针】指针解引用或释放前判空(lamda表达式,异步任务等使用指针前需判空) +- [ ] 【指针】内存释放后立即置空,防止出现UAF +- [ ] 【指针】循环时容器的增、删、改操作,必须保证迭代器有效 +- [ ] 【指针】禁止将栈内存地址作为返回值或赋值给全局变量 +- [ ] 【数值边界】加法、乘法、减法操作,必须进行溢出和翻转保护,确保先校验再运算 +- [ ] 【数值边界】除法、求余操作必须进行除零保护 +- [ ] 【数值边界】循环变量用整型,禁止使用浮点型 +- [ ] 【数值边界】循环退出条件一定确保可达,防止出现死循环等问题 +- [ ] 【数值边界】不同大小结构体禁止强转 +- [ ] 【安全隐私】禁止使用非安全函数,使用封装好的安全函数 +- [ ] 【安全隐私】日志必须检查PassWord/位置信息/networkId/devId/uuid/udid等关键字,避免明文打印敏感信息 +- [ ] 【入参及权限校验】对函数入参坚持先校验后使用的原则(指针判空、整型变量校验范围) +- [ ] 【入参及权限校验】跨进程调用需注意权限校验,对外部传入的PID、tokenID进行权限校验 +- [ ] 【条件竞争】共享数据均需加锁保护,并且锁配对使用 +- [ ] 【条件竞争】条件变量正确加锁,消除条件变量唤醒丢失等问题 +- [ ] 【条件竞争】加锁范围确保合理,避免过大或过小导致死锁问题 + +**TDD结果**: + +**XTS结果**: diff --git a/BUILD.gn b/BUILD.gn index 71aed68449e47af4cf6194b7532a0c41993ef8a9..f35ac38307551c55586d68f30827f89caee4114e 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -59,6 +59,7 @@ if (defined(ohos_lite)) { } group("device_manager_fwk") { deps = [ + "interfaces/cj:cj_distributed_device_manager_ffi", "interfaces/inner_kits/native_cpp:devicemanagersdk", "interfaces/kits:devicemanager_native_js", ] diff --git a/README.md b/README.md index e5359e382e2ccd0fde4c729a8105a4138c2d35f9..db56f0a4849aa8e27538e6081e27ac4627491ffe 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ foundation/distributedhardware/device_manager │ └── resources # Resource configuration files for PIN display ServiceExtensionAbility ├── figures ├── interfaces +| ├── cj # Cangjie FFI interfaces and their implementation │ ├── inner_kits # Internal interfaces and their implementation │ │ └── native_cpp # Internal native interfaces and their implementation │ │ ├── include diff --git a/README_zh.md b/README_zh.md index a69927fa1549fe0287f01e51ee1dde9824c37e52..33fd30bc971bac08a4a09c13c2df86cfe0aefeb1 100644 --- a/README_zh.md +++ b/README_zh.md @@ -38,6 +38,7 @@ foundation/distributedhardware/distributedhardware_device_manager │ └── resources # DM PIN码显示ServiceExtensionAbility相关资源配置文件目录 ├── figures ├── interfaces +| ├── cj # 仓颉接口ffi层实现存放目录 │ ├── inner_kits # 内部接口及实现存放目录 │ │ └── native_cpp # 内部native接口及实现存放目录 │ │ ├── include diff --git a/bundle.json b/bundle.json index 4270607a0a255322f6ea164e30529a4299430444..dd2be1b8dad6fb5ddb3d4c0337a7ddb2e3352cb4 100644 --- a/bundle.json +++ b/bundle.json @@ -29,13 +29,13 @@ "ability_base", "ability_runtime", "access_token", - "benchmark", "bounds_checking_function", "bluetooth", "bundle_framework", "cJSON", "c_utils", "common_event_service", + "data_share", "device_auth", "device_info_manager", "dsoftbus", @@ -48,9 +48,9 @@ "init", "ipc", "json", + "kv_store", "memmgr", "napi", - "node", "openssl", "os_account", "power_manager", diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index f2130975004d8fea3dc05838f4a4c08d358a27ee..137bc410170a3c096aabb583923313c600211789 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -29,13 +29,11 @@ enum DMIpcCmdInterfaceCode { GET_UDID_BY_NETWORK, GET_UUID_BY_NETWORK, GET_NETWORKTYPE_BY_NETWORK, - START_DEVICE_DISCOVER, - START_DEVICE_DISCOVERY, - STOP_DEVICE_DISCOVER, PUBLISH_DEVICE_DISCOVER, UNPUBLISH_DEVICE_DISCOVER, AUTHENTICATE_DEVICE, UNAUTHENTICATE_DEVICE, + STOP_AUTHENTICATE_DEVICE, VERIFY_AUTHENTICATION, SERVER_DEVICE_STATE_NOTIFY, SERVER_DEVICE_FOUND, @@ -90,6 +88,14 @@ enum DMIpcCmdInterfaceCode { CHECK_ACCESS_CONTROL, CHECK_SAME_ACCOUNT, SHIFT_LNN_GEAR, + SET_DN_POLICY, + REMOTE_DEVICE_TRUST_CHANGE, + SERVER_DEVICE_SCREEN_STATE_NOTIFY, + GET_DEVICE_SCREEN_STATUS, + GET_NETWORKID_BY_UDID, + SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, + SINK_BIND_TARGET_RESULT, + SYNC_CALLBACK, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 94993cc7c4e117007a28ffa2eef931a175eb9ab2..8c9787dd1f54e395317136972eef552167285db7 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -18,15 +18,19 @@ #include #include - -#include "dm_device_info.h" - #include "nlohmann/json.hpp" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { +namespace { + const std::string PRINT_LIST_SPLIT = ", "; + const int32_t LIST_SPLIT_LEN = 2; +} std::string GetAnonyString(const std::string &value); +std::string GetAnonyStringList(const std::vector &values); std::string GetAnonyInt32(const int32_t value); +std::string GetAnonyInt32List(const std::vector &values); bool IsNumberString(const std::string &inputString); bool IsString(const nlohmann::json &jsonObj, const std::string &key); bool IsInt32(const nlohmann::json &jsonObj, const std::string &key); @@ -38,6 +42,66 @@ std::string ConvertMapToJsonString(const std::map &par void ParseMapFromJsonString(const std::string &jsonStr, std::map ¶mMap); bool IsInvalidPeerTargetId(const PeerTargetId &targetId); std::string ConvertCharArray2String(const char *srcData, uint32_t srcLen); +int32_t StringToInt(const std::string &str, int32_t base); +int64_t StringToInt64(const std::string &str, int32_t base); +void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec); +bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); +bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); +std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId); +std::string GetCallerPkgName(const std::string &pkgName); +uint16_t GetSubscribeId(const std::string &pkgName); +template +std::string GetAnonyInteger(const T value) +{ + std::string tempString = std::to_string(value); + size_t length = tempString.length(); + if (length == 0x01) { + tempString[0] = '*'; + return tempString; + } + for (size_t i = 1; i < length - 1; i++) { + tempString[i] = '*'; + } + return tempString; +} + +template +std::string GetAnonyIntegerList(const std::vector &values) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &v : values) { + temp += GetAnonyInteger(v) + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + +template +std::string GetIntegerList(const std::vector &values) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &v : values) { + temp += std::to_string(v) + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + +bool IsIdLengthValid(const std::string &inputID); +bool IsMessageLengthValid(const std::string &inputMessage); +bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId); +bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent); +std::string SafetyDump(const nlohmann::json &jsonObj); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 00927bc59a75bf374cbd5f2d8dbe82fbfa6ce884..09bfd45bd447b71f39331913e0acc25c2a0bea09 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -37,6 +37,7 @@ enum { STOP_BIND = 1, /* Transfer to the other end device, not define specification error code */ + ERR_DM_NOT_SYSTEM_APP = 202, ERR_DM_TIME_OUT = -20001, ERR_DM_UNSUPPORTED_AUTH_TYPE = -20018, ERR_DM_AUTH_BUSINESS_BUSY = -20019, @@ -48,6 +49,7 @@ enum { ERR_DM_AUTH_CODE_INCORRECT = -20053, ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY = -20056, ERR_DM_SYNC_DELETE_DEVICE_REPEATED = -20058, + ERR_DM_VERSION_INCOMPATIBLE = -20059, ERR_DM_FAILED = 96929744, ERR_DM_NOT_INIT = 96929746, @@ -114,6 +116,9 @@ enum { ERR_DM_SOFTBUS_STOP_DISCOVERY_DEVICE = 96929815, ERR_DM_INVALID_JSON_STRING = 96929816, ERR_DM_GET_DATA_SHA256_HASH = 96929817, + ERR_DM_CHANNLE_OPEN_TIMEOUT = 96929818, + ERR_DM_ADD_GOUTP_TIMEOUT = 96929819, + ERR_DM_INPUT_TIMEOUT = 96929820, }; constexpr const char* TAG_GROUP_ID = "groupId"; @@ -128,9 +133,10 @@ constexpr const char* DM_ITF_VER = "1.1"; constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; constexpr const char* DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; constexpr const char* DM_PIN_HOLDER_SESSION_NAME = "ohos.distributedhardware.devicemanager.pinholder"; -constexpr const char* DM_UNBIND_SESSION_NAME = "ohos.distributedhardware.devicemanager.unbind"; +constexpr const char* DM_SYNC_USERID_SESSION_NAME = "ohos.distributedhardware.devicemanager.syncuserid"; constexpr const char* DM_CAPABILITY_OSD = "osdCapability"; constexpr const char* DM_CAPABILITY_APPROACH = "approach"; +constexpr const char* DM_CAPABILITY_TOUCH = "touch"; constexpr const char* DM_CAPABILITY_CASTPLUS = "castPlus"; constexpr const char* DM_CAPABILITY_VIRTUAL_LINK = "virtualLink"; constexpr const char* DM_CAPABILITY_SHARE = "share"; @@ -193,9 +199,13 @@ constexpr const char* FILTER_PARA_INCLUDE_TRUST = "FILTER_INCLUDE_TRUST"; constexpr const char* CONN_ADDR_TYPE_ID = "ID_TYPE"; constexpr const char* CONN_ADDR_TYPE_BR = "BR_TYPE"; constexpr const char* CONN_ADDR_TYPE_BLE = "BLE_TYPE"; +constexpr const char* CONN_ADDR_TYPE_USB = "USB_TYPE"; constexpr const char* CONN_ADDR_TYPE_WLAN_IP = "WLAN_IP_TYPE"; constexpr const char* CONN_ADDR_TYPE_ETH_IP = "ETH_IP_TYPE"; +// Softbus connection address type int +constexpr int32_t CONNECTION_ADDR_USB = 5; + // Parameter Key constexpr const char* PARAM_KEY_META_TYPE = "META_TYPE"; constexpr const char* PARAM_KEY_TARGET_ID = "TARGET_ID"; @@ -203,6 +213,8 @@ constexpr const char* PARAM_KEY_BR_MAC = "BR_MAC"; constexpr const char* PARAM_KEY_BLE_MAC = "BLE_MAC"; constexpr const char* PARAM_KEY_WIFI_IP = "WIFI_IP"; constexpr const char* PARAM_KEY_WIFI_PORT = "WIFI_PORT"; +constexpr const char* PARAM_KEY_USB_IP = "USB_IP"; +constexpr const char* PARAM_KEY_USB_PORT = "USB_PORT"; constexpr const char* PARAM_KEY_AUTH_TOKEN = "AUTH_TOKEN"; constexpr const char* PARAM_KEY_AUTH_TYPE = "AUTH_TYPE"; constexpr const char* PARAM_KEY_PIN_CODE = "PIN_CODE"; @@ -223,10 +235,15 @@ constexpr const char* PARAM_KEY_FILTER_OPTIONS = "FILTER_OPTIONS"; constexpr const char* PARAM_KEY_BIND_EXTRA_DATA = "BIND_EXTRA_DATA"; constexpr const char* PARAM_KEY_OS_TYPE = "OS_TYPE"; constexpr const char* PARAM_KEY_OS_VERSION = "OS_VERSION"; +constexpr const char* PARAM_KEY_UDID = "udid"; +constexpr const char* PARAM_KEY_UUID = "uuid"; constexpr const char* DM_CONNECTION_DISCONNECTED = "DM_CONNECTION_DISCONNECTED"; constexpr const char* BIND_LEVEL = "bindLevel"; constexpr const char* TOKENID = "tokenId"; constexpr const char* DM_BIND_RESULT_NETWORK_ID = "DM_BIND_RESULT_NETWORK_ID"; +constexpr const char* PARAM_KEY_POLICY_STRATEGY_FOR_BLE = "DM_POLICY_STRATEGY_FOR_BLE"; +constexpr const char* PARAM_KEY_POLICY_TIME_OUT = "DM_POLICY_TIMEOUT"; +constexpr const char* DEVICE_SCREEN_STATUS = "DEVICE_SCREEN_STATUS"; // screen state constexpr int32_t DM_SCREEN_UNKNOWN = -1; diff --git a/common/include/ipc/model/ipc_credential_auth_status_req.h b/common/include/ipc/model/ipc_credential_auth_status_req.h new file mode 100644 index 0000000000000000000000000000000000000000..730d077bf7a4a1185784196d3f09ec9cab551ee8 --- /dev/null +++ b/common/include/ipc/model/ipc_credential_auth_status_req.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_IPC_NOTIFY_CREDENTIAL_AUTH_STATUS_REQ_H +#define OHOS_DM_IPC_NOTIFY_CREDENTIAL_AUTH_STATUS_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyCredentialAuthStatusReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyCredentialAuthStatusReq); + +public: + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::GetDeviceList + * @tc.desc: Get DeviceList of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + std::string GetDeviceList() const + { + return deviceList_; + } + + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::SetDeviceList + * @tc.desc: Set DeviceList of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + void SetDeviceList(const std::string &deviceList) + { + deviceList_ = deviceList; + } + + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::GetDeviceTypeId + * @tc.desc: Get DeviceType of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + uint16_t GetDeviceTypeId() const + { + return deviceTypeId_; + } + + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::SetDeviceTypeId + * @tc.desc: Set DeviceType of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + void SetDeviceTypeId(uint16_t deviceTypeId) + { + deviceTypeId_ = deviceTypeId; + } + + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::GetErrCode + * @tc.desc: Get ErrCode of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + int32_t GetErrCode() const + { + return errcode_; + } + + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::SetErrCode + * @tc.desc: Set ErrCode of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + void SetErrCode(int32_t errcode) + { + errcode_ = errcode; + } + +private: + std::string deviceList_; + uint16_t deviceTypeId_ = 0; + int32_t errcode_ = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_NOTIFY_CREDENTIAL_AUTH_STATUS_REQ_H diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_get_device_screen_status_req.h similarity index 37% rename from common/include/ipc/model/ipc_start_discovery_req.h rename to common/include/ipc/model/ipc_get_device_screen_status_req.h index 421402c8549e6c18485c33db75fc04364d40d16f..5c223ccfa18d1b0646caa94a364aae2eb0da6fb2 100644 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ b/common/include/ipc/model/ipc_get_device_screen_status_req.h @@ -1,10 +1,10 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,62 +13,40 @@ * limitations under the License. */ -#ifndef OHOS_DM_IPC_START_DISCOVERY_REQ_H -#define OHOS_DM_IPC_START_DISCOVERY_REQ_H +#ifndef OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_REQ_H -#include "dm_subscribe_info.h" #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { -class IpcStartDiscoveryReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStartDiscoveryReq); +class IpcGetDeviceScreenStatusReq : public IpcReq { + DECLARE_IPC_MODEL(IpcGetDeviceScreenStatusReq); public: /** - * @tc.name: IpcStartDiscoveryReq::GetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Get SubscribeInfo + * @tc.name: IpcGetDeviceScreenStatusReq::GetNetWorkId + * @tc.desc: Ipc Get Device Screen Status request Get NetWorkId * @tc.type: FUNC */ - const DmSubscribeInfo &GetSubscribeInfo() const + const std::string GetNetWorkId() const { - return subscribeInfo_; + return netWorkId_; } /** - * @tc.name: IpcStartDiscoveryReq::SetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Set SubscribeInfo + * @tc.name: IpcGetDeviceScreenStatusReq::SetNetWorkId + * @tc.desc: Ipc Get Device Screen Status request Set NetWorkId * @tc.type: FUNC */ - void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) + void SetNetWorkId(const std::string &netWorkId) { - subscribeInfo_ = subscribeInfo; - } - - /** - * @tc.name: IpcStartDiscoveryReq::GetExtra - * @tc.desc: Ipc Start Discovery Request Get Extra - * @tc.type: FUNC - */ - const std::string &GetExtra() const - { - return extra_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetExtra - * @tc.desc: Ipc Start Discovery Request Set Extra - * @tc.type: FUNC - */ - void SetExtra(const std::string &extra) - { - extra_ = extra; + netWorkId_ = netWorkId; } private: - std::string extra_; - DmSubscribeInfo subscribeInfo_; + std::string netWorkId_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IPC_START_DISCOVERY_REQ_H +#endif // OOHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_REQ_H diff --git a/common/include/ipc/model/ipc_get_device_screen_status_rsp.h b/common/include/ipc/model/ipc_get_device_screen_status_rsp.h new file mode 100644 index 0000000000000000000000000000000000000000..f9be792dd346f135d46824873fa831eb0fdce839 --- /dev/null +++ b/common/include/ipc/model/ipc_get_device_screen_status_rsp.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_RSP_H + +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetDeviceScreenStatusRsp : public IpcRsp { + DECLARE_IPC_MODEL(IpcGetDeviceScreenStatusRsp); + +public: + /** + * @tc.name: IpcGetDeviceScreenStatusRsp::GetScreenStatus + * @tc.desc: Get ScreenStatus for Ipc to get information through ScreenStatusRsp + * @tc.type: FUNC + */ + int32_t GetScreenStatus() const + { + return screenStatus_; + } + + /** + * @tc.name: IpcGetDeviceScreenStatusRsp::SetScreenStatus + * @tc.desc: Set ScreenStatus for Ipc to get information through ScreenStatusRsp + * @tc.type: FUNC + */ + void SetScreenStatus(const int32_t &screenStatus) + { + screenStatus_ = screenStatus; + } + +private: + int32_t screenStatus_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_RSP_H diff --git a/common/include/ipc/model/ipc_get_info_by_network_req.h b/common/include/ipc/model/ipc_get_info_by_network_req.h index d3bec11aaade7370c7ea3f4c6c39c472597b6661..ea42810315b08268f89becd50ca15ee25d30ab40 100644 --- a/common/include/ipc/model/ipc_get_info_by_network_req.h +++ b/common/include/ipc/model/ipc_get_info_by_network_req.h @@ -44,8 +44,29 @@ public: netWorkId_ = netWorkId; } + /** + * @tc.name: IpcGetInfoByNetWorkReq::GetUdid + * @tc.desc: Ipc Get Info By NetWork request Get udid + * @tc.type: FUNC + */ + const std::string GetUdid() const + { + return udid_; + } + + /** + * @tc.name: IpcGetInfoByNetWorkReq::SetUdid + * @tc.desc: Ipc Get Info By NetWork request Set udid + * @tc.type: FUNC + */ + void SetUdid(const std::string &udid) + { + udid_ = udid; + } + private: std::string netWorkId_; + std::string udid_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_get_info_by_network_rsp.h b/common/include/ipc/model/ipc_get_info_by_network_rsp.h index ed95d18d543948cd16a47a550019efa517a09753..e121e247af8bc7e932bcac480e41669e79d132b0 100644 --- a/common/include/ipc/model/ipc_get_info_by_network_rsp.h +++ b/common/include/ipc/model/ipc_get_info_by_network_rsp.h @@ -106,9 +106,30 @@ public: securityLevel_ = securityLevel; } + /** + * @tc.name: IpcGetInfoByNetWorkRsp::GetNetWorkId + * @tc.desc: Ipc Get Info By NetWork request Get NetWorkId + * @tc.type: FUNC + */ + const std::string GetNetWorkId() const + { + return netWorkId_; + } + + /** + * @tc.name: IpcGetInfoByNetWorkRsp::SetNetWorkId + * @tc.desc: Ipc Get Info By NetWork request Set NetWorkId + * @tc.type: FUNC + */ + void SetNetWorkId(const std::string &netWorkId) + { + netWorkId_ = netWorkId; + } + private: std::string udid_; std::string uuid_; + std::string netWorkId_; int32_t networkType_; int32_t securityLevel_; }; diff --git a/common/include/ipc/model/ipc_notify_devicetrustchange_req.h b/common/include/ipc/model/ipc_notify_devicetrustchange_req.h new file mode 100644 index 0000000000000000000000000000000000000000..4af68e5522d8ef8602fbe421471498814fd104ef --- /dev/null +++ b/common/include/ipc/model/ipc_notify_devicetrustchange_req.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_IPC_NOTIFY_DEVICETRUSTCHANGE_REQ_H +#define OHOS_DM_IPC_NOTIFY_DEVICETRUSTCHANGE_REQ_H +#include "ipc_req.h" +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyDevTrustChangeReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyDevTrustChangeReq); + +public: + int32_t GetAuthForm() const + { + return authForm_; + } + void SetAuthForm(int32_t authForm) + { + authForm_ = authForm; + } + const std::string &GetUdid() const + { + return udid_; + } + void SetUdid(const std::string &udid) + { + udid_ = udid; + } + const std::string &GetUuid() const + { + return uuid_; + } + void SetUuid(const std::string &uuid) + { + uuid_ = uuid; + } +private: + int32_t authForm_; + std::string udid_; + std::string uuid_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_NOTIFY_DEVICETRUSTCHANGE_REQ_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index fd0d0c7855f30f8847666a5e5ca2665356e1d157..f16984c71256738b4ae1e97238c2dba9e2394d1c 100644 --- a/common/include/ipc/model/ipc_req.h +++ b/common/include/ipc/model/ipc_req.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include #include "ipc_def.h" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -36,8 +37,18 @@ public: pkgName_ = pkgName; } + const ProcessInfo GetProcessInfo() const + { + return processInfo_; + } + + void SetProcessInfo(const ProcessInfo &processInfo) + { + processInfo_ = processInfo; + } private: std::string pkgName_; + ProcessInfo processInfo_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_stop_discovery_req.h b/common/include/ipc/model/ipc_sync_callback_req.h similarity index 53% rename from common/include/ipc/model/ipc_stop_discovery_req.h rename to common/include/ipc/model/ipc_sync_callback_req.h index d5d2ae5ec5de0877bbc322c72e8db5a7765b35ab..cf9c3e0a82003194821adffc725c3e4fa671c5d3 100644 --- a/common/include/ipc/model/ipc_stop_discovery_req.h +++ b/common/include/ipc/model/ipc_sync_callback_req.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,42 +13,39 @@ * limitations under the License. */ -#ifndef OHOS_DM_IPC_STOP_DISCOVERY_REQ_H -#define OHOS_DM_IPC_STOP_DISCOVERY_REQ_H - -#include +#ifndef OHOS_DM_IPC_SYNC_CALLBACK_REQ_H +#define OHOS_DM_IPC_SYNC_CALLBACK_REQ_H #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { -class IpcStopDiscoveryReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStopDiscoveryReq); +class IpcSyncCallbackReq : public IpcReq { + DECLARE_IPC_MODEL(IpcSyncCallbackReq); public: /** - * @tc.name: IpcStopDiscoveryReq::GetSubscribeId - * @tc.desc: Ipc stop discovery request get subscription id + * @tc.name: IpcSyncCallbackReq::GetDmCommonNotifyEvent + * @tc.desc: Get notifyEvent of the Ipc Request * @tc.type: FUNC */ - uint16_t GetSubscribeId() const + int32_t GetDmCommonNotifyEvent() const { - return subscribeId_; + return dmCommonNotifyEvent_; } /** - * @tc.name: IpcStopDiscoveryReq::SetSubscribeId - * @tc.desc: Ipc stop discovery request set subscription id + * @tc.name: IpcSyncCallbackReq::SetDmCommonNotifyEvent + * @tc.desc: Set notifyEvent of the Ipc Request * @tc.type: FUNC */ - void SetSubscribeId(uint16_t subscribeId) + void SetDmCommonNotifyEvent(int32_t dmCommonNotifyEvent) { - subscribeId_ = subscribeId; + dmCommonNotifyEvent_ = dmCommonNotifyEvent; } - private: - uint16_t subscribeId_ { 0 }; + int32_t dmCommonNotifyEvent_ = 0; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IPC_STOP_DISCOVERY_REQ_H +#endif // OHOS_DM_IPC_SYNC_CALLBACK_REQ_H diff --git a/common/include/ipc/standard/ipc_cmd_register.h b/common/include/ipc/standard/ipc_cmd_register.h index 650a69950a4531611b59455633eb4b58cfa36c51..885abc550e7ad2cdd3ecdf2e1e230214b36147a6 100644 --- a/common/include/ipc/standard/ipc_cmd_register.h +++ b/common/include/ipc/standard/ipc_cmd_register.h @@ -18,6 +18,7 @@ #include #include +#include #include #include "device_manager_ipc_interface_code.h" @@ -76,6 +77,7 @@ public: */ void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) { + std::lock_guard autoLock(setIpcRequestFuncMapLock_); setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); }; @@ -86,6 +88,7 @@ public: */ void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) { + std::lock_guard autoLock(readResponseFuncMapLock_); readResponseFuncMap_.emplace(cmdCode, readResponseFunc); }; @@ -96,6 +99,7 @@ public: */ void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) { + std::lock_guard autoLock(onIpcCmdFuncMapLock_); onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); }; @@ -121,8 +125,11 @@ public: int32_t OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply); private: + std::mutex setIpcRequestFuncMapLock_; std::unordered_map setIpcRequestFuncMap_; + std::mutex readResponseFuncMapLock_; std::unordered_map readResponseFuncMap_; + std::mutex onIpcCmdFuncMapLock_; std::unordered_map onIpcCmdFuncMap_; }; } // namespace DistributedHardware diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 3ede31124e3c528ee3eb03e221b56d2c05180cfb..f23e723d2566274d6794c51db971369088067940 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -15,11 +15,14 @@ #include "dm_anonymous.h" #include "dm_log.h" - +#include namespace OHOS { namespace DistributedHardware { namespace { constexpr uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; +constexpr uint32_t MAX_MAP_LEN = 1000; +constexpr uint32_t MAX_INT_LEN = 20; +constexpr uint32_t MAX_ID_LEN = 256; } std::string GetAnonyString(const std::string &value) @@ -48,6 +51,21 @@ std::string GetAnonyString(const std::string &value) return res; } +std::string GetAnonyStringList(const std::vector &values) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &v : values) { + temp += GetAnonyString(v) + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + std::string GetAnonyInt32(const int32_t value) { std::string tempString = std::to_string(value); @@ -62,18 +80,33 @@ std::string GetAnonyInt32(const int32_t value) return tempString; } +std::string GetAnonyInt32List(const std::vector &values) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &v : values) { + temp += GetAnonyInt32(v) + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + bool IsNumberString(const std::string &inputString) { LOGI("IsNumberString for DeviceManagerNapi"); - if (inputString.length() == 0) { - LOGE("inputString is Null"); + if (inputString.length() == 0 || inputString.length() > MAX_INT_LEN) { + LOGE("inputString is Null or inputString length is too long"); return false; } - const int32_t MIN_ASCLL_NUM = 48; - const int32_t MAX_ASCLL_NUM = 57; + const int32_t MIN_ASCII_NUM = 48; + const int32_t MAX_ASCII_NUM = 57; for (size_t i = 0; i < inputString.length(); i++) { int num = (int)inputString[i]; - if (num >= MIN_ASCLL_NUM && num <= MAX_ASCLL_NUM) { + if (num >= MIN_ASCII_NUM && num <= MAX_ASCII_NUM) { continue; } else { return false; @@ -142,12 +175,16 @@ bool IsBool(const nlohmann::json &jsonObj, const std::string &key) std::string ConvertMapToJsonString(const std::map ¶mMap) { std::string jsonStr = ""; + if (paramMap.size() > MAX_MAP_LEN) { + LOGE("invalid paramMap"); + return jsonStr; + } if (!paramMap.empty()) { nlohmann::json jsonObj; for (const auto &it : paramMap) { jsonObj[it.first] = it.second; } - jsonStr = jsonObj.dump(); + jsonStr = SafetyDump(jsonObj); } return jsonStr; } @@ -157,6 +194,10 @@ void ParseMapFromJsonString(const std::string &jsonStr, std::map MAX_MAP_LEN) { + LOGE("invalid paramMap"); + return; + } nlohmann::json paramJson = nlohmann::json::parse(jsonStr, nullptr, false); if (paramJson.is_discarded()) { return; @@ -189,5 +230,146 @@ std::string ConvertCharArray2String(const char *srcData, uint32_t srcLen) delete[] dstData; return temp; } + +int32_t StringToInt(const std::string &str, int32_t base) +{ + if (str.empty()) { + LOGE("Str is empty."); + return 0; + } + char *nextPtr = nullptr; + long result = strtol(str.c_str(), &nextPtr, base); + if (errno == ERANGE || *nextPtr != '\0') { + LOGE("parse int error"); + return 0; + } + return static_cast(result); +} + +int64_t StringToInt64(const std::string &str, int32_t base) +{ + if (str.empty()) { + LOGE("Str is empty."); + return 0; + } + char *nextPtr = nullptr; + int64_t result = strtoll(str.c_str(), &nextPtr, base); + if (errno == ERANGE || nextPtr == nullptr || nextPtr == str.c_str() || *nextPtr != '\0') { + LOGE("parse int error"); + return 0; + } + return result; +} + +void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec) +{ + std::istringstream iss(str); + std::string item = ""; + while (getline(iss, item, split)) { + numVec.push_back(atoi(item.c_str())); + } +} + +bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum) +{ + for (uint32_t index = 0; index < std::min(srcVecNum.size(), sinkVecNum.size()); index++) { + if (srcVecNum[index] > sinkVecNum[index]) { + return true; + } else if (srcVecNum[index] < sinkVecNum[index]) { + return false; + } else { + continue; + } + } + if (srcVecNum.size() > sinkVecNum.size()) { + return true; + } + return false; +} + +bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion) +{ + LOGI("remoteVersion %{public}s, oldVersion %{public}s.", remoteVersion.c_str(), oldVersion.c_str()); + std::vector remoteVersionVec; + std::vector oldVersionVec; + VersionSplitToInt(remoteVersion, '.', remoteVersionVec); + VersionSplitToInt(oldVersion, '.', oldVersionVec); + return CompareVecNum(remoteVersionVec, oldVersionVec); +} + +std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId) +{ + std::string strTemp = pkgName + "#" + std::to_string(subscribeId); + return strTemp; +} + +std::string GetCallerPkgName(const std::string &pkgName) +{ + std::istringstream stream(pkgName); + std::string item = ""; + getline(stream, item, '#'); + return item; +} + +uint16_t GetSubscribeId(const std::string &pkgName) +{ + std::vector strVec; + size_t subIdIndex = 1; + size_t start = 0; + size_t end = pkgName.find("#"); + + while (end != std::string::npos) { + strVec.push_back(pkgName.substr(start, end - start)); + start = end + 1; + end = pkgName.find("#", start); + } + strVec.push_back(pkgName.substr(start)); + if (strVec.size() >= subIdIndex + 1) { + return std::atoi(strVec.at(subIdIndex).c_str()); + } + return 0; +} + +bool IsIdLengthValid(const std::string &inputID) +{ + if (inputID.empty() || inputID.length() > MAX_ID_LEN) { + LOGE("On parameter length error, maybe empty or beyond MAX_ID_LEN!"); + return false; + } + return true; +} + +bool IsMessageLengthValid(const std::string &inputMessage) +{ + if (inputMessage.empty() || inputMessage.length() > MAX_MESSAGE_LEN) { + LOGE("On parameter error, maybe empty or beyond MAX_MESSAGE_LEN!"); + return false; + } + return true; +} + +bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId) +{ + for (const auto &item : unorderedmap) { + if (item.first == udid && item.second == userId) { + return true; + } + } + return false; +} + +bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent) +{ + if (dmCommonNotifyEvent > DmCommonNotifyEvent::MIN && dmCommonNotifyEvent < DmCommonNotifyEvent::MAX) { + return true; + } + return false; +} + +std::string SafetyDump(const nlohmann::json &jsonObj) +{ + int indent = -1; + return jsonObj.dump(indent, ' ', false, nlohmann::detail::error_handler_t::ignore); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/common/src/dm_error_message.cpp b/common/src/dm_error_message.cpp index 8cf81bdfa3cbf9e7917dbdcdc2eaeae6e43de07c..18d2cbe110a0b8adb82f8574ad5a0c9088081b90 100644 --- a/common/src/dm_error_message.cpp +++ b/common/src/dm_error_message.cpp @@ -25,7 +25,7 @@ typedef struct ERROR_INFO { } ERROR_INFO; ERROR_INFO g_errorMessages[] = { - {ERR_DM_FAILED, "dm process execution failed."}, + {ERR_DM_FAILED, "dm process execution failed..."}, {ERR_DM_TIME_OUT, "dm process execution timeout."}, {ERR_DM_NOT_INIT, "dm service is not initialized, please try again later."}, {ERR_DM_INIT_FAILED, "dm service initialize failed."}, diff --git a/common/src/ipc/lite/ipc_cmd_register.cpp b/common/src/ipc/lite/ipc_cmd_register.cpp index 434c7f3dca8b8388d77fe004a8ebe85165a8b021..933ab010aeeb3502e08c540bde2f6c0c0ce26901 100644 --- a/common/src/ipc/lite/ipc_cmd_register.cpp +++ b/common/src/ipc/lite/ipc_cmd_register.cpp @@ -26,6 +26,10 @@ DM_IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, size_t buffLen) { + if (pBaseReq == nullptr) { + LOGE("IpcCmdRegister::SetRequest pBaseReq is nullptr!"); + return ERR_DM_POINT_NULL; + } if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { LOGE("IpcCmdRegister::SetRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; diff --git a/common/src/ipc/standard/ipc_cmd_register.cpp b/common/src/ipc/standard/ipc_cmd_register.cpp index 4f18a43bb1c777786955612f1b7fde37128a1676..f6e23e205e9d69590dae0ecd26d8e357228916b7 100644 --- a/common/src/ipc/standard/ipc_cmd_register.cpp +++ b/common/src/ipc/standard/ipc_cmd_register.cpp @@ -32,7 +32,6 @@ constexpr int32_t ERR_DM_POINT_NULL = 96929748; int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) { - int32_t ret = DM_OK; if (pBaseReq == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } @@ -41,22 +40,21 @@ int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBas LOGE("IpcCmdRegister::SetRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - - if (setIpcRequestFuncMap_.count(cmdCode) == 0) { - LOGE("cmdCode:%{public}d not register SetRequestFunc", cmdCode); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - - auto setRequestMapIter = setIpcRequestFuncMap_.find(cmdCode); - if (setRequestMapIter != setIpcRequestFuncMap_.end()) { - SetIpcRequestFunc ptr = setRequestMapIter->second; + SetIpcRequestFunc ptr = nullptr; + { + std::lock_guard autoLock(setIpcRequestFuncMapLock_); + auto setRequestMapIter = setIpcRequestFuncMap_.find(cmdCode); + if (setRequestMapIter == setIpcRequestFuncMap_.end()) { + LOGE("cmdCode:%{public}d not register SetRequestFunc", cmdCode); + return ERR_DM_UNSUPPORTED_IPC_COMMAND; + } + ptr = setRequestMapIter->second; if (ptr == nullptr) { LOGE("IpcCmdRegister::SetRequest setRequestMapIter->second is null"); return ERR_DM_POINT_NULL; } - ret = (setRequestMapIter->second)(pBaseReq, data); } - return ret; + return (ptr)(pBaseReq, data); } int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) @@ -65,15 +63,21 @@ int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std: LOGE("IpcCmdRegister::ReadResponse cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - auto readResponseMapIter = readResponseFuncMap_.find(cmdCode); - if (readResponseMapIter == readResponseFuncMap_.end()) { - LOGE("cmdCode:%{public}d not register ReadResponseFunc", cmdCode); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - if (readResponseMapIter->second == nullptr) { - return ERR_DM_POINT_NULL; + ReadResponseFunc ptr = nullptr; + { + std::lock_guard autoLock(readResponseFuncMapLock_); + auto readResponseMapIter = readResponseFuncMap_.find(cmdCode); + if (readResponseMapIter == readResponseFuncMap_.end()) { + LOGE("cmdCode:%{public}d not register ReadResponseFunc", cmdCode); + return ERR_DM_UNSUPPORTED_IPC_COMMAND; + } + ptr = readResponseMapIter->second; + if (ptr == nullptr) { + LOGE("IpcCmdRegister::ReadResponse readResponseMapIter->second is null"); + return ERR_DM_POINT_NULL; + } } - return (readResponseMapIter->second)(reply, pBaseRsp); + return (ptr)(reply, pBaseRsp); } int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply) @@ -82,15 +86,21 @@ int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessagePa LOGE("IpcCmdRegister::OnIpcCmd cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - auto onIpcCmdMapIter = onIpcCmdFuncMap_.find(cmdCode); - if (onIpcCmdMapIter == onIpcCmdFuncMap_.end()) { - LOGE("cmdCode:%{public}d not register OnIpcCmdFunc", cmdCode); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - if (onIpcCmdMapIter->second == nullptr) { - return ERR_DM_POINT_NULL; + OnIpcCmdFunc ptr = nullptr; + { + std::lock_guard autoLock(onIpcCmdFuncMapLock_); + auto onIpcCmdMapIter = onIpcCmdFuncMap_.find(cmdCode); + if (onIpcCmdMapIter == onIpcCmdFuncMap_.end()) { + LOGE("cmdCode:%{public}d not register OnIpcCmdFunc", cmdCode); + return ERR_DM_UNSUPPORTED_IPC_COMMAND; + } + ptr = onIpcCmdMapIter->second; + if (ptr == nullptr) { + LOGE("IpcCmdRegister::OnIpcCmd onIpcCmdMapIter->second is null"); + return ERR_DM_POINT_NULL; + } } - return (onIpcCmdMapIter->second)(data, reply); + return (ptr)(data, reply); } } // namespace DistributedHardware } // namespace OHOS diff --git a/commondependency/BUILD.gn b/commondependency/BUILD.gn index 162437022b9cbe73c9e5ac05c6476bc729fd226d..f08ca00d470ee03ee63b65c779e53edf533d6e39 100644 --- a/commondependency/BUILD.gn +++ b/commondependency/BUILD.gn @@ -40,7 +40,7 @@ ohos_shared_library("devicemanagerdependency") { defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"devicemanagerdependency\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004112", ] deps = [ diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index d60e259cfd33ad48dcc2d9fa7e0d8ebd2ecb9b5f..8ada37d6ad38cf2725e6dffe3ae540b85185ea66 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -14,11 +14,14 @@ */ #ifndef OHOS_DM_DEVICEPROFILE_CONNECTOR_H #define OHOS_DM_DEVICEPROFILE_CONNECTOR_H -#include #include +#include +#include #include "access_control_profile.h" #include "dm_device_info.h" #include "dm_single_instance.h" +#include "i_dp_inited_callback.h" +#include "trusted_device_info.h" constexpr uint32_t ALLOW_AUTH_ONCE = 1; constexpr uint32_t ALLOW_AUTH_ALWAYS = 2; @@ -33,7 +36,7 @@ constexpr uint32_t IDENTICAL_ACCOUNT_TYPE = 5; constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; constexpr uint32_t DM_POINT_TO_POINT = 256; constexpr uint32_t DM_ACROSS_ACCOUNT = 1282; - +constexpr uint32_t DM_INVALIED_BINDTYPE = 2048; constexpr uint32_t DEVICE = 1; constexpr uint32_t SERVICE = 2; constexpr uint32_t APP = 3; @@ -44,6 +47,7 @@ constexpr uint32_t ACTIVE = 1; typedef struct DmDiscoveryInfo { std::string pkgname; std::string localDeviceId; + int32_t userId; std::string remoteDeviceIdHash; } DmDiscoveryInfo; @@ -77,7 +81,7 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; - std::vector pkgNameVec; + std::vector processVec; int32_t leftAclNumber; } DmOfflineParam; @@ -86,62 +90,39 @@ namespace DistributedHardware { class IDeviceProfileConnector { public: virtual ~IDeviceProfileConnector() {} - virtual std::vector GetAccessControlProfile() = 0; - virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; - virtual int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee) = 0; - virtual int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId) = 0; - virtual std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, - const std::string &deviceId) = 0; - virtual DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) = 0; - virtual std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, - std::string trustUdid) = 0; - virtual std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, - std::string localDeviceId, std::string targetDeviceId) = 0; virtual int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm) = 0; - virtual int32_t DeleteAccessControlList(int32_t userId, std::string &accountId) = 0; - virtual DmOfflineParam DeleteAccessControlList(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId) = 0; - virtual std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId) = 0; - virtual bool CheckIdenticalAccount(int32_t userId, const std::string &accountId) = 0; - virtual int32_t DeleteP2PAccessControlList(int32_t userId, std::string &accountId) = 0; - virtual bool CheckSrcDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) = 0; - virtual bool CheckSinkDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) = 0; - virtual uint32_t DeleteTimeOutAcl(const std::string &deviceId) = 0; - virtual int32_t GetTrustNumber(const std::string &deviceId) = 0; - virtual bool CheckDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) = 0; - virtual bool CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId) = 0; - virtual std::vector CompareBindType(std::vector profiles, - std::string pkgName, std::vector &sinkBindType, std::string localDeviceId, - std::string targetDeviceId) = 0; }; class DeviceProfileConnector : public IDeviceProfileConnector { DM_DECLARE_SINGLE_INSTANCE(DeviceProfileConnector); public: std::vector GetAccessControlProfile(); - uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId); + std::vector GetAccessControlProfileByUserId(int32_t userId); + std::vector GetAclProfileByDeviceIdAndUserId( + const std::string &deviceId, int32_t userId); + uint32_t CheckBindType(std::string peerUdid, std::string localUdid); int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee); int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId); std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, const std::string &deviceId); - DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId); std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid); std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId); int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); - int32_t DeleteAccessControlList(int32_t userId, std::string &accountId); - DmOfflineParam DeleteAccessControlList(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId); - std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId); + bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId); + void DeleteAclForUserRemoved(std::string localUdid, int32_t userId); + DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, + const std::string &remoteDeviceId, int32_t bindLevel); + std::vector GetProcessInfoFromAclByUserId(const std::string &localDeviceId, + const std::string &targetDeviceId, int32_t userId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); - int32_t DeleteP2PAccessControlList(int32_t userId, std::string &accountId); - bool CheckSrcDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId); - bool CheckSinkDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId); + bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); + bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); uint32_t DeleteTimeOutAcl(const std::string &deviceId); int32_t GetTrustNumber(const std::string &deviceId); - bool CheckDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId); - bool CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId); + bool CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); std::vector CompareBindType(std::vector profiles, std::string pkgName, std::vector &sinkBindType, std::string localDeviceId, std::string targetDeviceId); int32_t IsSameAccount(const std::string &udid); @@ -150,6 +131,35 @@ public: int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); void DeleteAccessControlList(const std::string &udid); + int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId); + std::map GetDeviceIdAndBindLevel(std::vector userIds, const std::string &localUdid); + std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId, + const std::string &localUdid); + int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid, const std::string &localUdid); + int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); + OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid); + std::vector GetAllAccessControlProfile(); + void DeleteAccessControlById(int64_t accessControlId); + int32_t HandleUserSwitched(const std::string &localUdid, int32_t currentUserId, int32_t beforeUserId); + void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid, + const std::vector &localUserIds, std::string &localUdid); + std::vector GetOfflineProcessInfo(std::string &localUdid, const std::vector &localUserIds, + const std::string &remoteUdid, const std::vector &remoteUserIds); + std::map GetUserIdAndBindLevel(const std::string &localUdid, const std::string &peerUdid); + void UpdateACL(std::string &localUdid, const std::vector &localUserIds, + const std::string &remoteUdid, const std::vector &remoteFrontUserIds, + const std::vector &remoteBackUserIds); + std::multimap GetDevIdAndUserIdByActHash(const std::string &localUdid, + const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash); + std::multimap GetDeviceIdAndUserId(const std::string &localUdid, int32_t localUserId); + void HandleSyncBackgroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid, + const std::vector &localUserIds, std::string &localUdid); + int32_t SubscribeDeviceProfileInited(sptr dpInitedCallback); + int32_t UnSubscribeDeviceProfileInited(); + int32_t PutAllTrustedDevices(const std::vector &deviceInfos); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); @@ -161,8 +171,25 @@ private: const std::string &reqDev); int32_t CheckAuthForm(DmAuthForm form, DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); - bool SingleUserProcess(const DistributedDeviceProfile::AccessControlProfile &profile, - const DmAccessCaller &caller, const DmAccessCallee &callee); + bool SingleUserProcess(const DistributedDeviceProfile::AccessControlProfile &profile, const DmAccessCaller &caller, + const DmAccessCallee &callee); + void DeleteAppBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void DeleteDeviceBindLevel(DmOfflineParam &offlineParam, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void DeleteServiceBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void UpdateBindType(const std::string &udid, int32_t compareParam, std::map &deviceMap); + std::vector GetAclProfileByUserId(const std::string &localUdid, + int32_t userId, const std::string &remoteUdid); + void DeleteSigTrustACL(DistributedDeviceProfile::AccessControlProfile profile, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds, const std::vector &remoteBackUserIds); + void UpdatePeerUserId(DistributedDeviceProfile::AccessControlProfile profile, std::string &localUdid, + const std::vector &localUserIds, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 03fe99631c0f044bc2965a469739eb9f2e929af1..2df32cf7ca3ae9448a5a2dbb4a842dfda443d21b 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,9 +17,16 @@ #define OHOS_DM_MULTIPLE_USER_CONNECTOR_H #include +#include +#include #include +#include namespace OHOS { namespace DistributedHardware { +typedef struct DMAccountInfo { + std::string accountId; + std::string accountName; +} DMAccountInfo; class MultipleUserConnector { public: /** @@ -45,11 +52,19 @@ public: /** * @tc.name: MultipleUserConnector::GetOhosAccountId - * @tc.desc: Get Current AccountId of the Multiple User Connector + * @tc.desc: Get Current AccountId of current user * @tc.type: FUNC */ static std::string GetOhosAccountId(void); - + + /** + * @brief Get the Ohos Account Id By Userid + * + * @param userId the user id in which account login + * @return std::string the account id + */ + static std::string GetOhosAccountIdByUserId(int32_t userId); + /** * @tc.name: MultipleUserConnector::SetSwitchOldAccountId * @tc.desc: Set Switch Old UserId of the Multiple User Connector @@ -63,9 +78,45 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountId(void); + + /** + * @tc.name: MultipleUserConnector::SetSwitchOldAccountName + * @tc.desc: Set Switch Old AccountName of the Multiple User Connector + * @tc.type: FUNC + */ + static void SetSwitchOldAccountName(std::string accountName); + + /** + * @tc.name: MultipleUserConnector::GetOhosAccountName + * @tc.desc: Get Current AccountName of the Multiple User Connector + * @tc.type: FUNC + */ + static std::string GetOhosAccountName(void); + + /** + * @tc.name: MultipleUserConnector::GetSwitchOldAccountName + * @tc.desc: Get Switc Old AccountName of the Multiple User Connector + * @tc.type: FUNC + */ + static std::string GetSwitchOldAccountName(void); + + static void SetAccountInfo(int32_t userId, DMAccountInfo dmAccountInfo); + static DMAccountInfo GetAccountInfoByUserId(int32_t userId); + static void DeleteAccountInfoByUserId(int32_t userId); + static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); + static void GetCallerUserId(int32_t &userId); + static int32_t GetForegroundUserIds(std::vector &userVec); + static int32_t GetFirstForegroundUserId(void); + static int32_t GetBackgroundUserIds(std::vector &userIdVec); + static int32_t GetAllUserIds(std::vector &userIdVec); + private: static int32_t oldUserId_; static std::string accountId_; + static std::string accountName_; + static std::mutex lock_; + static std::map dmAccountInfoMap_; + static std::mutex dmAccountInfoMaplock_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 60dde15814e9e9116310b0f67368520a9ce874ce..3aa52907589bf8feb4782b3b394be36b40707902 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -20,6 +20,7 @@ #include "dm_log.h" #include "multiple_user_connector.h" #include "distributed_device_profile_client.h" +#include "system_ability_definition.h" using namespace OHOS::DistributedDeviceProfile; @@ -31,19 +32,62 @@ std::vector DeviceProfileConnector::GetAccessControlProfil std::vector profiles; std::map queryParams; int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - queryParams["userId"] = std::to_string(userId); + queryParams[USERID] = std::to_string(userId); if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { LOGE("DP GetAccessControlProfile failed."); } return profiles; } +std::vector DeviceProfileConnector::GetAccessControlProfileByUserId(int32_t userId) +{ + std::vector profiles; + std::map queryParams; + queryParams[USERID] = std::to_string(userId); + if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { + LOGE("DP GetAccessControlProfileByUserId failed."); + } + return profiles; +} + +std::vector DeviceProfileConnector::GetAclProfileByDeviceIdAndUserId(const std::string &deviceId, + int32_t userId) +{ + std::vector profiles; + std::vector aclProfileVec; + std::map queryParams; + queryParams[USERID] = std::to_string(userId); + if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { + LOGE("DP GetAccessControlProfile failed."); + return aclProfileVec; + } + for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserDeviceId() == deviceId && + item.GetAccesser().GetAccesserUserId() == userId) || + (item.GetAccessee().GetAccesseeDeviceId() == deviceId && + item.GetAccessee().GetAccesseeUserId() == userId)) { + aclProfileVec.push_back(item); + } + } + return aclProfileVec; +} + std::unordered_map DeviceProfileConnector::GetAppTrustDeviceList(const std::string &pkgName, const std::string &deviceId) { - std::vector profiles = GetAccessControlProfile(); - std::unordered_map deviceIdMap; + int32_t userId = MultipleUserConnector::GetFirstForegroundUserId(); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(deviceId, userId); + std::vector profilesFilter = {}; for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccesser().GetAccesserDeviceId() == deviceId) || + (item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == deviceId)) { + profilesFilter.push_back(item); + } + } + std::unordered_map deviceIdMap; + for (auto &item : profilesFilter) { std::string trustDeviceId = item.GetTrustDeviceId(); if (trustDeviceId == deviceId || item.GetStatus() != ACTIVE) { continue; @@ -76,18 +120,19 @@ std::unordered_map DeviceProfileConnector::GetAppTrustD int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm) { - std::vector profiles = GetAccessControlProfile(); - if (profiles.size() == 0) { - return DM_OK; - } + std::vector profiles = GetAccessControlProfileByUserId(discoveryInfo.userId); std::vector bindTypes; for (auto &item : profiles) { char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(item.GetTrustDeviceId(), reinterpret_cast(deviceIdHash)) != DM_OK) { LOGE("get deviceIdHash by deviceId: %{public}s failed.", GetAnonyString(deviceIdHash).c_str()); - return ERR_DM_FAILED; + continue; } - if (static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || item.GetStatus() != ACTIVE) { + if (static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || + (discoveryInfo.localDeviceId == item.GetAccesser().GetAccesserDeviceId() && + discoveryInfo.userId != item.GetAccesser().GetAccesserUserId()) || + (discoveryInfo.localDeviceId == item.GetAccessee().GetAccesseeDeviceId() && + discoveryInfo.userId != item.GetAccessee().GetAccesseeUserId())) { continue; } int32_t bindType = HandleDmAuthForm(item, discoveryInfo); @@ -99,19 +144,19 @@ int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, if (std::count(bindTypes.begin(), bindTypes.end(), DmAuthForm::IDENTICAL_ACCOUNT) > 0) { isOnline = true; authForm = DmAuthForm::IDENTICAL_ACCOUNT; - LOGI("GetDeviceAclParam, The found device is identical account device bind type."); + LOGI("The found device is identical account device bind type."); return DM_OK; } if (std::count(bindTypes.begin(), bindTypes.end(), DmAuthForm::PEER_TO_PEER) > 0) { isOnline = true; authForm = DmAuthForm::PEER_TO_PEER; - LOGI("GetDeviceAclParam, The found device is peer-to-peer device bind-level."); + LOGI("The found device is peer-to-peer device bind-level."); return DM_OK; } if (std::count(bindTypes.begin(), bindTypes.end(), DmAuthForm::ACROSS_ACCOUNT) > 0) { isOnline = true; authForm = DmAuthForm::ACROSS_ACCOUNT; - LOGI("GetDeviceAclParam, The found device is across-account device bind-level."); + LOGI("The found device is across-account device bind-level."); return DM_OK; } authForm = DmAuthForm::INVALID_TYPE; @@ -151,17 +196,17 @@ int32_t DeviceProfileConnector::HandleDmAuthForm(AccessControlProfile profiles, return DmAuthForm::INVALID_TYPE; } -uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::string requestDeviceId) +uint32_t DeviceProfileConnector::CheckBindType(std::string peerUdid, std::string localUdid) { - LOGI("CheckBindType start."); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + std::vector filterProfiles = GetAclProfileByUserId(localUdid, + MultipleUserConnector::GetFirstForegroundUserId(), peerUdid); + LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); uint32_t highestPriority = INVALIED_TYPE; - for (auto &item : profiles) { - if (trustDeviceId != item.GetTrustDeviceId() || item.GetStatus() != ACTIVE) { + for (auto &item : filterProfiles) { + if (peerUdid != item.GetTrustDeviceId()) { continue; } - uint32_t priority = static_cast(GetAuthForm(item, trustDeviceId, requestDeviceId)); + uint32_t priority = static_cast(GetAuthForm(item, peerUdid, localUdid)); if (priority > highestPriority) { highestPriority = priority; } @@ -172,7 +217,7 @@ uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::s int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, const std::string &trustDev, const std::string &reqDev) { - LOGI("DeviceProfileConnector::GetAuthForm bindType %{public}d, bindLevel %{public}d", + LOGI("BindType %{public}d, bindLevel %{public}d", profiles.GetBindType(), profiles.GetBindLevel()); uint32_t priority = INVALIED_TYPE; uint32_t bindType = profiles.GetBindType(); @@ -183,22 +228,14 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont case DM_POINT_TO_POINT: if (profiles.GetBindLevel() == DEVICE) { priority = DEVICE_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccesser().GetAccesserDeviceId() == reqDev && - profiles.GetAccessee().GetAccesseeDeviceId() == trustDev) { - priority = APP_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccessee().GetAccesseeDeviceId() == reqDev && - profiles.GetAccesser().GetAccesserDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; } break; case DM_ACROSS_ACCOUNT: if (profiles.GetBindLevel() == DEVICE) { priority = DEVICE_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccesser().GetAccesserDeviceId() == reqDev && - profiles.GetAccessee().GetAccesseeDeviceId() == trustDev) { - priority = APP_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccessee().GetAccesseeDeviceId() == reqDev && - profiles.GetAccesser().GetAccesserDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; } break; @@ -212,8 +249,9 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont std::vector DeviceProfileConnector::GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid) { - LOGI("GetBindTypeByPkgName start."); - std::vector profiles = GetAccessControlProfile(); + LOGI("Start."); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetFirstForegroundUserId()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector bindTypeVec; for (auto &item : profiles) { @@ -328,7 +366,8 @@ void DeviceProfileConnector::ProcessBindType(AccessControlProfile profiles, DmDi std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId) { - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetFirstForegroundUserId()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector sinkBindType; std::vector bindType; @@ -350,66 +389,39 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa return bindType; } -std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string &localDeviceId, - std::string &targetDeviceId) +std::vector DeviceProfileConnector::GetProcessInfoFromAclByUserId( + const std::string &localDeviceId, const std::string &targetDeviceId, int32_t userId) { - LOGI("GetPkgNameFromAcl start."); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - std::vector pkgNameVec; - for (auto &item : profiles) { - if (item.GetTrustDeviceId() != targetDeviceId || item.GetStatus() != ACTIVE) { + std::vector filterProfiles = GetAclProfileByUserId(localDeviceId, + userId, targetDeviceId); + LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); + std::vector processInfoVec; + for (auto &item : filterProfiles) { + if (item.GetTrustDeviceId() != targetDeviceId) { continue; } - if ((item.GetAccesser().GetAccesserDeviceId() == localDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == targetDeviceId) || - (item.GetAccesser().GetAccesserDeviceId() == targetDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == localDeviceId)) { - pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } - } - return pkgNameVec; -} - -DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) -{ - LOGI("DeviceProfileConnector::GetOfflineParamFromAcl, trustDeviceId = %{public}s and requestDeviceId = %{public}s", - GetAnonyString(trustDeviceId).c_str(), GetAnonyString(requestDeviceId).c_str()); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - DmOfflineParam offlineParam; - offlineParam.leftAclNumber = 0; - offlineParam.bindType = INVALIED_TYPE; - for (auto &item : profiles) { - if (item.GetTrustDeviceId() != trustDeviceId || item.GetStatus() != ACTIVE) { + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + OHOS::DistributedHardware::ProcessInfo processInfo; + if (accesserUdid == localDeviceId) { + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfoVec.push_back(processInfo); continue; } - offlineParam.leftAclNumber++; - uint32_t priority = INVALIED_TYPE; - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - priority = IDENTICAL_ACCOUNT_TYPE; - } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ALWAYS) { - priority = DEVICE_PEER_TO_PEER_TYPE; - } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { - priority = DEVICE_PEER_TO_PEER_TYPE; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } else if ((item.GetAccesser().GetAccesserDeviceId() == requestDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == trustDeviceId) || - (item.GetAccesser().GetAccesserDeviceId() == trustDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == requestDeviceId)) { - priority = APP_PEER_TO_PEER_TYPE; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } - if (priority > offlineParam.bindType) { - offlineParam.bindType = priority; + if (accesseeUdid == localDeviceId) { + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + processInfoVec.push_back(processInfo); + continue; } } - return offlineParam; + return processInfoVec; } int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee) { - LOGI("DeviceProfileConnector::PutAccessControlList start."); + LOGI("Start."); Accesser accesser; accesser.SetAccesserDeviceId(dmAccesser.requestDeviceId); accesser.SetAccesserUserId(dmAccesser.requestUserId); @@ -439,32 +451,76 @@ int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccess return ret; } -int32_t DeviceProfileConnector::DeleteAccessControlList(int32_t userId, std::string &accountId) +bool DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) { - LOGI("DeleteAccessControlList by userId and accountId."); - std::vector profiles; - std::map queryParams; - queryParams["userId"] = std::to_string(userId); - if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { - LOGE("DP GetAccessControlProfile failed."); + LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", + GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); + std::vector profiles = GetAllAccessControlProfile(); + std::vector deleteProfiles; + bool notifyOffline = false; + bool isDelete = false; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != peerUdid) { + continue; + } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesserUserId == localUserId && + accesseeUdid == peerUdid && accesseeUserId == peerUserId) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + isDelete = true; + } + deleteProfiles.push_back(item); + notifyOffline = (item.GetStatus() == ACTIVE); + continue; + } + if (accesserUdid == peerUdid && accesserUserId == peerUserId && + accesseeUdid == localUdid && accesseeUserId == localUserId) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + isDelete = true; + } + deleteProfiles.push_back(item); + notifyOffline = (item.GetStatus() == ACTIVE); + continue; + } } - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - for (auto &item : profiles) { - LOGI("AccessControlProfile bindType is : %{public}d.", item.GetBindType()); + if (!isDelete) { + return false; + } + for (const auto &item : deleteProfiles) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); } - return DM_OK; + return notifyOffline; +} + +void DeviceProfileConnector::DeleteAclForUserRemoved(std::string localUdid, int32_t userId) +{ + LOGI("localUdid %{public}s, userId %{public}d.", GetAnonyString(localUdid).c_str(), userId); + std::vector profiles = GetAccessControlProfileByUserId(userId); + for (const auto &item : profiles) { + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if ((accesserUdid == localUdid && accesserUserId == userId) || + (accesseeUdid == localUdid && accesseeUserId == userId)) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } + } } void DeviceProfileConnector::DeleteAccessControlList(const std::string &udid) { - LOGI("DeleteAccessControlList by udid: %{public}s.", GetAnonyString(udid).c_str()); + LOGI("Udid: %{public}s.", GetAnonyString(udid).c_str()); if (udid.empty()) { LOGE("DeleteAccessControlList udid is empty."); return; } std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + LOGI("Size is %{public}zu", profiles.size()); for (const auto &item : profiles) { if (item.GetTrustDeviceId() == udid) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); @@ -472,60 +528,156 @@ void DeviceProfileConnector::DeleteAccessControlList(const std::string &udid) } } -DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId) +DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string &pkgName, + const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel) { - LOGI("DeleteAccessControlList by pkgName, localDeviceId, remoteDeviceId."); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + LOGI("pkgName %{public}s, localDeviceId %{public}s, remoteDeviceId %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); DmOfflineParam offlineParam; offlineParam.bindType = INVALIED_TYPE; - offlineParam.leftAclNumber = 0; + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < DEVICE) { + LOGE("Invalied bindlevel."); + return offlineParam; + } + std::vector profiles = GetAccessControlProfile(); + if (profiles.empty()) { + LOGE("Acl is empty."); + return offlineParam; + } + switch (bindLevel) { + case APP: + DeleteAppBindLevel(offlineParam, pkgName, profiles, localDeviceId, remoteDeviceId); + break; + case SERVICE: + DeleteServiceBindLevel(offlineParam, pkgName, profiles, localDeviceId, remoteDeviceId); + break; + case DEVICE: + DeleteDeviceBindLevel(offlineParam, profiles, localDeviceId, remoteDeviceId); + break; + default: + break; + } + return offlineParam; +} + +void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; for (auto &item : profiles) { - if (item.GetTrustDeviceId() != remoteDeviceId || item.GetStatus() != ACTIVE) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { continue; } - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - LOGE("Identical account forbid unbind."); - offlineParam.bindType = INVALIED_TYPE; - return offlineParam; - } - if (item.GetTrustDeviceId() == remoteDeviceId) { - offlineParam.leftAclNumber++; - if (item.GetBindLevel() == DEVICE && item.GetBindType() != DM_IDENTICAL_ACCOUNT && - item.GetAccesser().GetAccesserBundleName() == pkgName) { - LOGI("DeleteAccessControlList device unbind."); - offlineParam.bindType = DEVICE_PEER_TO_PEER_TYPE; - } + bindNums++; + if (item.GetAccesser().GetAccesserBundleName() == pkgName && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if (item.GetAccessee().GetAccesseeBundleName() == pkgName && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; } } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, + const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; for (auto &item : profiles) { - if (item.GetTrustDeviceId() != remoteDeviceId || item.GetStatus() != ACTIVE) { - continue; - } - if ((item.GetAccesser().GetAccesserDeviceId() == localDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == remoteDeviceId) || - (item.GetAccessee().GetAccesseeDeviceId() == localDeviceId && - item.GetAccesser().GetAccesserDeviceId() == remoteDeviceId)) { - if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - offlineParam.leftAclNumber--; - } else if (item.GetAccesser().GetAccesserBundleName() == pkgName && - item.GetAccessee().GetAccesseeBundleName() == pkgName) { - offlineParam.bindType = APP_PEER_TO_PEER_TYPE; - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - offlineParam.leftAclNumber--; - break; - } + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + continue; + } + bindNums++; + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = DEVICE; + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = DEVICE; + LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + continue; } } - return offlineParam; + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteServiceBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } + bindNums++; + if (item.GetAccesser().GetAccesserBundleName() == pkgName && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if (item.GetAccessee().GetAccesseeBundleName() == pkgName && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; } int32_t DeviceProfileConnector::UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId) { - LOGI("UpdateAccessControlList by userId and accountId."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { @@ -547,85 +699,46 @@ int32_t DeviceProfileConnector::UpdateAccessControlList(int32_t userId, std::str return DM_OK; } -bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::string &accountId) -{ - LOGI("DeviceProfileConnector::CheckIdenticalAccount"); - std::vector profiles; - std::map queryParams; - queryParams["userId"] = std::to_string(userId); - queryParams["accountId"] = accountId; - if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { - LOGE("DP GetAccessControlProfile failed."); - } - for (auto &item : profiles) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT && item.GetStatus() == ACTIVE) { - return true; - } - } - return false; -} -int32_t DeviceProfileConnector::DeleteP2PAccessControlList(int32_t userId, std::string &accountId) -{ - LOGI("DeviceProfileConnector::DeleteP2PAccessControlList"); - std::vector profiles; - std::map queryParams; - queryParams["userId"] = std::to_string(userId); - queryParams["accountId"] = accountId; - if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { - LOGE("DP GetAccessControlProfile failed."); - } - for (auto &item : profiles) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetStatus() != ACTIVE) { - continue; - } - if ((item.GetAccesser().GetAccesserUserId() == userId && - item.GetAccesser().GetAccesserAccountId() == accountId) || - (item.GetAccessee().GetAccesseeUserId() == userId && - item.GetAccessee().GetAccesseeAccountId() == accountId)) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - } - } - return DM_OK; -} - -bool DeviceProfileConnector::CheckSrcDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) +bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { - LOGI("DeviceProfileConnector::CheckSrcDeviceIdInAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && item.GetAccessee().GetAccesseeBundleName() == pkgName && - item.GetAccessee().GetAccesseeUserId() == 0 && item.GetAccessee().GetAccesseeAccountId() == "") { + item.GetBindLevel() == DEVICE && (item.GetAccessee().GetAccesseeBundleName() == pkgName || + item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccessee().GetAccesseeUserId() == 0 && + item.GetAccessee().GetAccesseeAccountId() == "") { return true; } } return false; } -bool DeviceProfileConnector::CheckSinkDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) +bool DeviceProfileConnector::CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { - LOGI("DeviceProfileConnector::CheckSinkDeviceIdInAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && item.GetAccesser().GetAccesserBundleName() == pkgName && - item.GetAccesser().GetAccesserUserId() == 0 && item.GetAccesser().GetAccesserAccountId() == "") { + item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || + item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccesser().GetAccesserUserId() == 0 && + item.GetAccesser().GetAccesserAccountId() == "") { return true; } } return false; } -bool DeviceProfileConnector::CheckDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) +bool DeviceProfileConnector::CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { - return (CheckSinkDeviceIdInAcl(pkgName, deviceId) || CheckSrcDeviceIdInAcl(pkgName, deviceId)); + return (CheckSinkDevIdInAclForDevBind(pkgName, deviceId) || CheckSrcDevIdInAclForDevBind(pkgName, deviceId)); } uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId) { - LOGI("DeviceProfileConnector::DeleteTimeOutAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); uint32_t res = 0; @@ -644,7 +757,7 @@ uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId) int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) { - LOGI("DeviceProfileConnector::DeleteTimeOutAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); int32_t trustNumber = 0; @@ -656,39 +769,9 @@ int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) return trustNumber; } -bool DeviceProfileConnector::CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId) -{ - LOGI("DeviceProfileConnector::CheckPkgnameInAcl"); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - for (auto &item : profiles) { - if (item.GetTrustDeviceId() != remoteDeviceId && item.GetStatus() != ACTIVE) { - continue; - } - if ((item.GetBindType() == DM_POINT_TO_POINT || item.GetBindType() == DM_ACROSS_ACCOUNT) && - item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || - item.GetAccessee().GetAccesseeBundleName() == pkgName)) { - LOGI("The pkgname %{public}s is peer-to-peer device unbind.", pkgName.c_str()); - return true; - } else if ((item.GetBindType() == DM_POINT_TO_POINT || item.GetBindType() == DM_ACROSS_ACCOUNT) && - item.GetBindLevel() == APP && item.GetAccesser().GetAccesserBundleName() == pkgName && - item.GetAccesser().GetAccesserDeviceId() == localDeviceId) { - LOGI("The pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); - return true; - } else if ((item.GetBindType() == DM_POINT_TO_POINT || item.GetBindType() == DM_ACROSS_ACCOUNT) && - item.GetBindLevel() == APP && item.GetAccessee().GetAccesseeBundleName() == pkgName && - item.GetAccessee().GetAccesseeDeviceId() == localDeviceId) { - LOGI("The pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); - return true; - } - } - return false; -} - int32_t DeviceProfileConnector::IsSameAccount(const std::string &udid) { - LOGI("DeviceProfileConnector::IsSameAccount start."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); for (auto &item : profiles) { if (item.GetTrustDeviceId() == udid && item.GetStatus() == ACTIVE) { @@ -701,13 +784,47 @@ int32_t DeviceProfileConnector::IsSameAccount(const std::string &udid) return ERR_DM_FAILED; } +std::vector GetACLByDeviceIdAndUserId(std::vector profiles, + const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) +{ + std::vector profilesFilter; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserUserId() == caller.userId && + item.GetAccesser().GetAccesserDeviceId() == srcUdid && + item.GetAccessee().GetAccesseeDeviceId() == sinkUdid) { + if (callee.userId != 0 && callee.userId == item.GetAccessee().GetAccesseeUserId()) { + profilesFilter.push_back(item); + continue; + } else if (callee.userId == 0 || item.GetAccessee().GetAccesseeUserId() == -1) { + profilesFilter.push_back(item); + continue; + } + } + if ((item.GetAccessee().GetAccesseeUserId() == caller.userId || + item.GetAccessee().GetAccesseeUserId() == -1) && + item.GetAccessee().GetAccesseeDeviceId() == srcUdid && + item.GetAccesser().GetAccesserDeviceId() == sinkUdid) { + if (callee.userId != 0 && callee.userId == item.GetAccesser().GetAccesserUserId()) { + profilesFilter.push_back(item); + continue; + } else if (callee.userId == 0 || item.GetAccesser().GetAccesserUserId() == -1) { + profilesFilter.push_back(item); + continue; + } + } + } + return profilesFilter; +} + int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) { - LOGI("DeviceProfileConnector::CheckAccessControl pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", + LOGI("PkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - for (auto &item : profiles) { + std::vector profiles = GetAllAccessControlProfile(); + std::vector profilesFilter = + GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, callee, sinkUdid); + for (auto &item : profilesFilter) { if (item.GetStatus() != ACTIVE || (item.GetTrustDeviceId() != sinkUdid && item.GetTrustDeviceId() != srcUdid)) { continue; @@ -719,10 +836,28 @@ int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, return ERR_DM_FAILED; } +bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::string &accountId) +{ + LOGI("Start"); + std::vector profiles; + std::map queryParams; + queryParams[USERID] = std::to_string(userId); + queryParams[ACCOUNTID] = accountId; + if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { + LOGE("DP GetAccessControlProfile failed."); + } + for (auto &item : profiles) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT && item.GetStatus() == ACTIVE) { + return true; + } + } + return false; +} + bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::AccessControlProfile &profile, const DmAccessCaller &caller, const DmAccessCallee &callee) { - LOGI("DeviceProfileConnector::SingleUserProcess bindType %{public}d, bindLevel %{public}d.", + LOGI("BindType %{public}d, bindLevel %{public}d.", profile.GetBindType(), profile.GetBindLevel()); uint32_t bindType = profile.GetBindType(); bool ret = false; @@ -756,10 +891,12 @@ bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::A int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) { - LOGI("DeviceProfileConnector::CheckAccessControl pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", + LOGI("DeviceProfileConnector::CheckIsSameAccount pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - for (auto &item : profiles) { + std::vector profiles = GetAllAccessControlProfile(); + std::vector profilesFilter + = GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, callee, sinkUdid); + for (auto &item : profilesFilter) { if (item.GetStatus() != ACTIVE || (item.GetTrustDeviceId() != sinkUdid && item.GetTrustDeviceId() != srcUdid)) { continue; @@ -772,6 +909,559 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, return ERR_DM_FAILED; } +int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + LOGI("pkgName %{public}s, tokenId %{public}" PRId64", udid %{public}s.", pkgName.c_str(), + tokenId, GetAnonyString(udid).c_str()); + std::vector profiles = GetAccessControlProfile(); + int32_t bindLevel = INVALIED_TYPE; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != udid) { + continue; + } + if (item.GetAccesser().GetAccesserBundleName() == pkgName && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == udid) { + tokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); + bindLevel = static_cast(item.GetBindLevel()); + LOGI("Src get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); + continue; + } + if (item.GetAccessee().GetAccesseeBundleName() == pkgName && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == udid) { + tokenId = static_cast(item.GetAccessee().GetAccesseeTokenId()); + bindLevel = static_cast(item.GetBindLevel()); + LOGI("Sink get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); + continue; + } + } + return bindLevel; +} + +std::map DeviceProfileConnector::GetDeviceIdAndBindLevel(std::vector userIds, + const std::string &localUdid) +{ + std::vector profiles = GetAllAccessControlProfile(); + std::map deviceIdMap; + for (const auto &item : profiles) { + if (find(userIds.begin(), userIds.end(), item.GetAccesser().GetAccesserUserId()) != userIds.end() && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Get Device Bind type localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindLevel(), deviceIdMap); + continue; + } + if (find(userIds.begin(), userIds.end(), item.GetAccessee().GetAccesseeUserId()) != userIds.end() && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Get Device Bind type localUdid %{public}s is sink.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindLevel(), deviceIdMap); + continue; + } + } + return deviceIdMap; +} + +std::multimap DeviceProfileConnector::GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId, const std::string &localUdid) +{ + LOGI("localUdid %{public}s, userId %{public}d, accountId %{public}s.", GetAnonyString(localUdid).c_str(), + userId, GetAnonyString(accountId).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::multimap deviceIdMap; + for (const auto &item : profiles) { + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesserUserId == userId && item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + LOGI("Account logout trust udid %{public}s userid %{public}d is src.", + GetAnonyString(accesseeUdid).c_str(), accesseeUserId); + deviceIdMap.insert(std::pair(accesseeUdid, accesseeUserId)); + continue; + } + if (accesseeUdid == localUdid && accesseeUserId == userId && item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + LOGI("Account logout trust udid %{public}s userid %{public}d is sink.", + GetAnonyString(accesserUdid).c_str(), accesserUserId); + deviceIdMap.insert(std::pair(accesserUdid, accesserUserId)); + continue; + } + } + return deviceIdMap; +} + +void DeviceProfileConnector::UpdateBindType(const std::string &udid, int32_t compareParam, + std::map &deviceMap) +{ + LOGI("BindType %{public}d.", compareParam); + if (deviceMap.find(udid) == deviceMap.end()) { + deviceMap[udid] = compareParam; + } else { + deviceMap[udid] = std::min(deviceMap[udid], compareParam); + } +} + +int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, + const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) +{ + LOGI("RemoteUserId %{public}d, remoteAccountHash %{public}s, remoteUdid %{public}s, localUdid %{public}s.", + remoteUserId, GetAnonyString(remoteAccountHash).c_str(), GetAnonyString(remoteUdid).c_str(), + GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAccessControlProfileByUserId(remoteUserId); + int32_t bindType = DM_INVALIED_BINDTYPE; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid) { + continue; + } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == remoteUdid && accesseeUserId == remoteUserId) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = DM_IDENTICAL_ACCOUNT; + continue; + } + if (accesseeUdid == localUdid && accesserUdid == remoteUdid && accesserUserId == remoteUserId) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = DM_IDENTICAL_ACCOUNT; + continue; + } + } + return bindType; +} + +int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid) +{ + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, + GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAccessControlProfile(); + int32_t bindType = DM_INVALIED_BINDTYPE; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid) { + continue; + } + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + bindType = DM_IDENTICAL_ACCOUNT; + continue; + } + if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Src device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Sink device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } + } + return bindType; +} + +OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) +{ + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", + remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAccessControlProfile(); + ProcessInfo processInfo; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + if (item.GetAccesser().GetAccesserUserId() == remoteUserId && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Src device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Sink device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + continue; + } + } + return processInfo; +} + +std::vector DeviceProfileConnector::GetAllAccessControlProfile() +{ + std::vector profiles; + if (DistributedDeviceProfileClient::GetInstance().GetAllAccessControlProfile(profiles) != DM_OK) { + LOGE("DP failed."); + } + return profiles; +} + +void DeviceProfileConnector::DeleteAccessControlById(int64_t accessControlId) +{ + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(accessControlId); +} + +int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, int32_t currentUserId, + int32_t beforeUserId) +{ + LOGI("Start."); + std::vector profiles = GetAllAccessControlProfile(); + std::vector activeProfiles; + std::vector inActiveProfiles; + for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == beforeUserId && item.GetStatus() == ACTIVE) || + (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == beforeUserId && item.GetStatus() == ACTIVE)) { + item.SetStatus(INACTIVE); + inActiveProfiles.push_back(item); + continue; + } + if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == currentUserId && item.GetStatus() == INACTIVE) || ( + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == currentUserId && item.GetStatus() == INACTIVE)) { + item.SetStatus(ACTIVE); + activeProfiles.push_back(item); + continue; + } + } + for (auto &item : inActiveProfiles) { + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + for (auto &item : activeProfiles) { + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + return DM_OK; +} + +std::vector DeviceProfileConnector::GetAclProfileByUserId(const std::string &localUdid, + int32_t userId, const std::string &remoteUdid) +{ + LOGI("localUdid %{public}s, localUserId %{public}d, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + userId, GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::vector profilesTemp; + for (const auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } + } + return profilesTemp; +} + +void DeviceProfileConnector::HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != remoteUserIds.end() && item.GetStatus() == INACTIVE) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != remoteUserIds.end() && item.GetStatus() == INACTIVE) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + } +} + +std::vector DeviceProfileConnector::GetOfflineProcessInfo(std::string &localUdid, + const std::vector &localUserIds, const std::string &remoteUdid, const std::vector &remoteUserIds) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::vector processInfos; + int32_t bindLevel = 100; + for (const auto &item : profiles) { + ProcessInfo processInfo; + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), accesserUserId) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), accesseeUserId) != remoteUserIds.end() && + item.GetStatus() == ACTIVE) { + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); + processInfos.push_back(processInfo); + } else if (accesseeUdid == localUdid && accesserUdid == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), accesseeUserId) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), accesserUserId) != remoteUserIds.end() && + item.GetStatus() == ACTIVE) { + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); + processInfos.push_back(processInfo); + } + } + if (bindLevel == INVALIED_TYPE || bindLevel == DEVICE) { + processInfos.clear(); + for (const auto &item : localUserIds) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = item; + processInfos.push_back(processInfo); + } + } + return processInfos; +} + +std::map DeviceProfileConnector::GetUserIdAndBindLevel(const std::string &localUdid, + const std::string &peerUdid) +{ + LOGI("localUdid %{public}s, peerUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(peerUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::map userIdAndBindLevel; + for (const auto &item : profiles) { + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == peerUdid) { + if (userIdAndBindLevel.find(accesserUserid) == userIdAndBindLevel.end()) { + userIdAndBindLevel[accesserUserid] = item.GetBindLevel(); + } else { + userIdAndBindLevel[accesserUserid] = + std::min(static_cast(item.GetBindLevel()), userIdAndBindLevel[accesserUserid]); + } + } else if (accesseeUdid == localUdid && accesserUdid == peerUdid) { + if (userIdAndBindLevel.find(accesseeUserid) == userIdAndBindLevel.end()) { + userIdAndBindLevel[accesseeUserid] = item.GetBindLevel(); + } else { + userIdAndBindLevel[accesseeUserid] = + std::min(static_cast(item.GetBindLevel()), userIdAndBindLevel[accesseeUserid]); + } + } + } + return userIdAndBindLevel; +} + +void DeviceProfileConnector::UpdateACL(std::string &localUdid, const std::vector &localUserIds, + const std::string &remoteUdid, const std::vector &remoteFrontUserIds, + const std::vector &remoteBackUserIds) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (auto item : profiles) { + // deleta signal trust acl. + DeleteSigTrustACL(item, remoteUdid, remoteFrontUserIds, remoteBackUserIds); + // update identical account userId. + UpdatePeerUserId(item, localUdid, localUserIds, remoteUdid, remoteFrontUserIds); + } +} + +void DeviceProfileConnector::DeleteSigTrustACL(AccessControlProfile profile, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds, const std::vector &remoteBackUserIds) +{ + LOGI("start."); + std::string accesserUdid = profile.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = profile.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = profile.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = profile.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == remoteUdid && accesserUserid != 0 && accesserUserid != -1 && + find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesserUserid) == remoteFrontUserIds.end() && + find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesserUserid) == remoteBackUserIds.end()) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(profile.GetAccessControlId()); + return; + } + if (accesseeUdid == remoteUdid && accesseeUserid != 0 && accesseeUserid != -1 && + find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesseeUserid) == remoteFrontUserIds.end() && + find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesseeUserid) == remoteBackUserIds.end()) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(profile.GetAccessControlId()); + return; + } +} + +void DeviceProfileConnector::UpdatePeerUserId(AccessControlProfile profile, std::string &localUdid, + const std::vector &localUserIds, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds) +{ + LOGI("start."); + std::string accesserUdid = profile.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = profile.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = profile.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = profile.GetAccessee().GetAccesseeUserId(); + int32_t bindType = profile.GetBindType(); + if (accesserUdid == localUdid && accesseeUdid == remoteUdid && bindType == DM_IDENTICAL_ACCOUNT && + find(localUserIds.begin(), localUserIds.end(), accesserUserid) != localUserIds.end() && + (accesseeUserid == 0 || accesseeUserid == -1)) { + Accessee accessee = profile.GetAccessee(); + accessee.SetAccesseeUserId(remoteFrontUserIds[0]); + profile.SetAccessee(accessee); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(profile); + return; + } +} + +std::multimap DeviceProfileConnector::GetDevIdAndUserIdByActHash(const std::string &localUdid, + const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash) +{ + LOGI("localUdid %{public}s, peerUdid %{public}s, peerUserId %{public}d, peerAccountHash %{public}s.", + GetAnonyString(localUdid).c_str(), GetAnonyString(peerUdid).c_str(), peerUserId, peerAccountHash.c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::multimap deviceIdMap; + for (const auto &item : profiles) { + std::string accesserAccountId = item.GetAccesser().GetAccesserAccountId(); + std::string accesseeAccountId = item.GetAccessee().GetAccesseeAccountId(); + char accesserAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesserAccountId, reinterpret_cast(accesserAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + char accesseeAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesseeAccountId, reinterpret_cast(accesseeAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + LOGI("accesserAccountIdHash %{public}s, accesseeAccountIdHash %{public}s", accesserAccountIdHash, + accesseeAccountIdHash); + if (std::string(accesserAccountIdHash) != peerAccountHash || + std::string(accesseeAccountIdHash) != peerAccountHash) { + continue; + } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == peerUdid && accesseeUserid == peerUserId) { + deviceIdMap.insert(std::pair(accesserUdid, accesserUserid)); + continue; + } + if (accesseeUdid == localUdid && accesserUdid == peerUdid && accesserUserid == peerUserId) { + deviceIdMap.insert(std::pair(accesseeUdid, accesseeUserid)); + continue; + } + } + return deviceIdMap; +} + +std::multimap DeviceProfileConnector::GetDeviceIdAndUserId(const std::string &localUdid, + int32_t localUserId) +{ + LOGI("localUdid %{public}s, userId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId); + std::vector profiles = GetAllAccessControlProfile(); + std::multimap deviceIdMap; + for (const auto &item : profiles) { + std::string accesserDeviceId = item.GetAccesser().GetAccesserDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + std::string accesseeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserDeviceId == localUdid && accesserUserId == localUserId) { + if (!IsValueExist(deviceIdMap, accesseeDeviceId, accesseeUserId)) { + deviceIdMap.insert(std::pair(accesseeDeviceId, accesseeUserId)); + } + continue; + } + if (accesseeDeviceId == localUdid && accesseeUserId == localUserId) { + if (!IsValueExist(deviceIdMap, accesserDeviceId, accesserUserId)) { + deviceIdMap.insert(std::pair(accesserDeviceId, accesserUserId)); + } + continue; + } + } + return deviceIdMap; +} + +void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (auto &item : profiles) { + std::string accesserDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserDeviceId == localUdid && accesseeDeviceId == remoteUdid && item.GetStatus() == ACTIVE && + find(remoteUserIds.begin(), remoteUserIds.end(), accesseeUserId) != remoteUserIds.end()) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } else if ((accesseeDeviceId == localUdid && accesserDeviceId == remoteUdid) && item.GetStatus() == ACTIVE && + find(remoteUserIds.begin(), remoteUserIds.end(), accesserUserId) != remoteUserIds.end()) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + } +} + +int32_t DeviceProfileConnector::SubscribeDeviceProfileInited( + sptr dpInitedCallback) +{ + LOGI("In"); + if (dpInitedCallback == nullptr) { + LOGE("dpInitedCallback is nullptr"); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t ret = DistributedDeviceProfileClient::GetInstance().SubscribeDeviceProfileInited( + DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, dpInitedCallback); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceProfileConnector::UnSubscribeDeviceProfileInited() +{ + LOGI("In"); + int32_t ret = DistributedDeviceProfileClient::GetInstance().UnSubscribeDeviceProfileInited( + DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceProfileConnector::PutAllTrustedDevices( + const std::vector &deviceInfos) +{ + LOGI("In deviceInfos.size:%{public}zu", deviceInfos.size()); + int32_t ret = DistributedDeviceProfileClient::GetInstance().PutAllTrustedDevices(deviceInfos); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index f51559ab1359c8c1192354a3fbe5ffed418db52c..11b4a2f351c8548902c648d4704fc0f3716801c5 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -15,10 +15,11 @@ #include "multiple_user_connector.h" +#include "dm_constants.h" #include "dm_log.h" - #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "account_info.h" +#include "ipc_skeleton.h" #include "ohos_account_kits.h" #ifdef OS_ACCOUNT_PART_EXISTS #include "os_account_manager.h" @@ -30,7 +31,10 @@ namespace OHOS { namespace DistributedHardware { int32_t MultipleUserConnector::oldUserId_ = -1; std::string MultipleUserConnector::accountId_ = ""; - +std::string MultipleUserConnector::accountName_ = ""; +std::mutex MultipleUserConnector::lock_; +std::map MultipleUserConnector::dmAccountInfoMap_ = {}; +std::mutex MultipleUserConnector::dmAccountInfoMaplock_; #ifndef OS_ACCOUNT_PART_EXISTS const int32_t DEFAULT_OS_ACCOUNT_ID = 0; // 0 is the default id when there is no os_account part #endif // OS_ACCOUNT_PART_EXISTS @@ -39,8 +43,7 @@ int32_t MultipleUserConnector::GetCurrentAccountUserID(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return 0; -#else -#ifdef OS_ACCOUNT_PART_EXISTS +#elif OS_ACCOUNT_PART_EXISTS std::vector ids; ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); if (ret != 0 || ids.empty()) { @@ -50,7 +53,6 @@ int32_t MultipleUserConnector::GetCurrentAccountUserID(void) return ids[0]; #else // OS_ACCOUNT_PART_EXISTS return DEFAULT_OS_ACCOUNT_ID; -#endif // OS_ACCOUNT_PART_EXISTS #endif } @@ -58,8 +60,7 @@ std::string MultipleUserConnector::GetOhosAccountId(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return ""; -#else -#ifdef OS_ACCOUNT_PART_EXISTS +#elif OS_ACCOUNT_PART_EXISTS OhosAccountInfo accountInfo; ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfo(accountInfo); if (ret != 0 || accountInfo.uid_ == "") { @@ -67,30 +68,237 @@ std::string MultipleUserConnector::GetOhosAccountId(void) return ""; } return accountInfo.uid_; -#else // OS_ACCOUNT_PART_EXISTS +#else + return ""; +#endif +} + +std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + (void)userId; + return ""; +#elif OS_ACCOUNT_PART_EXISTS + OhosAccountInfo accountInfo; + ErrCode ret = OhosAccountKits::GetInstance().GetOsAccountDistributedInfo(userId, accountInfo); + if (ret != 0 || accountInfo.uid_ == "") { + LOGE("error ret: %{public}d", ret); + return ""; + } + return accountInfo.uid_; +#else + (void)userId; return ""; -#endif // OS_ACCOUNT_PART_EXISTS +#endif +} + +std::string MultipleUserConnector::GetOhosAccountName(void) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return ""; +#elif OS_ACCOUNT_PART_EXISTS + auto accountInfo = OhosAccountKits::GetInstance().QueryOhosAccountInfo(); + if (!accountInfo.first) { + LOGE("QueryOhosAccountInfo failed."); + return ""; + } + if (accountInfo.second.name_.empty()) { + LOGE("QueryOhosAccountInfo name empty."); + return ""; + } + return accountInfo.second.name_; +#else + return ""; +#endif +} + +void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif + userId = GetFirstForegroundUserId(); +} + +void MultipleUserConnector::GetCallerUserId(int32_t &userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + (void)userId; + return; +#elif OS_ACCOUNT_PART_EXISTS + int32_t uid = OHOS::IPCSkeleton::GetCallingUid(); + ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + if (ret != 0) { + LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); + } + return; +#else // OS_ACCOUNT_PART_EXISTS + (void)userId; + return; #endif } void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) { + std::lock_guard lock(lock_); oldUserId_ = userId; } int32_t MultipleUserConnector::GetSwitchOldUserId(void) { + std::lock_guard lock(lock_); return oldUserId_; } void MultipleUserConnector::SetSwitchOldAccountId(std::string accountId) { + std::lock_guard lock(lock_); accountId_ = accountId; } std::string MultipleUserConnector::GetSwitchOldAccountId(void) { + std::lock_guard lock(lock_); return accountId_; } + +void MultipleUserConnector::SetSwitchOldAccountName(std::string accountName) +{ + std::lock_guard lock(lock_); + accountName_ = accountName; +} + +std::string MultipleUserConnector::GetSwitchOldAccountName(void) +{ + std::lock_guard lock(lock_); + return accountName_; +} + +void MultipleUserConnector::SetAccountInfo(int32_t userId, DMAccountInfo dmAccountInfo) +{ + std::lock_guard lock(dmAccountInfoMaplock_); + dmAccountInfoMap_[userId] = dmAccountInfo; +} + +DMAccountInfo MultipleUserConnector::GetAccountInfoByUserId(int32_t userId) +{ + DMAccountInfo dmAccountInfo; + { + std::lock_guard lock(dmAccountInfoMaplock_); + if (dmAccountInfoMap_.find(userId) != dmAccountInfoMap_.end()) { + dmAccountInfo = dmAccountInfoMap_[userId]; + return dmAccountInfo; + } + } + LOGE("userId is not exist."); + return dmAccountInfo; +} + +void MultipleUserConnector::DeleteAccountInfoByUserId(int32_t userId) +{ + std::lock_guard lock(dmAccountInfoMaplock_); + LOGI("userId: %{public}d", userId); + if (dmAccountInfoMap_.find(userId) != dmAccountInfoMap_.end()) { + dmAccountInfoMap_.erase(userId); + } +} + +int32_t MultipleUserConnector::GetForegroundUserIds(std::vector &userVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userVec.push_back(DEFAULT_OS_ACCOUNT_ID); + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + userVec.clear(); + std::vector accounts; + ErrCode ret = OsAccountManager::GetForegroundOsAccounts(accounts); + if (ret != 0 || accounts.empty()) { + LOGE("error ret: %{public}d", ret); + return ret; + } + for (auto &account : accounts) { + userVec.push_back(account.localId); + } + return DM_OK; +#else // OS_ACCOUNT_PART_EXISTS + userVec.push_back(DEFAULT_OS_ACCOUNT_ID); + return DM_OK; +#endif +} + +int32_t MultipleUserConnector::GetFirstForegroundUserId(void) +{ + std::vector userVec; + int32_t ret = GetForegroundUserIds(userVec); + if (ret != DM_OK || userVec.size() == 0) { + LOGE("get userid error ret: %{public}d.", ret); + return -1; + } + return userVec[0]; +} + +int32_t MultipleUserConnector::GetBackgroundUserIds(std::vector &userIdVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + userIdVec.clear(); + std::vector allOsAccounts; + ErrCode ret = OsAccountManager::QueryAllCreatedOsAccounts(allOsAccounts); + if (ret != 0) { + LOGE("Get all created accounts error, ret: %{public}d", ret); + return ret; + } + + std::vector foregroundAccounts; + ret = OsAccountManager::GetForegroundOsAccounts(foregroundAccounts); + if (ret != 0) { + LOGE("Get foreground accounts error ret: %{public}d", ret); + return ret; + } + + std::vector allUserIds; + std::vector foregroundUserIds; + for (const auto &u : allOsAccounts) { + allUserIds.push_back(u.GetLocalId()); + } + for (const auto &u : foregroundAccounts) { + foregroundUserIds.push_back(u.localId); + } + + for (const auto &userId : allUserIds) { + if (std::find(foregroundUserIds.begin(), foregroundUserIds.end(), userId) == foregroundUserIds.end()) { + userIdVec.push_back(userId); + } + } + return DM_OK; +#else + return DM_OK; +#endif +} + +int32_t MultipleUserConnector::GetAllUserIds(std::vector &userIdVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + userIdVec.clear(); + std::vector allOsAccounts; + ErrCode ret = OsAccountManager::QueryAllCreatedOsAccounts(allOsAccounts); + if (ret != 0) { + LOGE("Get all created accounts error, ret: %{public}d", ret); + return ret; + } + + for (const auto &u : allOsAccounts) { + userIdVec.push_back(u.GetLocalId()); + } + return DM_OK; +#else + return DM_OK; +#endif +} } // namespace DistributedHardware } // namespace OHOS diff --git a/device_manager.gni b/device_manager.gni index f07ffdfda6f5a6bfc534336db7f8ec5f76c354f2..d197e5b76926abddff618697c753db8a829a3649 100644 --- a/device_manager.gni +++ b/device_manager.gni @@ -36,21 +36,21 @@ declare_args() { device_manager_no_interaction_auth = false device_manager_feature_product = "default" - if (!defined(global_parts_info) || + if (defined(global_parts_info) && defined(global_parts_info.account_os_account)) { os_account_part_exists = true } else { os_account_part_exists = false } - if (!defined(global_parts_info) || + if (defined(global_parts_info) && defined(global_parts_info.communication_bluetooth)) { support_bluetooth = true } else { support_bluetooth = false } - if (!defined(global_parts_info) || + if (defined(global_parts_info) && defined(global_parts_info.communication_wifi)) { support_wifi = true } else { @@ -70,4 +70,19 @@ declare_args() { } else { support_screenlock = false } + + if (defined(global_parts_info) && + defined(global_parts_info.resourceschedule_memmgr_override)) { + support_memmgr = true + } else { + support_memmgr = false + } + + if (defined(global_parts_info) && + defined( + global_parts_info.distributedhardware_distributed_hardware_adapter)) { + device_manager_common = false + } else { + device_manager_common = true + } } diff --git a/display/AppScope/app.json b/display/AppScope/app.json index e2743b68d6ac665598e0799051b2b35b0f71a082..335740525c2f40cfc0f08712b82d6965fd56abf9 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -1,17 +1,16 @@ - - { "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000016, - "versionName": "1.0.16", + "versionCode": 1000025, + "versionName": "1.0.25", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, "targetAPIVersion": 10, "distributedNotificationEnabled": true, "apiReleaseType": "Beta3", - "debug": false + "debug": false, + "configuration":"$profile:configuration" } } diff --git a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets index 4c24158c3efed072fb4facb2e47fda8be325f6b1..15a8081dcf0b8c1adbb458e2a8726e667d88682a 100644 --- a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets @@ -24,6 +24,9 @@ export default class InputUIExtAbility extends UIExtensionAbility { if (want.parameters && want.parameters.targetDeviceName) { AppStorage.setOrCreate('targetDeviceName', want.parameters.targetDeviceName); } + if (want.parameters && want.parameters.model) { + AppStorage.setOrCreate('model', want.parameters.model); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/pages/ConfirmDialog.ets b/display/entry/src/main/ets/pages/ConfirmDialog.ets index 2e320c6a25ac309af78e801644944924660baacf..598b966e375626a7bb6e1421f854b71090cd060a 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialog.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialog.ets @@ -139,14 +139,6 @@ struct ConfirmCustomDialog { } destruction() { - if (dmClass != null) { - try { - dmClass.release(); - dmClass = null; - } catch (error) { - console.log('dmClass release failed') - } - } let session = AppStorage.get('ConfirmSession'); if (session) { session.terminateSelf(); @@ -356,6 +348,7 @@ struct dialogPlusPage { let tmpStr: Record = JSON.parse(data.param) let msg: number = tmpStr.uiStateMsg as number if (msg === MSG_CANCEL_CONFIRM_SHOW) { + console.log('cancel confirm show.') this.destruction() return } @@ -369,17 +362,22 @@ struct dialogPlusPage { } destruction() { + let session = AppStorage.get('ConfirmSession'); + if (session) { + session.terminateSelf(); + } + } + + aboutToDisappear() { + console.log(TAG + 'aboutToDisappear aboutToDisappear') if (dmClass != null) { try { + dmClass.off('uiStateChange'); dmClass.release(); - dmClass = null; } catch (error) { console.log('dmClass release failed') } - } - let session = AppStorage.get('ConfirmSession'); - if (session) { - session.terminateSelf(); + dmClass = null } } diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index d261d732a5b9ab9845ad641a84b0d9eb549250ca..b7815957d4e96446cf5440a0be221c054758f9b9 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -26,6 +26,8 @@ const ACTION_DONE_PINCODE_INPUT: number = 5 const MSG_PIN_CODE_ERROR: number = 0 const MSG_CANCEL_PIN_CODE_INPUT: number = 3 const MSG_DOING_AUTH: number = 4 +const MODEL_PIN: string = 'pin'; +const MODEL_PASSWORD: string = 'password'; @CustomDialog struct InputCustomDialog { @@ -36,6 +38,7 @@ struct InputCustomDialog { @State errorTipsVisible: Visibility = Visibility.None; @State heightNum: number = 600; @State targetDeviceName: string = ''; + @State model: string = MODEL_PIN; @State isPC: boolean = false; @State btnColor: ResourceColor = Color.Transparent; listener: mediaquery.MediaQueryListener = mediaquery.matchMediaSync('(orientation: landscape)'); @@ -67,6 +70,10 @@ struct InputCustomDialog { this.targetDeviceName = AppStorage.get('targetDeviceName') as string; console.log('targetDeviceName is ' + this.targetDeviceName); } + if (AppStorage.get('model') != null) { + this.model = AppStorage.get('model') as string; + console.log('model is ' + this.model); + } deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', (err: Error, dm: deviceManager.DeviceManager) => { if (err) { @@ -88,8 +95,12 @@ struct InputCustomDialog { return; } if (msg === MSG_PIN_CODE_ERROR) { - this.isTimes--; - this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); + if (this.model == MODEL_PASSWORD) { + this.errorTips = $r('app.string.dm_password_error'); + } else { + this.isTimes--; + this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); + } this.password = ''; this.errorTipsVisible = Visibility.Visible; this.passwordCircle = ['', '', '', '', '', '']; @@ -216,7 +227,6 @@ struct InputCustomDialog { .fontSize($r('sys.float.ohos_id_text_size_headline7')) .fontColor($r('sys.color.ohos_id_color_text_primary')) .fontWeight(FontWeight.Medium) - .height(26) }.width('10%') .height('100%') .visibility(item === '' ? Visibility.None : Visibility.Visible) @@ -306,8 +316,8 @@ struct InputCustomDialog { } }) }.margin({ - left: this.isPC ? 72 : 16, - right: this.isPC ? 72 : 16, + left: 16, + right: 16, bottom: this.isPC ? 24 : 16 }) } } @@ -316,7 +326,10 @@ struct InputCustomDialog { .constraintSize({ maxHeight: `${this.heightNum}`}) .borderRadius($r('sys.float.ohos_id_corner_radius_dialog')) .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) - .margin({ left: $r('sys.float.ohos_id_dialog_margin_start'), right: $r('sys.float.ohos_id_dialog_margin_end') }) + .margin({ + left: $r('sys.float.ohos_id_dialog_margin_bottom'), + right: $r('sys.float.ohos_id_dialog_margin_bottom') + }) } }.margin({top: 8, bottom: 20}) } @@ -335,7 +348,7 @@ struct dialogPlusPage { }); aboutToAppear() { - console.log(TAG + 'aboutToAppear aboutToAppear') + console.log(TAG + 'aboutToAppear aboutToAppear'); } aboutToDisappear() { diff --git a/display/entry/src/main/ets/pages/PinDialog.ets b/display/entry/src/main/ets/pages/PinDialog.ets index 7645b200cf721170a5c8b740014b902e5933c48d..2ee89538be9e9fa332493d83b1da801c0a9ca19d 100644 --- a/display/entry/src/main/ets/pages/PinDialog.ets +++ b/display/entry/src/main/ets/pages/PinDialog.ets @@ -95,7 +95,6 @@ struct PinCustomDialog { .fontSize($r('sys.float.ohos_id_text_size_headline7')) .fontColor($r('sys.color.ohos_id_color_text_primary')) .fontWeight(FontWeight.Medium) - .height(26) }.width('10%') .height('100%') }) @@ -133,8 +132,8 @@ struct PinCustomDialog { } }) }.margin({ - left: this.isPC ? 72 : 16, - right: this.isPC ? 72 : 16, + left: 16, + right: 16, bottom: this.isPC ? 24 : 16 }) } .constraintSize({ maxHeight: `${300}` }) diff --git a/display/entry/src/main/module.json b/display/entry/src/main/module.json index a18b0c6a78b2f4b900b208aa48be7bbef071fae9..0c27af8a5bc98d008440808df91b2641ac2f3419 100644 --- a/display/entry/src/main/module.json +++ b/display/entry/src/main/module.json @@ -5,7 +5,7 @@ "srcEntrance": "", "description": "$string:entry_desc", "mainElement": "MainAbility", - "deviceTypes": ["default", "tablet", "2in1", "wearable"], + "deviceTypes": ["default", "tablet", "2in1", "wearable", "car"], "deliveryWithInstall": true, "installationFree": false, "pages": "$profile:main_pages", diff --git a/display/entry/src/main/resources/base/element/plural.json b/display/entry/src/main/resources/base/element/plural.json index e19eb94d6e455f84f0f484e554a742fd7e15e85d..f103d249c9a88320efd93b45090dd412c9d5ceef 100644 --- a/display/entry/src/main/resources/base/element/plural.json +++ b/display/entry/src/main/resources/base/element/plural.json @@ -18,11 +18,11 @@ "value":[ { "quantity":"one", - "value":"Incorrect connection code. %d attempt remaining." + "value":"Incorrect. %d attempt remaining." }, { "quantity":"other", - "value":"Incorrect connection code. %d attempts remaining." + "value":"Incorrect. %d attempts remaining." } ] } diff --git a/display/entry/src/main/resources/base/element/string.json b/display/entry/src/main/resources/base/element/string.json index fdcc8bdf1b1668c1479c6c133edc932d67a6ed7d..ad22f14feb9945e54dd5971f128f73c048c7d806 100644 --- a/display/entry/src/main/resources/base/element/string.json +++ b/display/entry/src/main/resources/base/element/string.json @@ -78,7 +78,11 @@ }, { "name":"dm_enter_peer_connect_code", - "value":"Enter the peer connection code" + "value":"Enter connection code" + }, + { + "name":"dm_password_error", + "value":"Incorrect password. Connection failed." } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/base/profile/configuration.json b/display/entry/src/main/resources/base/profile/configuration.json new file mode 100644 index 0000000000000000000000000000000000000000..b2635e1f42018f496ff164de4d6e8c45f3650228 --- /dev/null +++ b/display/entry/src/main/resources/base/profile/configuration.json @@ -0,0 +1,6 @@ +{ + "configuration": { + "fontSizeScale" : "followSystem", + "fontSizeMaxScale" : "3.2" + } +} \ No newline at end of file diff --git a/display/entry/src/main/resources/bo_CN/element/string.json b/display/entry/src/main/resources/bo_CN/element/string.json index 172322a6839b1a15ad2a18ea257841dbb3b1868f..3b5e8dd456a2b2475b24e895528c997627e2cd2d 100644 --- a/display/entry/src/main/resources/bo_CN/element/string.json +++ b/display/entry/src/main/resources/bo_CN/element/string.json @@ -55,6 +55,14 @@ { "name":"dm_bluetooth_dialog_content", "value":"སྒྲིག་ཆས་སྦྲེལ་མཐུད་བྱ་བར་སོ་སྔོན་ཁ་འབྱེད་དགོས། ཁ་ཕྱེ་ནས་ཡང་བསྐྱར་ཚོད་ལྟ་གནང་རོགས།" + }, + { + "name":"dm_password_error", + "value":"གསང་གྲངས་ནོར་འཁྲུལ་བྱུང་། སྦྲེལ་མཐུད་བྱེད་མ་ཐུབ།" + }, + { + "name":"dm_enter_peer_connect_code", + "value":"ཕ་རོལ་སྣེའི་སྦྲེལ་མཐུད་ཨང་རྟགས་འཇུག་རོགས།" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/ug/element/string.json b/display/entry/src/main/resources/ug/element/string.json index bef55b20e86f8bf9725acf9c7d63b9de4f8fd702..88d86cb8aed9ccce832569346d49ec19767310f2 100644 --- a/display/entry/src/main/resources/ug/element/string.json +++ b/display/entry/src/main/resources/ug/element/string.json @@ -55,6 +55,14 @@ { "name":"dm_bluetooth_dialog_content", "value":"ئۈسكۈنە ئۇلاش ئۈچۈن كۆكچىشنى ئېچىش كېرەك، ئېچىپ قايتا سىناڭ." + }, + { + "name":"dm_password_error", + "value":"مەخپىي نومۇر خاتا، ئۇلانمىدى." + }, + { + "name":"dm_enter_peer_connect_code", + "value":"ئۇلاش كودى كىرگۈزۈڭ" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_CN/element/plural.json b/display/entry/src/main/resources/zh_CN/element/plural.json index cc627408d22581e125da7000b066534372d4647f..47e018471f47668a73f5c6686e28e948cb24adb0 100644 --- a/display/entry/src/main/resources/zh_CN/element/plural.json +++ b/display/entry/src/main/resources/zh_CN/element/plural.json @@ -22,7 +22,7 @@ }, { "quantity":"other", - "value":"连接码错误,还可尝试 %d 次" + "value":"连接码错误,还可以尝试 %d 次" } ] } diff --git a/display/entry/src/main/resources/zh_CN/element/string.json b/display/entry/src/main/resources/zh_CN/element/string.json index cde7f2102286ec9497431aaf629be327ec791e69..e4e630fb176f7bf6e5fb7c227e40563fa64f46f0 100644 --- a/display/entry/src/main/resources/zh_CN/element/string.json +++ b/display/entry/src/main/resources/zh_CN/element/string.json @@ -79,6 +79,10 @@ { "name":"dm_enter_peer_connect_code", "value":"输入对端连接码" + }, + { + "name":"dm_password_error", + "value":"密码错误,连接失败。" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_HK/element/string.json b/display/entry/src/main/resources/zh_HK/element/string.json index 52c71bd58bc3a9552373a51b6cb4bc61eddd3a4c..86d184a73027604b6874a73a2f02ba732b9458d5 100644 --- a/display/entry/src/main/resources/zh_HK/element/string.json +++ b/display/entry/src/main/resources/zh_HK/element/string.json @@ -34,7 +34,7 @@ }, { "name":"dm_is_trust_device", - "value":"%s 信任此裝置?" + "value":"%s信任此裝置?" }, { "name":"dm_confirm_title_hap", @@ -55,6 +55,14 @@ { "name":"dm_bluetooth_dialog_content", "value":"裝置連接需要啟用藍牙。請先啟用,然後重試。" + }, + { + "name":"dm_password_error", + "value":"密碼錯誤,連接失敗。" + }, + { + "name":"dm_enter_peer_connect_code", + "value":"輸入對端連接碼" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_TW/element/string.json b/display/entry/src/main/resources/zh_TW/element/string.json index a5e5c5eca4a47ac491ed3252092e6b6ba4465093..c8117d996de36692610f30436e96aca64c3e1362 100644 --- a/display/entry/src/main/resources/zh_TW/element/string.json +++ b/display/entry/src/main/resources/zh_TW/element/string.json @@ -26,7 +26,7 @@ }, { "name":"dm_allow_always", - "value":"始終信任" + "value":"永遠信任" }, { "name":"dm_confirm_title_cast", @@ -55,6 +55,14 @@ { "name":"dm_bluetooth_dialog_content", "value":"裝置連線需要啟用藍牙,請啟用後重試。" + }, + { + "name":"dm_password_error", + "value":"密碼錯誤,連線失敗。" + }, + { + "name":"dm_enter_peer_connect_code", + "value":"輸入對端連線碼" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zz_ZX/element/plural.json b/display/entry/src/main/resources/zz_ZX/element/plural.json index f015807ed592d19af72ee756eeb2a97196d6ad9b..45ea146440ef761e3443afa3c78254636d671136 100644 --- a/display/entry/src/main/resources/zz_ZX/element/plural.json +++ b/display/entry/src/main/resources/zz_ZX/element/plural.json @@ -5,27 +5,27 @@ "value":[ { "quantity":"one", - "value":"[TS_922746]_Incorrect connection code. %d attempt remaining." + "value":"[TS_922746]_Incorrect. %d attempt remaining." }, { "quantity":"other", - "value":"[TS_922743]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922743]_Incorrect. %d attempts remaining." }, { "quantity":"zero", - "value":"[TS_922738]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922738]_Incorrect. %d attempts remaining." }, { "quantity":"few", - "value":"[TS_922740]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922740]_Incorrect. %d attempts remaining." }, { "quantity":"many", - "value":"[TS_922747]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922747]_Incorrect. %d attempts remaining." }, { "quantity":"two", - "value":"[TS_922736]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922736]_Incorrect. %d attempts remaining." } ] }, diff --git a/display/entry/src/main/resources/zz_ZX/element/string.json b/display/entry/src/main/resources/zz_ZX/element/string.json index 7404e663b86b665853b732f391d9c814b4085e93..1fdf6a26cacf1810aa04c6f92a843dda896250ec 100644 --- a/display/entry/src/main/resources/zz_ZX/element/string.json +++ b/display/entry/src/main/resources/zz_ZX/element/string.json @@ -75,6 +75,14 @@ { "name":"dm_confirm_intention", "value":"[TS_931360]_This is required for cross-device data syncing and collaboration." + }, + { + "name":"dm_enter_peer_connect_code", + "value":"[TS_949559]_Enter connection code" + }, + { + "name":"dm_password_error", + "value":"[TS_958913]_Incorrect password. Connection failed." } ] } \ No newline at end of file diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index 740e11e1b1d81bc0ec751bd168d8c1aae61ac497..f82d51102c64e953d5cd1d89a33d8dc6c4bb6bed 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -79,6 +79,7 @@ ohos_shared_library("devicemanagerext_pin_auth") { "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_single", diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp index 82852b6d10542d4d2d92c58abfe3d74998b7fa9e..3beb339fd31437005cd5498dc3123f680e283517 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -23,7 +23,11 @@ namespace OHOS { namespace DistributedHardware { AbilityStatus DmAbilityManager::StartAbility(AAFwk::Want &want) { - AAFwk::AbilityManagerClient::GetInstance()->Connect(); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->Connect(); + if (ret != 0) { + LOGE("Connect Ability failed, error value = %{public}d", (int32_t)ret); + return AbilityStatus::ABILITY_STATUS_FAILED; + } ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); if (result != 0) { LOGE("Start Ability failed, error value = %{public}d", (int32_t)result); diff --git a/interfaces/cj/BUILD.gn b/interfaces/cj/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9a245a111200b75cb1c84de110f14ebf1effcddd --- /dev/null +++ b/interfaces/cj/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +ohos_shared_library("cj_distributed_device_manager_ffi") { + branch_protector_ret = "pac_ret" + + sanitize = { + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + integer_overflow = true + ubsan = true + } + + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-fvisibility=hidden", + ] + + include_dirs = [ + "include", + "${common_path}/include", + "${common_path}/include/ipc", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc", + "${innerkits_path}/native_cpp/include/ipc/standard", + ] + + sources = [ + "${common_path}/src/dm_anonymous.cpp", + "${common_path}/src/dm_error_message.cpp", + "src/device_manager_ffi.cpp", + "src/device_manager_impl.cpp", + "src/device_manager_utils.cpp", + ] + + deps = [ "${innerkits_path}/native_cpp:devicemanagersdk" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"cj_distrubuted_devicemanager\"", + "LOG_DOMAIN=0xD004111", + ] + + external_deps = [ + "access_token:libtokenid_sdk", + "bounds_checking_function:libsec_shared", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "json:nlohmann_json_static", + "napi:cj_bind_ffi", + "napi:cj_bind_native", + ] + + innerapi_tags = [ "platformsdk" ] + subsystem_name = "distributedhardware" + part_name = "device_manager" +} diff --git a/interfaces/cj/include/device_manager_ffi.h b/interfaces/cj/include/device_manager_ffi.h new file mode 100644 index 0000000000000000000000000000000000000000..f29e161206cf3377969f7c48f5a3b0e2ce0c8323 --- /dev/null +++ b/interfaces/cj/include/device_manager_ffi.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_MANAGER_FFI_H +#define OHOS_DEVICE_MANAGER_FFI_H + +#include "cj_common_ffi.h" +#include "ffi_remote_data.h" + +extern "C" { +typedef struct { + char *deviceId; + char *deviceName; + uint16_t deviceType; + char *networkId; +} FfiDeviceBasicInfo; + +typedef struct { + FfiDeviceBasicInfo *head; + int64_t size; +} FfiDeviceBasicInfoArray; + +FFI_EXPORT int64_t FfiOHOSDistributedDeviceManagerCreateDeviceManager(const char *name, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerReleaseDeviceManager(int64_t id, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerGetAvailableDeviceList( + int64_t id, FfiDeviceBasicInfoArray *deviceInfoList, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerFreeDeviceInfoList(FfiDeviceBasicInfoArray deviceInfoList); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceNetworkId(int64_t id, int32_t *errCode); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceName(int64_t id, int32_t *errCode); + +FFI_EXPORT int32_t FfiOHOSDistributedDeviceManagerGetLocalDeviceType(int64_t id, int32_t *errCode); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceId(int64_t id, int32_t *errCode); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetDeviceName( + int64_t id, const char *networkId, int32_t *errCode); + +FFI_EXPORT int32_t FfiOHOSDistributedDeviceManagerGetDeviceType(int64_t id, const char *networkId, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerStartDiscovering(int64_t id, const char *extra, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerStopDiscovering(int64_t id, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerBindTarget(int64_t id, const char *deviceId, const char *bindParam, + bool isMetaType, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerUnbindTarget(int64_t id, const char *deviceId, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerOn(int64_t id, const char *type, void *callback, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerOff(int64_t id, const char *type, int32_t *errCode); +} + +#endif // OHOS_DEVICE_MANAGER_FFI_H diff --git a/interfaces/cj/include/device_manager_impl.h b/interfaces/cj/include/device_manager_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..30d8cd6c24111ae05c46c973b358b44fc0933a6f --- /dev/null +++ b/interfaces/cj/include/device_manager_impl.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_MANAGER_IMPL_H +#define OHOS_DEVICE_MANAGER_IMPL_H + +#include +#include +#include +#include + +#include "ffi_remote_data.h" + +#include "device_manager_ffi.h" +#include "device_manager_utils.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerFfiImpl : public OHOS::FFI::FFIData { +public: + explicit DeviceManagerFfiImpl(const std::string &bundleName, int32_t *errCode); + ~DeviceManagerFfiImpl() override = default; + + static DeviceManagerFfiImpl *GetDeviceManagerFfi(std::string &bundleName); + + int32_t ReleaseDeviceManager(); + int32_t GetAvailableDeviceList(FfiDeviceBasicInfoArray &deviceInfoList); + static void DeviceListFree(FfiDeviceBasicInfoArray &deviceInfoList, int64_t size = -1); + int32_t GetLocalDeviceNetworkId(const char *&networkId); + int32_t GetLocalDeviceName(const char *&deviceName); + int32_t GetLocalDeviceType(int32_t &deviceType); + int32_t GetLocalDeviceId(const char *&deviceId); + int32_t GetDeviceName(const std::string &networkId, const char *&deviceName); + int32_t GetDeviceType(const std::string &networkId, int32_t &deviceType); + int32_t StartDiscovering(const std::string &extra); + int32_t StopDiscovering(); + int32_t BindTarget(const std::string &deviceId, const std::string &bindParam, bool isMetaType); + int32_t UnbindTarget(const std::string &deviceId); + int32_t EventOn(const std::string &type, void *callback); + int32_t EventOff(const std::string &type); + + void OnDeviceStatusChange(int32_t action, const DmDeviceBasicInfo &deviceBasicInfo); + void OnDeviceNameChange(const std::string &deviceName); + void OnDeviceFound(uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo); + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason); + void OnPublishResult(int32_t publishId, int32_t publishResult); + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason); + void OnDmUiCall(const std::string ¶mJson); + +private: + void ClearBundleCallbacks(); + static int32_t Transform2FfiDeviceBasicInfo(const DmDeviceBasicInfo &in, FfiDeviceBasicInfo &out); + int32_t BindTargetWarpper(const std::string &deviceId, + const std::string &bindParam, std::shared_ptr callback); + int32_t WaitForCallbackCv(); + + int32_t RegisterDevStatusCallback(); + int32_t RegisterDiscoveryCallback(); + int32_t RegisterPublishCallback(); + int32_t RegisterReplyCallback(); + + int32_t ReleaseDevStatusCallback(); + int32_t ReleaseDiscoveryCallback(); + int32_t ReleasePublishCallback(); + int32_t ReleaseReplyCallback(); + + void RegisterCallbackByType(const std::string &type, void *callback); + void Off(const std::string &type); + + inline static void FreeDeviceInfo(const FfiDeviceBasicInfo &info) + { + free(info.deviceId); + free(info.deviceName); + free(info.networkId); + }; + + std::string bundleName_; + std::function deviceStateChangedCallback; + std::function discoverSuccessCallback; + std::function deviceNameChangedCallback; + std::function deviceDiscoverFailedCallback; + std::mutex callbackLock; + + std::condition_variable callbackFinishedCv; + std::mutex callbackFinishedMutex; + bool callbackFinished = false; + std::atomic errCode_ = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IMPL_H diff --git a/interfaces/cj/include/device_manager_utils.h b/interfaces/cj/include/device_manager_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..871634e8a332bd267cc2620c4c31e885be9ca5ae --- /dev/null +++ b/interfaces/cj/include/device_manager_utils.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_MANAGER_UTILS_H +#define OHOS_DEVICE_MANAGER_UTILS_H + +#include + +#include "nlohmann/json.hpp" + +#include "device_manager_callback.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { + +enum DmFfiDevStatusChange { UNKNOWN = 0, AVAILABLE = 1, UNAVAILABLE = 2, CHANGE = 3}; + +class DmFfiInitCallback : public DmInitCallback { +public: + explicit DmFfiInitCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiInitCallback() override = default; + void OnRemoteDied() override; + +private: + std::string bundleName_; +}; + +class DmFfiDeviceStatusCallback : public DeviceStatusCallback { +public: + explicit DmFfiDeviceStatusCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiDeviceStatusCallback() override = default; + void OnDeviceOnline(const DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceOffline(const DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceChanged(const DmDeviceBasicInfo &deviceBasicInfo) override; +private: + std::string bundleName_; +}; + +class DmFfiDiscoveryCallback : public DiscoveryCallback { +public: + explicit DmFfiDiscoveryCallback(const std::string &bundleName): refCount_(0), bundleName_(bundleName) + { + } + ~DmFfiDiscoveryCallback() override = default; + void OnDeviceFound(uint16_t subscribeId, + const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; + void OnDiscoverySuccess(uint16_t subscribeId) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); + +private: + std::atomic refCount_; + std::string bundleName_; +}; + +class DmFfiPublishCallback : public PublishCallback { +public: + explicit DmFfiPublishCallback(const std::string &bundleName): refCount_(0), bundleName_(bundleName) + { + } + ~DmFfiPublishCallback() override = default; + void OnPublishResult(int32_t publishId, int32_t publishResult) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); + +private: + std::atomic refCount_; + std::string bundleName_; +}; + +class DmFfiDeviceManagerUiCallback : public DeviceManagerUiCallback { +public: + explicit DmFfiDeviceManagerUiCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiDeviceManagerUiCallback() override = default; + void OnCall(const std::string ¶mJson) override; + +private: + std::string bundleName_; +}; + +class DmFfiAuthenticateCallback : public AuthenticateCallback { +public: + explicit DmFfiAuthenticateCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiAuthenticateCallback() override = default; + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override; + +private: + std::string bundleName_; +}; + +class DmFfiBindTargetCallback : public BindTargetCallback { +public: + explicit DmFfiBindTargetCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiBindTargetCallback() override = default; + void OnBindResult(const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; + +private: + std::string bundleName_; +}; + +const std::string &GetDeviceTypeById(DmDeviceType type); +char *MallocCStr(const char *in); +void InsertMapParames(nlohmann::json &bindParamObj, std::map &bindParamMap); +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DEVICE_MANAGER_IMPL_H diff --git a/interfaces/cj/src/device_manager_ffi.cpp b/interfaces/cj/src/device_manager_ffi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6a0b9ca798ee96c90e5f7801dad4ace4558b4a1 --- /dev/null +++ b/interfaces/cj/src/device_manager_ffi.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_ffi.h" + +#include + +#include "device_manager.h" +#include "device_manager_impl.h" +#include "dm_log.h" + +int64_t FfiOHOSDistributedDeviceManagerCreateDeviceManager(const char *name, int32_t *errCode) +{ + auto deviceManager = OHOS::FFI::FFIData::Create( + std::string(name), errCode); + if (*errCode != 0) { + LOGE("deviceManager create fail, the errcode is %{public}d", *errCode); + delete static_cast(deviceManager); + return 0; + } + return deviceManager->GetID(); +} + +void FfiOHOSDistributedDeviceManagerReleaseDeviceManager(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->ReleaseDeviceManager(); +} + +void FfiOHOSDistributedDeviceManagerGetAvailableDeviceList( + int64_t id, FfiDeviceBasicInfoArray *deviceInfoList, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->GetAvailableDeviceList(*deviceInfoList); +} + +void FfiOHOSDistributedDeviceManagerFreeDeviceInfoList(FfiDeviceBasicInfoArray deviceInfoList) +{ + OHOS::DistributedHardware::DeviceManagerFfiImpl::DeviceListFree(deviceInfoList); +} + +const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceNetworkId(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *networkIdPtr = nullptr; + *errCode = instance->GetLocalDeviceNetworkId(networkIdPtr); + return networkIdPtr; +} + +const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceName(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *deviceName = nullptr; + *errCode = instance->GetLocalDeviceName(deviceName); + return deviceName; +} + +int32_t FfiOHOSDistributedDeviceManagerGetLocalDeviceType(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + int32_t deviceType = 0; + *errCode = instance->GetLocalDeviceType(deviceType); + return deviceType; +} + +const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceId(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *deviceId = nullptr; + *errCode = instance->GetLocalDeviceId(deviceId); + return deviceId; +} + +const char *FfiOHOSDistributedDeviceManagerGetDeviceName(int64_t id, const char *networkId, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *deviceName = nullptr; + *errCode = instance->GetDeviceName(networkId, deviceName); + return deviceName; +} + +int32_t FfiOHOSDistributedDeviceManagerGetDeviceType(int64_t id, const char *networkId, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + int32_t deviceType = 0; + *errCode = instance->GetDeviceType(networkId, deviceType); + return deviceType; +} + +void FfiOHOSDistributedDeviceManagerStartDiscovering(int64_t id, const char *extra, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->StartDiscovering(extra); +} + +void FfiOHOSDistributedDeviceManagerStopDiscovering(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->StopDiscovering(); +} + +void FfiOHOSDistributedDeviceManagerBindTarget( + int64_t id, const char *deviceId, const char *bindParam, bool isMetaType, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->BindTarget(deviceId, bindParam, isMetaType); +} + +void FfiOHOSDistributedDeviceManagerUnbindTarget(int64_t id, const char *deviceId, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->UnbindTarget(deviceId); +} + +void FfiOHOSDistributedDeviceManagerOn(int64_t id, const char *type, void *callback, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->EventOn(type, callback); +} + +void FfiOHOSDistributedDeviceManagerOff(int64_t id, const char *type, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->EventOff(type); +} diff --git a/interfaces/cj/src/device_manager_impl.cpp b/interfaces/cj/src/device_manager_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aee35808bb46ee2e80c3dbdf9d3e19def2c5082c --- /dev/null +++ b/interfaces/cj/src/device_manager_impl.cpp @@ -0,0 +1,881 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_impl.h" + +#include +#include + +#include "cj_lambda.h" +#include "ipc_skeleton.h" + +#include "device_manager.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_error_message.h" +#include "dm_log.h" + +namespace OHOS::DistributedHardware { + +namespace { +std::map g_deviceManagerMap; +std::map> g_initCallbackMap; +std::map> g_deviceStatusCallbackMap; +std::map> g_DiscoveryCallbackMap; +std::map> g_publishCallbackMap; +std::map> g_authCallbackMap; +std::map> g_bindCallbackMap; +std::map> g_dmUiCallbackMap; + +std::mutex g_deviceManagerMapMutex; +std::mutex g_initCallbackMapMutex; +std::mutex g_deviceStatusCallbackMapMutex; +std::mutex g_discoveryCallbackMapMutex; +std::mutex g_publishCallbackMapMutex; +std::mutex g_authCallbackMapMutex; +std::mutex g_bindCallbackMapMutex; +std::mutex g_dmUiCallbackMapMutex; + +const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7; +const int32_t DM_FFI_BUF_LENGTH = 256; + +const std::string DM_FFI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange"; +const std::string DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS = "discoverSuccess"; +const std::string DM_FFI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFailure"; +const std::string DM_FFI_EVENT_DEVICE_PUBLISH_SUCCESS = "publishSuccess"; +const std::string DM_FFI_EVENT_DEVICE_PUBLISH_FAIL = "publishFailure"; +const std::string DEVICE_MANAGER_FFI_CLASS_NAME = "DeviceManager"; +const std::string DM_FFI_EVENT_REPLY_RESULT = "replyResult"; +const std::string DM_FFI_EVENT_DEVICE_NAME_CHANGE = "deviceNameChange"; + +enum ErrorCode { + // OK + ERR_OK = 0, + // Permission verify failed. + ERR_NO_PERMISSION = 201, + // The caller is not a system application. + ERR_NOT_SYSTEM_APP = 202, + // Input parameter error. + ERR_INVALID_PARAMS = 401, + // Failed to execute the function. + DM_ERR_FAILED = 11600101, + // Failed to obtain the service. + DM_ERR_OBTAIN_SERVICE = 11600102, + // Authentication invalid. + DM_ERR_AUTHENTICALTION_INVALID = 11600103, + // Discovery invalid. + DM_ERR_DISCOVERY_INVALID = 11600104, + // Publish invalid. + DM_ERR_PUBLISH_INVALID = 11600105, +}; + +inline int32_t stringCheck(const std::string &str) +{ + if (str.size() == 0 || str.size() >= DM_FFI_BUF_LENGTH) { + return ERR_INVALID_PARAMS; + } + return ERR_OK; +} + +int32_t transformErrCode(const int32_t errCode) +{ + switch (errCode) { + case ERR_DM_NO_PERMISSION: + return ERR_NO_PERMISSION; + case ERR_DM_DISCOVERY_REPEATED: + return DM_ERR_DISCOVERY_INVALID; + case ERR_DM_PUBLISH_REPEATED: + return DM_ERR_PUBLISH_INVALID; + case ERR_DM_AUTH_BUSINESS_BUSY: + return DM_ERR_AUTHENTICALTION_INVALID; + case ERR_DM_INPUT_PARA_INVALID: + case ERR_DM_UNSUPPORTED_AUTH_TYPE: + return ERR_INVALID_PARAMS; + case ERR_DM_INIT_FAILED: + return DM_ERR_OBTAIN_SERVICE; + case ERR_NOT_SYSTEM_APP: + return ERR_NOT_SYSTEM_APP; + default: + return DM_ERR_FAILED; + } + return 0; +} + +inline void InsertIntItem(nlohmann::json &jsonObj, std::map &jsonMap, + const std::string &searchKey, const std::string &insertKey) +{ + if (IsInt32(jsonObj, searchKey)) { + int32_t value = jsonObj[searchKey].get(); + jsonMap.insert(std::pair(insertKey, std::to_string(value))); + } +} + +inline void InsertStringItem(nlohmann::json &jsonObj, std::map &jsonMap, + const std::string &searchKey, const std::string &insertKey) +{ + if (IsString(jsonObj, searchKey)) { + std::string value = jsonObj[searchKey].get(); + jsonMap.insert(std::pair(insertKey, value)); + } +} + +void InsertJsonParamesToMap(nlohmann::json &bindParamObj, std::map &bindParamMap) +{ + LOGI("Insert map parames start"); + InsertIntItem(bindParamObj, bindParamMap, AUTH_TYPE, PARAM_KEY_AUTH_TYPE); + InsertStringItem(bindParamObj, bindParamMap, APP_OPERATION, PARAM_KEY_APP_OPER); + InsertStringItem(bindParamObj, bindParamMap, CUSTOM_DESCRIPTION, PARAM_KEY_APP_DESC); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_TARGET_PKG_NAME, PARAM_KEY_TARGET_PKG_NAME); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_META_TYPE, PARAM_KEY_META_TYPE); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_PIN_CODE, PARAM_KEY_PIN_CODE); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_AUTH_TOKEN, PARAM_KEY_AUTH_TOKEN); + InsertIntItem(bindParamObj, bindParamMap, BIND_LEVEL, BIND_LEVEL); +} +} // namespace + +DeviceManagerFfiImpl::DeviceManagerFfiImpl(const std::string &bundleName, int32_t *errCode) : bundleName_(bundleName) +{ + *errCode = stringCheck(bundleName); + if (*errCode != 0) { + LOGE("CreateDeviceManager for bundleName %{public}s failed, ret %{public}d.", bundleName_.c_str(), *errCode); + return; + } + std::shared_ptr initCallback = std::make_shared(bundleName_); + *errCode = DeviceManager::GetInstance().InitDeviceManager(bundleName_, initCallback); + if (*errCode != 0) { + *errCode = transformErrCode(*errCode); + LOGE("CreateDeviceManager for bundleName %{public}s failed, ret %{public}d.", bundleName_.c_str(), *errCode); + return; + } + { + std::lock_guard autoLock(g_initCallbackMapMutex); + g_initCallbackMap[bundleName_] = initCallback; + } + + std::lock_guard autoLock(g_deviceManagerMapMutex); + g_deviceManagerMap[bundleName_] = this; +} + +int32_t DeviceManagerFfiImpl::ReleaseDeviceManager() +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + int ret = DeviceManager::GetInstance().UnInitDeviceManager(bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("ReleaseDeviceManager for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + ClearBundleCallbacks(); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetAvailableDeviceList(FfiDeviceBasicInfoArray &deviceInfoList) +{ + int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + if (ret != 0) { + return transformErrCode(ret); + } + std::vector result; + ret = DeviceManager::GetInstance().GetAvailableDeviceList(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetTrustedDeviceList for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + + if (result.size() == 0) { + return ERR_OK; + } + + deviceInfoList.head = static_cast(malloc(sizeof(FfiDeviceBasicInfo) * result.size())); + if (deviceInfoList.head == nullptr) { + LOGE("Malloc failed"); + return DM_ERR_FAILED; + } + deviceInfoList.size = result.size(); + for (decltype(result.size()) i = 0; i < result.size(); ++i) { + ret = Transform2FfiDeviceBasicInfo(result[i], deviceInfoList.head[i]); + if (ret != 0) { + DeviceListFree(deviceInfoList, i); + return ret; + } + } + return ERR_OK; +} + +void DeviceManagerFfiImpl::DeviceListFree(FfiDeviceBasicInfoArray &deviceInfoList, int64_t size) +{ + if (size == -1) { + size = deviceInfoList.size; + } + for (int32_t i = 0; i < size; ++i) { + FreeDeviceInfo(deviceInfoList.head[i]); + } + free(deviceInfoList.head); + deviceInfoList.head = nullptr; + deviceInfoList.size = 0; +} + +int32_t DeviceManagerFfiImpl::Transform2FfiDeviceBasicInfo(const DmDeviceBasicInfo &in, FfiDeviceBasicInfo &out) +{ + out.deviceId = MallocCStr(in.deviceId); + out.deviceName = MallocCStr(in.deviceName); + out.deviceType = in.deviceTypeId; + out.networkId = MallocCStr(in.networkId); + if (out.deviceId == nullptr || out.deviceName == nullptr || out.networkId == nullptr) { + FreeDeviceInfo(out); + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceNetworkId(const char *&networkId) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + std::string result; + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceNetWorkId(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceNetworkId for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceNetworkId networkId:%{public}s", GetAnonyString(result).c_str()); + + networkId = MallocCStr(result.c_str()); + if (networkId == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceName(const char *&deviceName) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + std::string result; + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceName(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceName for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceName deviceName:%{public}s", GetAnonyString(result).c_str()); + + deviceName = MallocCStr(result.c_str()); + if (deviceName == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceType(int32_t &deviceType) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceType(bundleName_, deviceType); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceType for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceType deviceType:%{public}d", deviceType); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceId(const char *&deviceId) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + std::string result; + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceId(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceId for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceId deviceId:%{public}s", GetAnonyString(result).c_str()); + + deviceId = MallocCStr(result.c_str()); + if (deviceId == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetDeviceName(const std::string &networkId, const char *&deviceName) +{ + int32_t ret = stringCheck(networkId); + if (ret != 0) { + return ret; + } + std::string result; + ret = DeviceManager::GetInstance().GetDeviceName(bundleName_, networkId, result); + LOGI("DeviceManager::GetDeviceName getinstance return."); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetDeviceName for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetDeviceName deviceName:%{public}s", GetAnonyString(result).c_str()); + + deviceName = MallocCStr(result.c_str()); + if (deviceName == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetDeviceType(const std::string &networkId, int32_t &deviceType) +{ + int32_t ret = stringCheck(networkId); + if (ret != 0) { + return ret; + } + ret = DeviceManager::GetInstance().GetDeviceType(bundleName_, networkId, deviceType); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetDeviceType for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetDeviceType deviceType:%{public}d", deviceType); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::StartDiscovering(const std::string &extra) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + std::shared_ptr discoveryCallback = nullptr; + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + auto iter = g_DiscoveryCallbackMap.find(bundleName_); + if (iter == g_DiscoveryCallbackMap.end()) { + discoveryCallback = std::make_shared(bundleName_); + g_DiscoveryCallbackMap[bundleName_] = discoveryCallback; + } else { + discoveryCallback = iter->second; + } + } + uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID(); + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(bundleName_, tokenId, extra, discoveryCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("Discovery failed, bundleName %{public}s, ret %{public}d", bundleName_.c_str(), ret); + discoveryCallback->OnDiscoveryFailed(static_cast(0), ret); + return ret; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::StopDiscovering() +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID(); + int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(tokenId, bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("StopDeviceDiscovery for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::BindTarget(const std::string &deviceId, + const std::string &bindParam, const bool isMetaType) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + int32_t ret = stringCheck(deviceId); + if (ret != 0) { + return ret; + } + + callbackFinished = false; + if (isMetaType) { + std::shared_ptr bindTargetCallback = nullptr; + { + std::lock_guard autoLock(g_bindCallbackMapMutex); + auto iter = g_bindCallbackMap.find(bundleName_); + if (iter == g_bindCallbackMap.end()) { + bindTargetCallback = std::make_shared(bundleName_); + g_bindCallbackMap[bundleName_] = bindTargetCallback; + } else { + bindTargetCallback = iter->second; + } + } + int32_t ret = BindTargetWarpper(deviceId, bindParam, bindTargetCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("BindTarget for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return WaitForCallbackCv(); + } + + std::shared_ptr bindDeviceCallback = nullptr; + { + std::lock_guard autoLock(g_authCallbackMapMutex); + auto iter = g_authCallbackMap.find(bundleName_); + if (iter == g_authCallbackMap.end()) { + bindDeviceCallback = std::make_shared(bundleName_); + g_authCallbackMap[bundleName_] = bindDeviceCallback; + } else { + bindDeviceCallback = iter->second; + } + } + constexpr int32_t bindType = 1; + ret = DeviceManager::GetInstance().BindDevice(bundleName_, bindType, deviceId, bindParam, bindDeviceCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("BindDevice for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return WaitForCallbackCv(); +} + +int32_t DeviceManagerFfiImpl::WaitForCallbackCv() +{ + std::unique_lock autoLock(callbackFinishedMutex); + callbackFinishedCv.wait(autoLock, [this] { return this->callbackFinished; }); + LOGI("WaitForCallbackCv got notified, errCode is %{public}d", errCode_.load()); + return errCode_.load(); +} + +int32_t DeviceManagerFfiImpl::UnbindTarget(const std::string &deviceId) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + int32_t ret = stringCheck(deviceId); + if (ret != 0) { + return ret; + } + LOGI("UnBindDevice deviceId = %{public}s", GetAnonyString(deviceId).c_str()); + ret = DeviceManager::GetInstance().UnBindDevice(bundleName_, deviceId); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("UnBindDevice for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::EventOn(const std::string &type, void *callback) +{ + int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + if (ret != 0) { + return transformErrCode(ret); + } + + LOGI("EventOn for bundleName %{public}s, eventType %{public}s ", bundleName_.c_str(), type.c_str()); + RegisterCallbackByType(type, callback); + + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE || type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + return RegisterDevStatusCallback(); + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS || type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + return RegisterDiscoveryCallback(); + } + + return ERR_INVALID_PARAMS; +} + +int32_t DeviceManagerFfiImpl::EventOff(const std::string &type) +{ + int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + if (ret != 0) { + return ret; + } + + LOGI("EventOff for bundleName %{public}s, eventType %{public}s ", bundleName_.c_str(), type.c_str()); + Off(type); + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE || type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + if (!deviceStateChangedCallback && !deviceNameChangedCallback) { + return ReleaseDevStatusCallback(); + } + return ERR_OK; + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS || type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + return ReleaseDiscoveryCallback(); + } + return ERR_INVALID_PARAMS; +} + + +void DeviceManagerFfiImpl::OnDeviceStatusChange(int32_t action, const DmDeviceBasicInfo &deviceBasicInfo) +{ + std::lock_guard autoLock(callbackLock); + if (deviceStateChangedCallback) { + auto ptr = static_cast(malloc(sizeof(FfiDeviceBasicInfo))); + if (ptr == nullptr) { + LOGE("OnDeviceStatusChange malloc FfiDeviceBasicInfo failed."); + return; + } + int32_t ret = Transform2FfiDeviceBasicInfo(deviceBasicInfo, *ptr); + if (ret != 0) { + LOGE("OnDeviceStatusChange failed to transform DmDeviceBasicInfo."); + return; + } + deviceStateChangedCallback(action, ptr); + FreeDeviceInfo(*ptr); + free(ptr); + } +} + +void DeviceManagerFfiImpl::OnDeviceNameChange(const std::string &deviceName) +{ + std::lock_guard autoLock(callbackLock); + if (deviceNameChangedCallback) { + char *cDeviceName = MallocCStr(deviceName.c_str()); + if (cDeviceName == nullptr) { + LOGE("OnDeviceNameChange malloc deviname failed."); + return; + } + deviceNameChangedCallback(cDeviceName); + free(cDeviceName); + } +} + +void DeviceManagerFfiImpl::OnDeviceFound(uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo) +{ + std::lock_guard autoLock(callbackLock); + if (discoverSuccessCallback) { + auto ptr = static_cast(malloc(sizeof(FfiDeviceBasicInfo))); + if (ptr == nullptr) { + LOGE("OnDeviceStatusChange malloc FfiDeviceBasicInfo failed."); + return; + } + int32_t ret = Transform2FfiDeviceBasicInfo(deviceBasicInfo, *ptr); + if (ret != 0) { + LOGE("OnDeviceStatusChange failed to transform DmDeviceBasicInfo."); + return; + } + discoverSuccessCallback(ptr); + FreeDeviceInfo(*ptr); + free(ptr); + } +} + +void DeviceManagerFfiImpl::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) +{ + std::lock_guard autoLock(callbackLock); + LOGI("OnDiscoveryFailed for subscribeId %{public}d", (int32_t)subscribeId); + if (deviceDiscoverFailedCallback) { + deviceDiscoverFailedCallback(failedReason); + } +} + +void DeviceManagerFfiImpl::OnPublishResult(int32_t publishId, int32_t publishResult) +{ + LOGI("OnPublishResult for publishId %{public}d, publishResult %{public}d", publishId, publishResult); +} + +void DeviceManagerFfiImpl::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) +{ + LOGI("OnAuthResult for status: %{public}d, reason: %{public}d", status, reason); + if (reason == DM_OK && (status <= STATUS_DM_CLOSE_PIN_INPUT_UI && status >= STATUS_DM_SHOW_AUTHORIZE_UI)) { + LOGI("update ui change, status: %{public}d, reason: %{public}d", status, reason); + return; + } + + if (status == DM_AUTH_REQUEST_SUCCESS_STATUS && reason == 0) { + LOGI("OnAuthResult success"); + errCode_ = ERR_OK; + } else { + LOGI("OnAuthResult failed"); + errCode_ = reason; + } + + std::lock_guard autoLock(g_authCallbackMapMutex); + g_authCallbackMap.erase(bundleName_); + callbackFinished = true; + callbackFinishedCv.notify_one(); +} + +void DeviceManagerFfiImpl::OnDmUiCall(const std::string ¶mJson) +{ + LOGI("OnCall for paramJson"); +} + +DeviceManagerFfiImpl *DeviceManagerFfiImpl::GetDeviceManagerFfi(std::string &bundleName) +{ + std::lock_guard autoLock(g_deviceManagerMapMutex); + auto iter = g_deviceManagerMap.find(bundleName); + if (iter == g_deviceManagerMap.end()) { + return nullptr; + } + return iter->second; +} + +void DeviceManagerFfiImpl::ClearBundleCallbacks() +{ + LOGI("ClearBundleCallbacks start for bundleName %{public}s", bundleName_.c_str()); + { + std::lock_guard autoLock(g_deviceManagerMapMutex); + g_deviceManagerMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_initCallbackMapMutex); + g_initCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + g_deviceStatusCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + g_DiscoveryCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_publishCallbackMapMutex); + g_publishCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_authCallbackMapMutex); + g_authCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_bindCallbackMapMutex); + g_bindCallbackMap.erase(bundleName_); + } + return; +} + +int32_t DeviceManagerFfiImpl::BindTargetWarpper(const std::string &deviceId, + const std::string &bindParam, std::shared_ptr callback) +{ + if (bindParam.empty()) { + return ERR_INVALID_PARAMS; + } + nlohmann::json bindParamObj = nlohmann::json::parse(bindParam, nullptr, false); + if (bindParamObj.is_discarded()) { + return ERR_INVALID_PARAMS; + } + PeerTargetId targetId; + targetId.deviceId = deviceId; + if (IsString(bindParamObj, PARAM_KEY_BR_MAC)) { + targetId.brMac = bindParamObj[PARAM_KEY_BR_MAC].get(); + } + if (IsString(bindParamObj, PARAM_KEY_BLE_MAC)) { + targetId.bleMac = bindParamObj[PARAM_KEY_BLE_MAC].get(); + } + if (IsString(bindParamObj, PARAM_KEY_WIFI_IP)) { + targetId.wifiIp = bindParamObj[PARAM_KEY_WIFI_IP].get(); + } + if (IsInt32(bindParamObj, PARAM_KEY_WIFI_PORT)) { + targetId.wifiPort = (uint16_t)(bindParamObj[PARAM_KEY_WIFI_PORT].get()); + } + + std::map bindParamMap; + InsertJsonParamesToMap(bindParamObj, bindParamMap); + return DeviceManager::GetInstance().BindTarget(bundleName_, targetId, bindParamMap, callback); +} + + +int32_t DeviceManagerFfiImpl::RegisterDevStatusCallback() +{ + LOGI("RegisterDevStatusCallback start for bundleName %{public}s", bundleName_.c_str()); + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + if (g_deviceStatusCallbackMap.find(bundleName_) != g_deviceStatusCallbackMap.end()) { + LOGI("bundleName already register."); + return ERR_OK; + } + } + auto callback = std::make_shared(bundleName_); + int32_t ret = DeviceManager::GetInstance().RegisterDevStatusCallback(bundleName_, "", callback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("RegisterDevStatusCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + g_deviceStatusCallbackMap[bundleName_] = callback; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::RegisterDiscoveryCallback() +{ + auto discoveryCallback = std::make_shared(bundleName_); + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + g_DiscoveryCallbackMap[bundleName_] = discoveryCallback; + } + discoveryCallback->IncreaseRefCount(); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::RegisterPublishCallback() +{ + auto publishCallback = std::make_shared(bundleName_); + { + std::lock_guard autoLock(g_publishCallbackMapMutex); + g_publishCallbackMap[bundleName_] = publishCallback; + } + publishCallback->IncreaseRefCount(); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::RegisterReplyCallback() +{ + auto dmUiCallback = std::make_shared(bundleName_); + int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName_, dmUiCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("RegisterDeviceManagerFaCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_dmUiCallbackMapMutex); + g_dmUiCallbackMap[bundleName_] = dmUiCallback; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleaseDevStatusCallback() +{ + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + auto iter = g_deviceStatusCallbackMap.find(bundleName_); + if (iter == g_deviceStatusCallbackMap.end()) { + LOGE("ReleaseDmCallback: cannot find statusCallback for bundleName %{public}s", bundleName_.c_str()); + return ERR_INVALID_PARAMS; + } + } + int32_t ret = DeviceManager::GetInstance().UnRegisterDevStatusCallback(bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("UnRegisterDevStatusCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + g_deviceStatusCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleaseDiscoveryCallback() +{ + LOGI("ReleaseDiscoveryCallback for bundleName %{public}s", bundleName_.c_str()); + std::shared_ptr DiscoveryCallback = nullptr; + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + auto iter = g_DiscoveryCallbackMap.find(bundleName_); + if (iter == g_DiscoveryCallbackMap.end()) { + return ERR_OK; + } + DiscoveryCallback = iter->second; + } + DiscoveryCallback->DecreaseRefCount(); + if (DiscoveryCallback->GetRefCount() == 0) { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + g_DiscoveryCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleasePublishCallback() +{ + LOGI("ReleasePublishCallback for bundleName %{public}s", bundleName_.c_str()); + std::shared_ptr publishCallback = nullptr; + { + std::lock_guard autoLock(g_publishCallbackMapMutex); + auto iter = g_publishCallbackMap.find(bundleName_); + if (iter == g_publishCallbackMap.end()) { + return ERR_OK; + } + publishCallback = iter->second; + } + publishCallback->DecreaseRefCount(); + if (publishCallback->GetRefCount() == 0) { + std::lock_guard autoLock(g_publishCallbackMapMutex); + g_publishCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleaseReplyCallback() +{ + { + std::lock_guard autoLock(g_dmUiCallbackMapMutex); + auto iter = g_dmUiCallbackMap.find(bundleName_); + if (iter == g_dmUiCallbackMap.end()) { + LOGE("cannot find dmFaCallback for bundleName %{public}s", bundleName_.c_str()); + return ERR_INVALID_PARAMS; + } + } + int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("UnRegisterDeviceManagerFaCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_dmUiCallbackMapMutex); + g_dmUiCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + + +void DeviceManagerFfiImpl::RegisterCallbackByType(const std::string &type, void *callback) +{ + std::lock_guard autoLock(callbackLock); + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE) { + deviceStateChangedCallback = CJLambda::Create( + reinterpret_cast(callback)); + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS) { + discoverSuccessCallback = CJLambda::Create(reinterpret_cast(callback)); + } else if (type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + deviceNameChangedCallback = CJLambda::Create(reinterpret_cast(callback)); + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + deviceDiscoverFailedCallback = CJLambda::Create(reinterpret_cast(callback)); + } else { + LOGE("RegisterCallbackByType call with wrong type."); + } +} + +void DeviceManagerFfiImpl::Off(const std::string &type) +{ + std::lock_guard autoLock(callbackLock); + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE) { + deviceStateChangedCallback = nullptr; + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS) { + discoverSuccessCallback = nullptr; + } else if (type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + deviceNameChangedCallback = nullptr; + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + deviceDiscoverFailedCallback = nullptr; + } else { + LOGE("Off call with wrong type."); + } +} +} // namespace OHOS::DistributedHardware diff --git a/interfaces/cj/src/device_manager_utils.cpp b/interfaces/cj/src/device_manager_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86010e9548b811be1182b5300edb183ff37cc199 --- /dev/null +++ b/interfaces/cj/src/device_manager_utils.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_utils.h" + +#include +#include +#include + +#include "device_manager_impl.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS::DistributedHardware { + +namespace { + constexpr std::size_t MAX_MALLOC_SIZE = 0x10000; +} + +void DmFfiInitCallback::OnRemoteDied() +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnRemoteDied, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } + LOGI("OnRemoteDied, deviceManagerFfi bundleName %{public}s", bundleName_.c_str()); +} + +void DmFfiDeviceStatusCallback::OnDeviceOnline(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceOnline, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceStatusChange(DmFfiDevStatusChange::UNKNOWN, deviceBasicInfo); + } +} + +void DmFfiDeviceStatusCallback::OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceReady, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceStatusChange(DmFfiDevStatusChange::AVAILABLE, deviceBasicInfo); + } +} + +void DmFfiDeviceStatusCallback::OnDeviceOffline(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceOffline, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceStatusChange(DmFfiDevStatusChange::UNAVAILABLE, deviceBasicInfo); + } +} + +void DmFfiDeviceStatusCallback::OnDeviceChanged(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceChanged, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceNameChange(deviceBasicInfo.deviceName); + } +} + +void DmFfiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("OnDeviceFound for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceFound, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceFound(subscribeId, deviceBasicInfo); + } +} + +void DmFfiDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) +{ + LOGI("OnDiscoveryFailed for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDiscoveryFailed, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDiscoveryFailed(subscribeId, failedReason); + } +} + +void DmFfiDiscoveryCallback::OnDiscoverySuccess(uint16_t subscribeId) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDiscoverySuccess, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + return; + } + LOGI("DiscoverySuccess for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); +} + +void DmFfiDiscoveryCallback::IncreaseRefCount() +{ + refCount_++; +} + +void DmFfiDiscoveryCallback::DecreaseRefCount() +{ + refCount_--; +} + +int32_t DmFfiDiscoveryCallback::GetRefCount() +{ + return refCount_; +} + +void DmFfiPublishCallback::OnPublishResult(int32_t publishId, int32_t publishResult) +{ + LOGI("OnPublishResult for %{public}s, publishId %{public}d, publishResult %{public}d", bundleName_.c_str(), + publishId, publishResult); + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnPublishResult, deviceManagerFfi failed for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnPublishResult(publishId, publishResult); + } +} + +void DmFfiPublishCallback::IncreaseRefCount() +{ + refCount_++; +} + +void DmFfiPublishCallback::DecreaseRefCount() +{ + refCount_--; +} + +int32_t DmFfiPublishCallback::GetRefCount() +{ + return refCount_; +} + +void DmFfiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnAuthResult, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnAuthResult(deviceId, token, status, reason); + } +} + +void DmFfiDeviceManagerUiCallback::OnCall(const std::string ¶mJson) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnCall, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDmUiCall(paramJson); + } +} + +void DmFfiBindTargetCallback::OnBindResult(const PeerTargetId &targetId, int32_t result, int32_t status, + std::string content) +{ + (void)targetId; + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnBindResult, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnAuthResult(content, "", status, result); + } +} + +const std::string &GetDeviceTypeById(DmDeviceType type) +{ + const static std::pair mapArray[] = { + {DEVICE_TYPE_UNKNOWN, DEVICE_TYPE_UNKNOWN_STRING}, + {DEVICE_TYPE_PHONE, DEVICE_TYPE_PHONE_STRING}, + {DEVICE_TYPE_PAD, DEVICE_TYPE_PAD_STRING}, + {DEVICE_TYPE_TV, DEVICE_TYPE_TV_STRING}, + {DEVICE_TYPE_CAR, DEVICE_TYPE_CAR_STRING}, + {DEVICE_TYPE_WATCH, DEVICE_TYPE_WATCH_STRING}, + {DEVICE_TYPE_WIFI_CAMERA, DEVICE_TYPE_WIFICAMERA_STRING}, + {DEVICE_TYPE_PC, DEVICE_TYPE_PC_STRING}, + {DEVICE_TYPE_SMART_DISPLAY, DEVICE_TYPE_SMART_DISPLAY_STRING}, + {DEVICE_TYPE_2IN1, DEVICE_TYPE_2IN1_STRING}, + }; + for (const auto& item : mapArray) { + if (item.first == type) { + return item.second; + } + } + return DEVICE_TYPE_UNKNOWN_STRING; +} + +char *MallocCStr(const char *in) +{ + std::size_t len = strlen(in); + if (len >= MAX_MALLOC_SIZE) { + return nullptr; + } + char *result = static_cast(malloc(len + 1)); + if (result == nullptr) { + LOGE("Malloc failed."); + return nullptr; + } + std::char_traits::copy(result, in, len+1); + return result; +} +} // OHOS::DistributedHardware diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index a28a5704383b4e7f387cc93feea27b6d0c9d3029..3343bcbae0ee44c51ebecf302e9a0db0f34f2308 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -76,6 +76,7 @@ if (defined(ohos_lite)) { "${common_path}/include/ipc", "${common_path}/include/ipc/lite", "${common_path}/include/ipc/model", + "${devicemanager_path}/radar/include", "${interfaces_path}/c/ipc/include", "${interfaces_path}/ipc_core/include", "${samgr_lite_path}/kits/samgr", @@ -107,7 +108,7 @@ if (defined(ohos_lite)) { "LITE_DEVICE", "HI_LOG_ENABLE", "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004111", ] deps = [ @@ -136,6 +137,7 @@ if (defined(ohos_lite)) { "${common_path}/include/ipc/standard", "${common_path}/include/dfx", "${common_path}/include/dfx/standard", + "${devicemanager_path}/radar/include", ] } @@ -153,9 +155,11 @@ if (defined(ohos_lite)) { "${common_path}/src/dfx/standard/dm_hitrace.cpp", "${common_path}/src/dm_anonymous.cpp", "${common_path}/src/ipc/standard/ipc_cmd_register.cpp", + "${devicemanager_path}/radar/src/dm_radar_helper.cpp", "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", + "src/ipc/standard/dm_service_load.cpp", "src/ipc/standard/ipc_client_manager.cpp", "src/ipc/standard/ipc_client_server_proxy.cpp", "src/ipc/standard/ipc_client_stub.cpp", @@ -170,20 +174,24 @@ if (defined(ohos_lite)) { defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004111", ] external_deps = [ "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "cJSON:cjson", "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", + "init:libbegetutil", "ipc:ipc_core", "ipc:ipc_napi", "ipc:ipc_single", "ipc:libdbinder", + "openssl:libcrypto_shared", "samgr:samgr_proxy", ] diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index caba88092189faaaf98889fd3718a256f32865eb..d9abc735104daff6b9afb11265bfab7d3f80b8b3 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -606,6 +606,31 @@ public: virtual bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; virtual int32_t GetErrCode(int32_t errCode) = 0; virtual int32_t ShiftLNNGear(const std::string &pkgName) = 0; + virtual int32_t RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) = 0; + virtual int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) = 0; + + /** + * @brief Set Dn Policy + * @param pkgName package name. + * @param policy contain DM_POLICY_STRATEGY_FOR_BLE and DM_POLICY_TIMEOUT key and value. + * DM_POLICY_STRATEGY_FOR_BLE: Strategy BLE networking go-online policy, suppress or restore. + * DM_POLICY_TIMEOUT: Indicates the duration for suppressing ble networking. + * @return Returns 0 if success. + */ + virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; + virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) = 0; + virtual int32_t RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) = 0; + virtual int32_t RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterSinkBindCallback(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index b33857718d41055b7d1339398e69755df96eba7f..61989ccf34bfc9b969a1f17b7b2a52c16477d245 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -132,6 +132,30 @@ public: virtual void OnDestroyResult(int32_t result) = 0; virtual void OnPinHolderEvent(DmPinHolderEvent event, int32_t result, const std::string &content) = 0; }; + +class DevTrustChangeCallback { +public: + virtual ~DevTrustChangeCallback() + { + } + virtual void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) = 0; +}; + +class DeviceScreenStatusCallback { +public: + virtual ~DeviceScreenStatusCallback() + { + } + virtual void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) = 0; +}; + +class CredentialAuthStatusCallback { +public: + virtual ~CredentialAuthStatusCallback() + { + } + virtual void OnCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_CALLBACK_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 5505d0de37c4f4edac2d98a60014be9a47c7967b..cf09515130bdf0ff34450eef5c437eb45e408dc3 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -23,6 +23,7 @@ #endif #include #include +#include namespace OHOS { namespace DistributedHardware { @@ -385,6 +386,25 @@ public: virtual bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) override; virtual int32_t GetErrCode(int32_t errCode) override; virtual int32_t ShiftLNNGear(const std::string &pkgName) override; + virtual int32_t RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) override; + + virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) override; + virtual int32_t RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) override; + virtual int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) override; + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) override; + virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, + std::string &networkId) override; + virtual int32_t RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) override; + virtual int32_t RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterSinkBindCallback(const std::string &pkgName) override; + void SyncCallbacksToService(std::map> &callbackMap); private: DeviceManagerImpl() = default; @@ -394,21 +414,21 @@ private: DeviceManagerImpl(DeviceManagerImpl &&) = delete; DeviceManagerImpl &operator=(DeviceManagerImpl &&) = delete; - uint16_t AddDiscoveryCallback(const std::string &pkgName, std::shared_ptr callback); + uint16_t AddDiscoveryCallback(const std::string &pkgName, std::map &discoverParam, + std::shared_ptr callback); uint16_t RemoveDiscoveryCallback(const std::string &pkgName); int32_t AddPublishCallback(const std::string &pkgName); int32_t RemovePublishCallback(const std::string &pkgName); int32_t CheckApiPermission(int32_t permissionLevel); void ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); + uint16_t GetSubscribeIdFromMap(const std::string &pkgName); + void SyncCallbackToService(DmCommonNotifyEvent dmCommonNotifyEvent, const std::string &pkgName); private: #if !defined(__LITEOS_M__) std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); #endif - std::mutex subscribIdLock; - std::map subscribIdMap_; - std::mutex subMapLock; std::map pkgName2SubIdMap_; diff --git a/interfaces/inner_kits/native_cpp/include/dm_device_info.h b/interfaces/inner_kits/native_cpp/include/dm_device_info.h index 4354ee3ead61a00f6559916ca40b86b3ad208853..00d087fcbd26773ccd73e26acac0b5785ad89e6a 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -334,6 +334,19 @@ typedef enum { STATUS_DM_CLOSE_PIN_INPUT_UI = 13, } DmAuthStatus; +typedef enum { + MIN = 0, + REG_DEVICE_STATE = 1, + UN_REG_DEVICE_STATE = 2, + REG_DEVICE_SCREEN_STATE = 3, + UN_REG_DEVICE_SCREEN_STATE = 4, + REG_REMOTE_DEVICE_TRUST_CHANGE = 5, + UN_REG_REMOTE_DEVICE_TRUST_CHANGE = 6, + REG_CREDENTIAL_AUTH_STATUS_NOTIFY = 7, + UN_REG_CREDENTIAL_AUTH_STATUS_NOTIFY = 8, + MAX = 9, +} DmCommonNotifyEvent; + const std::string DEVICE_TYPE_UNKNOWN_STRING = "UNKNOWN"; const std::string DEVICE_TYPE_PHONE_STRING = "PHONE"; const std::string DEVICE_TYPE_PAD_STRING = "PAD"; @@ -361,6 +374,45 @@ typedef struct DmAccessCallee { int32_t userId; std::string extra; } DmAccessCallee; + +typedef struct ProcessInfo { + int32_t userId; + std::string pkgName; + + bool operator==(const ProcessInfo &other) const + { + return (userId == other.userId) && (pkgName == other.pkgName); + } + + bool operator<(const ProcessInfo &other) const + { + return (userId < other.userId) || + (userId == other.userId && pkgName < other.pkgName); + } +} ProcessInfo; + +typedef struct DmNotifyKey { + int32_t processUserId; + std::string processPkgName; + int32_t notifyUserId; + std::string udid; + + bool operator==(const DmNotifyKey &other) const + { + return (processUserId == other.processUserId) && (processPkgName == other.processPkgName) && + (notifyUserId == other.notifyUserId) && (udid == other.udid); + } + + bool operator<(const DmNotifyKey &other) const + { + return (processUserId < other.processUserId) || + (processUserId == other.processUserId && processPkgName < other.processPkgName) || + (processUserId == other.processUserId && processPkgName == other.processPkgName && + notifyUserId < other.notifyUserId) || + (processUserId == other.processUserId && processPkgName == other.processPkgName && + notifyUserId == other.notifyUserId && udid < other.udid); + } +} DmNotifyKey; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_DEVICE_INFO_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h b/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h index 83208d95ee7237393e528894867924a3f9f0f9f9..d39b30365aeeea6226c2d6add0cc8598b02e0975 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h @@ -81,6 +81,10 @@ typedef enum DmExchangeFreq { * Super-high */ DM_SUPER_HIGH = 3, + /** + * Extreme-high + */ + DM_EXTREME_HIGH = 4, DM_FREQ_BUTT } DmExchangeFreq; diff --git a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h index 6d84dda2e5aa572b66613b95082dc6d85eef519e..690650918386edc36efbf5a7f1abe0effb8e2e69 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h @@ -20,11 +20,11 @@ #include #include "ipc_client.h" -namespace OHOS::DistributedHardware { class IpcReq; } -namespace OHOS::DistributedHardware { class IpcRsp; } namespace OHOS { namespace DistributedHardware { +class IpcReq; +class IpcRsp; class IpcClientProxy : public IpcClient { DECLARE_IPC_INTERFACE(IpcClientProxy); diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/dm_service_load.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/dm_service_load.h new file mode 100644 index 0000000000000000000000000000000000000000..beb819b5f8b476052563ece14ff5453c8c02e95e --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/dm_service_load.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_SA_LOAD_H +#define OHOS_DM_SA_LOAD_H + +#include "dm_single_instance.h" +#include "iremote_object.h" +#include "system_ability_load_callback_stub.h" + +namespace OHOS { +namespace DistributedHardware { +class DMLoadCallback : public SystemAbilityLoadCallbackStub { +public: + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr &remoteObject) override; + void OnLoadSystemAbilityFail(int32_t systemAbilityId) override; +}; + +class DmServiceLoad { + DM_DECLARE_SINGLE_INSTANCE(DmServiceLoad); +public: + int32_t LoadDMService(void); + void SetLoadFinish(void); +private: + std::atomic isDMServiceLoading_ = false; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SA_LOAD_H diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 5e3442fe7d20f9221d1e330d6e8d31bcb6ee3a82..cf7be62ad40f1f50242fec1c1baecf8f62c573cc 100644 --- a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h +++ b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -66,6 +67,15 @@ public: std::string content); void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, std::string content); void RegisterPinHolderCallback(const std::string &pkgName, std::shared_ptr callback); + void RegDevTrustChangeCallback(const std::string &pkgName, std::shared_ptr callback); + void RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback); + void UnRegisterDeviceScreenStatusCallback(const std::string &pkgName); + void RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback); + void UnRegisterCredentialAuthStatusCallback(const std::string &pkgName); + void RegisterSinkBindCallback(const std::string &pkgName, std::shared_ptr callback); + void UnRegisterSinkBindCallback(const std::string &pkgName); public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -80,6 +90,8 @@ public: std::shared_ptr tempCbk); static void DeviceBasicInfoReady(const DmDeviceBasicInfo &deviceBasicInfo, std::shared_ptr tempCbk); + static void DeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm, + std::shared_ptr tempCbk); public: void OnRemoteDied(); void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); @@ -107,6 +119,16 @@ public: void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content); std::map> GetDmInitCallback(); + void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, + int32_t authForm); + void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, + uint16_t deviceTypeId, int32_t errcode); + void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, + std::string content); + std::shared_ptr GetDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId); + void GetCallBack(std::map> &callbackMap); + private: #if !defined(__LITEOS_M__) std::mutex lock_; @@ -122,12 +144,11 @@ private: std::map>> bindCallback_; std::map>> unbindCallback_; std::map> pinHolderCallback_; + std::map> devTrustChangeCallback_; + std::map> deviceScreenStatusCallback_; + std::map> credentialAuthStatusCallback_; + std::map> sinkBindTargetCallback_; std::mutex bindLock_; - std::condition_variable cv_; - bool binding_ = false; -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - std::shared_ptr ffrtQueue_; -#endif }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 4227178947c7bec07567fab7e8364964c8cf30ce..a799d988f43cbb2c2afdab60ff5f69d2140d035c 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -25,6 +25,7 @@ #include "dm_hisysevent.h" #include "dm_hitrace.h" #include "dm_log.h" +#include "dm_radar_helper.h" #include "ipc_acl_profile_req.h" #include "ipc_authenticate_device_req.h" #include "ipc_bind_device_req.h" @@ -36,6 +37,8 @@ #include "ipc_export_auth_code_rsp.h" #include "ipc_generate_encrypted_uuid_req.h" #include "ipc_get_device_info_rsp.h" +#include "ipc_get_device_screen_status_req.h" +#include "ipc_get_device_screen_status_rsp.h" #include "ipc_get_encrypted_uuid_req.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_info_by_network_rsp.h" @@ -51,9 +54,8 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" +#include "ipc_skeleton.h" +#include "ipc_sync_callback_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_unbind_device_req.h" #include "ipc_unpublish_req.h" @@ -64,7 +66,6 @@ #endif namespace OHOS { namespace DistributedHardware { -const int32_t SLEEP_TIME_MS = 50000; // 50ms constexpr const char* DM_INIT_DEVICE_MANAGER_SUCCESS = "DM_INIT_DEVICE_MANAGER_SUCCESS"; constexpr const char* DM_INIT_DEVICE_MANAGER_FAILED = "DM_INIT_DEVICE_MANAGER_FAILED"; @@ -98,7 +99,7 @@ const uint16_t DM_IMPORT_AUTH_CODE_LENGTH = 6; const int32_t NORMAL = 0; const int32_t SYSTEM_BASIC = 1; const int32_t SYSTEM_CORE = 2; -const int32_t USLEEP_TIME_MS = 100000; // 100ms +const int32_t USLEEP_TIME_US_100000 = 100000; // 100ms uint16_t GenRandUint(uint16_t randMin, uint16_t randMax) { std::random_device randDevice; @@ -116,26 +117,29 @@ DeviceManagerImpl &DeviceManagerImpl::GetInstance() int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) { if (pkgName.empty() || dmInitCallback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "InitDeviceManager", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::InitDeviceManager error: Invalid parameter, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } DmTraceStart(std::string(DM_HITRACE_INIT)); - LOGI("InitDeviceManager start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); int32_t ret = DM_OK; int32_t retryNum = 0; while (retryNum < SERVICE_INIT_TRY_MAX_NUM) { ret = ipcClientProxy_->Init(pkgName); - if (ret != ERR_DM_NOT_INIT) { + if (ret == DM_OK) { break; } - usleep(SLEEP_TIME_MS); + usleep(USLEEP_TIME_US_100000); retryNum++; if (retryNum == SERVICE_INIT_TRY_MAX_NUM) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "InitDeviceManager", ERR_DM_NOT_INIT); LOGE("InitDeviceManager error, wait for device manager service starting timeout."); return ERR_DM_NOT_INIT; } } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "InitDeviceManager", ret); if (ret != DM_OK) { LOGE("InitDeviceManager error, proxy init failed ret: %{public}d", ret); SysEventWrite(std::string(DM_INIT_DEVICE_MANAGER_FAILED), DM_HISYEVENT_FAULT, @@ -145,7 +149,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); DmTraceEnd(); - LOGI("InitDeviceManager success"); + LOGI("Success"); SysEventWrite(std::string(DM_INIT_DEVICE_MANAGER_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(DM_INIT_DEVICE_MANAGER_SUCCESS_MSG)); return DM_OK; @@ -154,38 +158,50 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnInitDeviceManager", ERR_DM_INPUT_PARA_INVALID); LOGE("UnInitDeviceManager Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnInitDeviceManager start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); int32_t ret = ipcClientProxy_->UnInit(pkgName); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnInitDeviceManager", ret); if (ret != DM_OK) { LOGE("UnInitDeviceManager error, proxy unInit failed ret: %{public}d", ret); return ERR_DM_FAILED; } DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); - LOGI("UnInitDeviceManager success"); + LOGI("Success"); return DM_OK; } void DeviceManagerImpl::ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { - (void)memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != DM_OK) { + LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed."); + return; + } + if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + return; } + if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + return; } + if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); + return; } + deviceBasicInfo.deviceTypeId = info.deviceTypeId; } @@ -193,10 +209,12 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons std::vector &deviceList) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList( + pkgName, "GetTrustedDeviceList", deviceList, ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetTrustedDeviceList start, pkgName: %{public}s, extra: %{public}s", pkgName.c_str(), extra.c_str()); + LOGD("Start, pkgName: %{public}s, extra: %{public}s", GetAnonyString(pkgName).c_str(), extra.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -204,19 +222,21 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons req->SetExtra(extra); int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGE("DeviceManagerImpl::GetTrustedDeviceList error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGI("GetTrustedDeviceList error, failed ret: %{public}d", ret); return ret; } deviceList = rsp->GetDeviceVec(); - LOGI("DeviceManagerImpl::GetTrustedDeviceList completed, pkgName: %{public}s, device size %{public}zu", - pkgName.c_str(), deviceList.size()); + LOGI("Completed, device size %{public}zu", deviceList.size()); + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, DM_OK); return DM_OK; } @@ -224,11 +244,13 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons bool isRefresh, std::vector &deviceList) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList( + pkgName, "GetTrustedDeviceList", deviceList, ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetTrustedDeviceList start, pkgName: %{public}s, extra: %{public}s, isRefresh: %{public}d", pkgName.c_str(), - extra.c_str(), isRefresh); + LOGD("Start, pkgName: %{public}s, extra: %{public}s, isRefresh: %{public}d", GetAnonyString(pkgName).c_str(), + extra.c_str(), isRefresh); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -237,28 +259,31 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons req->SetRefresh(isRefresh); int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGE("DeviceManagerImpl::GetTrustedDeviceList error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGE("GetTrustedDeviceList error, failed ret: %{public}d", ret); return ret; } deviceList = rsp->GetDeviceVec(); - LOGI("DeviceManagerImpl::GetTrustedDeviceList completed, pkgName: %{public}s, device size %{public}zu", - pkgName.c_str(), deviceList.size()); + LOGI("Completed, device size %{public}zu", deviceList.size()); + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, DM_OK); return DM_OK; } int32_t DeviceManagerImpl::GetAvailableDeviceList(const std::string &pkgName, std::vector &deviceList) { - LOGI("GetAvailableDeviceList start, pkgName: %{public}s.", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s.", GetAnonyString(pkgName).c_str()); std::vector deviceListTemp; std::string extra = ""; int32_t ret = GetTrustedDeviceList(pkgName, extra, false, deviceListTemp); + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceListTemp, ret); if (ret != DM_OK) { LOGE("DeviceManagerImpl::GetTrustedDeviceList error."); return ret; @@ -268,8 +293,7 @@ int32_t DeviceManagerImpl::GetAvailableDeviceList(const std::string &pkgName, ConvertDeviceInfoToDeviceBasicInfo(item, deviceBasicInfo); deviceList.push_back(deviceBasicInfo); } - LOGI("DeviceManagerImpl::GetAvailableDeviceList completed, pkgName: %{public}s, device size %{public}zu", - pkgName.c_str(), deviceList.size()); + LOGI("Completed, device size %{public}zu", deviceList.size()); return DM_OK; } @@ -277,11 +301,13 @@ int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, const std:: DmDeviceInfo &deviceInfo) { if (pkgName.empty() || networkId.empty()) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo( + pkgName, "GetDeviceInfo", deviceInfo, ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::GetDeviceInfo start, pkgName: %{public}s networKId : %{public}s", pkgName.c_str(), + LOGI("Start, pkgName: %{public}s networKId : %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -289,39 +315,42 @@ int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, const std:: req->SetNetWorkId(networkId); int32_t ret = ipcClientProxy_->SendRequest(GET_DEVICE_INFO, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceInfo", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceInfo error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceInfo", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceInfo error, failed ret: %{public}d", ret); return ret; } deviceInfo = rsp->GetDeviceInfo(); - LOGI("DeviceManagerImpl::GetDeviceInfo completed, pkgname = %{public}s networKId = %{public}s deviceName" - " = %{public}s", - req->GetPkgName().c_str(), GetAnonyString(req->GetNetWorkId()).c_str(), + LOGI("Completed, networKId = %{public}s deviceName = %{public}s", GetAnonyString(req->GetNetWorkId()).c_str(), GetAnonyString(deviceInfo.deviceName).c_str()); + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceInfo", deviceInfo, DM_OK); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) { - LOGI("DeviceManagerImpl::GetLocalDeviceInfo start, pkgName: %{public}s", pkgName.c_str()); + LOGD("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); DmTraceStart(std::string(DM_HITRACE_GET_LOCAL_DEVICE_INFO)); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); int32_t ret = ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceInfo", info, ret); LOGE("DeviceManagerImpl::GetLocalDeviceInfo error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceInfo", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceInfo error, failed ret: %{public}d", ret); SysEventWrite(std::string(GET_LOCAL_DEVICE_INFO_FAILED), DM_HISYEVENT_BEHAVIOR, std::string(GET_LOCAL_DEVICE_INFO_FAILED_MSG)); @@ -330,9 +359,10 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDevi info = rsp->GetLocalDeviceInfo(); DmTraceEnd(); - LOGI("DeviceManagerImpl::GetLocalDeviceInfo completed, pkgname = %{public}s", req->GetPkgName().c_str()); + LOGI("Completed"); SysEventWrite(std::string(GET_LOCAL_DEVICE_INFO_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(GET_LOCAL_DEVICE_INFO_SUCCESS_MSG)); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceInfo", info, DM_OK); return DM_OK; } @@ -340,28 +370,33 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterDevStateCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::RegisterDevStateCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ERR_DM_INIT_FAILED); LOGE("Get SystemAbilityManager Failed"); return ERR_DM_INIT_FAILED; } while (samgr->CheckSystemAbility(ACCESS_TOKEN_MANAGER_SERVICE_ID) == nullptr) { LOGD("Access_token SA not start."); - usleep(USLEEP_TIME_MS); + usleep(USLEEP_TIME_US_100000); } int32_t ret = CheckApiPermission(SYSTEM_CORE); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ret); LOGE("System SA not have permission, ret: %{public}d.", ret); return ret; } #endif + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); - LOGI("RegisterDevStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); + LOGI("Completed"); return DM_OK; } @@ -369,36 +404,48 @@ int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegisterDevStatusCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterDevStatusCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::RegisterDevStatusCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStatusCallback(pkgName, callback); - LOGI("RegisterDevStatusCallback completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStatusCallback", DM_OK); + LOGI("Completed"); return DM_OK; } int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDevStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("UnRegisterDevStateCallback Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDevStateCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); - LOGI("UnRegisterDevStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDevStateCallback", DM_OK); + LOGI("Completed"); return DM_OK; } int32_t DeviceManagerImpl::UnRegisterDevStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDevStatusCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("UnRegisterDevStatusCallback Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDevStatusCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().UnRegisterDeviceStatusCallback(pkgName); - LOGI("UnRegisterDevStatusCallback completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDevStatusCallback", DM_OK); + LOGI("Completed"); return DM_OK; } @@ -410,35 +457,14 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons LOGE("DeviceManagerImpl::StartDeviceDiscovery error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - - LOGI("StartDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeInfo.subscribeId, callback); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetExtra(extra); - req->SetSubscribeInfo(subscribeInfo); - int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Failed with ret %{public}d", ret); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_FAILED), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_FAILED_MSG)); - return ret; - } - - DmTraceEnd(); - LOGI("StartDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, + std::to_string(subscribeInfo.subscribeId))); + discParam.insert(std::pair(PARAM_KEY_DISC_MEDIUM, std::to_string(subscribeInfo.medium))); + std::map filterOps; + filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, extra)); + return StartDiscovering(pkgName, discParam, filterOps, callback); } int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint64_t tokenId, @@ -448,107 +474,111 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint LOGE("DeviceManagerImpl::StartDeviceDiscovery error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(tokenId))); + std::map filterOps; + filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, filterOptions)); + return StartDiscovering(pkgName, discParam, filterOps, callback); +} - LOGI("StartDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = 0; - { - std::lock_guard autoLock(subscribIdLock); - if (subscribIdMap_.find(tokenId) != subscribIdMap_.end()) { - return ERR_DM_DISCOVERY_REPEATED; - } - subscribeId = GenRandUint(0, DM_MAX_RANDOM); - subscribIdMap_[tokenId] = subscribeId; - } - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFilterOption(filterOptions); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVERY, req, rsp); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Failed with ret %{public}d", ret); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_FAILED), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_FAILED_MSG)); - return ret; +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + if (pkgName.empty()) { + LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; } - - DmTraceEnd(); - LOGI("StartDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId))); + return StopDiscovering(pkgName, discParam); } -int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::string &pkgName) { if (pkgName.empty()) { LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StopDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); - std::shared_ptr req = std::make_shared(); + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(tokenId))); + return StopDiscovering(pkgName, discParam); +} + +int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, + std::map &discoverParam, const std::map &filterOptions, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("DeviceManagerImpl::StartDiscovering failed: input callback is null or pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); + + uint16_t subscribeId = AddDiscoveryCallback(pkgName, discoverParam, callback); + discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); + std::string discParaStr = ConvertMapToJsonString(discoverParam); + std::string filterOpStr = ConvertMapToJsonString(filterOptions); + + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); + req->SetFirstParam(discParaStr); + req->SetSecondParam(filterOpStr); + int32_t ret = ipcClientProxy_->SendRequest(START_DISCOVERING, req, rsp); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Send Request failed ret: %{public}d", ret); + LOGE("StartDiscovering error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } - ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Failed with ret %{public}d", ret); + LOGE("StartDiscovering error: Failed with ret %{public}d", ret); return ret; } - DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); - LOGI("StopDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + DmTraceEnd(); + LOGI("Completed"); + SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, + std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); return DM_OK; } -int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::string &pkgName) +int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, + std::map &discoverParam) { if (pkgName.empty()) { - LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); + LOGE("DeviceManagerImpl::StopDiscovering failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StopDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = 0; - { - std::lock_guard autoLock(subscribIdLock); - if (subscribIdMap_.find(tokenId) == subscribIdMap_.end()) { - return ERR_DM_STOP_DISCOVERY; - } - subscribeId = subscribIdMap_[tokenId]; - subscribIdMap_.erase(tokenId); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + uint16_t subscribeId = DM_INVALID_FLAG_ID; + if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { + subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); } - std::shared_ptr req = std::make_shared(); + std::string pkgNameTemp = ComposeStr(pkgName, subscribeId); + subscribeId = GetSubscribeIdFromMap(pkgNameTemp); + if (subscribeId == DM_INVALID_FLAG_ID) { + LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); + return ERR_DM_INPUT_PARA_INVALID; + } + discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); + std::string discParaStr = ConvertMapToJsonString(discoverParam); + + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); + req->SetFirstParam(discParaStr); + int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Send Request failed ret: %{public}d", ret); + LOGE("StopDiscovering error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } - ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Failed with ret %{public}d", ret); + LOGE("StopDiscovering error: Failed with ret %{public}d", ret); return ret; } - - DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); - LOGI("StopDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + RemoveDiscoveryCallback(pkgNameTemp); + LOGI("Completed"); return DM_OK; } @@ -556,11 +586,12 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", ERR_DM_INPUT_PARA_INVALID); LOGE("PublishDeviceDiscovery error: pkgName %{public}s invalid para", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("PublishDeviceDiscovery start, pkgName %{public}s", pkgName.c_str()); + LOGI("Start, pkgName %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterPublishCallback(pkgName, publishInfo.publishId, callback); std::shared_ptr req = std::make_shared(); @@ -569,6 +600,7 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co req->SetPublishInfo(publishInfo); int32_t ret = ipcClientProxy_->SendRequest(PUBLISH_DEVICE_DISCOVER, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", ret); LOGE("PublishDeviceDiscovery error: Send Request failed ret: %{public}d", ret); DeviceManagerNotify::GetInstance().UnRegisterPublishCallback(pkgName, publishInfo.publishId); return ERR_DM_IPC_SEND_REQUEST_FAILED; @@ -576,40 +608,45 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", ret); LOGE("PublishDeviceDiscovery error: Failed with ret %{public}d", ret); return ret; } - - LOGI("PublishDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", DM_OK); + LOGI("Completed"); return DM_OK; } int32_t DeviceManagerImpl::UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnPublishDeviceDiscovery start, pkgName %{public}s", pkgName.c_str()); + LOGI("Start, pkgName %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetPublishId(publishId); int32_t ret = ipcClientProxy_->SendRequest(UNPUBLISH_DEVICE_DISCOVER, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", ret); LOGE("UnPublishDeviceDiscovery error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", ret); LOGE("UnPublishDeviceDiscovery error: Failed with ret %{public}d", ret); return ret; } DeviceManagerNotify::GetInstance().UnRegisterPublishCallback(pkgName, publishId); - LOGI("UnPublishDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", DM_OK); + LOGI("Completed"); return DM_OK; } @@ -621,15 +658,23 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("AuthenticateDevice start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmTraceStart(std::string(DM_HITRACE_AUTH_TO_CONSULT)); std::string strDeviceId = deviceInfo.deviceId; DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, strDeviceId, callback); + nlohmann::json extraJson = nlohmann::json::parse(extra, nullptr, false); + if (extraJson.is_discarded()) { + LOGE("extra bindParam %{public}s.", extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + extraJson[TOKENID] = std::to_string(OHOS::IPCSkeleton::GetSelfTokenID()); +#endif std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetExtra(extra); + req->SetExtra(SafetyDump(extraJson)); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); @@ -648,7 +693,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ return ret; } DmTraceEnd(); - LOGI("AuthenticateDevice completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -658,7 +703,7 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons LOGE("UnAuthenticateDevice error: Invalid para. pkgName %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnAuthenticateDevice start, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), + LOGI("Start, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(std::string(deviceInfo.networkId)).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -679,7 +724,35 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons SysEventWrite(std::string(UNAUTHENTICATE_DEVICE_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(UNAUTHENTICATE_DEVICE_SUCCESS_MSG)); - LOGI("UnAuthenticateDevice completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); + return DM_OK; +} + +int32_t DeviceManagerImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "StopAuthenticateDevice", ERR_DM_INPUT_PARA_INVALID); + LOGE("StopAuthenticateDevice error: Invalid para. pkgName %{public}s", pkgName.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + int32_t ret = ipcClientProxy_->SendRequest(STOP_AUTHENTICATE_DEVICE, req, rsp); + if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "StopAuthenticateDevice", ret); + LOGE("StopAuthenticateDevice error: Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "StopAuthenticateDevice", ret); + LOGE("StopAuthenticateDevice error: Failed with ret %{public}d", ret); + return ret; + } + + LOGI("Completed"); return DM_OK; } @@ -687,28 +760,34 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pk std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegisterDeviceManagerFaCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterDeviceManagerFaCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("dRegisterDeviceManagerFaCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); RegisterUiStateCallback(pkgName); - LOGI("DeviceManagerImpl::RegisterDeviceManagerFaCallback completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDeviceManagerFaCallback", DM_OK); + LOGI("Completed"); return DM_OK; } int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDeviceManagerFaCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDeviceManagerFaCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); UnRegisterUiStateCallback(pkgName); - LOGI("UnRegisterDevStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDeviceManagerFaCallback", DM_OK); + LOGI("Completed"); return DM_OK; } @@ -737,7 +816,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t params.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("SetUserOperation start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -756,7 +835,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t LOGE("CheckAuthentication Failed with ret %{public}d", ret); return ret; } - LOGI("SetUserOperation completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -768,7 +847,7 @@ int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(netWorkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetUdidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGD("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -798,7 +877,7 @@ int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(netWorkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetUuidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -839,10 +918,11 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName int32_t DeviceManagerImpl::RegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("RegisterUiStateCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -850,21 +930,26 @@ int32_t DeviceManagerImpl::RegisterUiStateCallback(const std::string &pkgName) int32_t ret = ipcClientProxy_->SendRequest(REGISTER_UI_STATE_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", ret); LOGI("RegisterUiStateCallback Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", ret); LOGE("RegisterUiStateCallback Failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", DM_OK); return DM_OK; } int32_t DeviceManagerImpl::UnRegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterUiStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -875,15 +960,18 @@ int32_t DeviceManagerImpl::UnRegisterUiStateCallback(const std::string &pkgName) int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_UI_STATE_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterUiStateCallback", ret); LOGI("UnRegisterUiStateCallback Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterUiStateCallback", ret); LOGE("UnRegisterUiStateCallback Failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterUiStateCallback", DM_OK); return DM_OK; } @@ -993,7 +1081,7 @@ int32_t DeviceManagerImpl::RegisterCredentialCallback(const std::string &pkgName return ERR_DM_INPUT_PARA_INVALID; } - LOGI("RegisterCredentialCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1010,7 +1098,7 @@ int32_t DeviceManagerImpl::RegisterCredentialCallback(const std::string &pkgName LOGE("RegisterCredentialCallback error: Failed with ret %{public}d", ret); return ret; } - LOGI("RegisterCredentialCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } @@ -1020,7 +1108,7 @@ int32_t DeviceManagerImpl::UnRegisterCredentialCallback(const std::string &pkgNa LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterCredentialCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterCredentialCallback(pkgName); std::shared_ptr req = std::make_shared(); @@ -1038,21 +1126,23 @@ int32_t DeviceManagerImpl::UnRegisterCredentialCallback(const std::string &pkgNa LOGE("UnRegisterCredentialCallback Failed with ret %{public}d", ret); return ret; } - LOGI("UnRegisterCredentialCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } int32_t DeviceManagerImpl::NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ERR_DM_INPUT_PARA_INVALID); LOGE("NotifyEvent error: pkgName empty"); return ERR_DM_INPUT_PARA_INVALID; } if ((eventId <= DM_NOTIFY_EVENT_START) || (eventId >= DM_NOTIFY_EVENT_BUTT)) { LOGE("NotifyEvent eventId invalid"); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ERR_DM_INPUT_PARA_INVALID); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("NotifyEvent start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -1061,16 +1151,19 @@ int32_t DeviceManagerImpl::NotifyEvent(const std::string &pkgName, const int32_t int32_t ret = ipcClientProxy_->SendRequest(NOTIFY_EVENT, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ret); LOGI("NotifyEvent Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ret); LOGE("NotifyEvent failed with ret %{public}d", ret); return ret; } - LOGI("NotifyEvent completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", DM_OK); + LOGI("Completed"); return DM_OK; } @@ -1080,8 +1173,7 @@ int32_t DeviceManagerImpl::RequestCredential(const std::string &pkgName, std::st LOGE("RequestCredential failed, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::RequestCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("Request credential start."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::map requestParam; requestParam.emplace(DM_CREDENTIAL_TYPE, DM_TYPE_MINE); std::string reqParaStr = ConvertMapToJsonString(requestParam); @@ -1100,7 +1192,7 @@ int32_t DeviceManagerImpl::RequestCredential(const std::string &pkgName, std::st return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("request device credential completed."); + LOGI("Completed."); return DM_OK; } @@ -1111,8 +1203,7 @@ int32_t DeviceManagerImpl::CheckCredential(const std::string &pkgName, const std LOGE("Check the credential is invalid para."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::CheckCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("start to CheckCredential."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -1130,7 +1221,7 @@ int32_t DeviceManagerImpl::CheckCredential(const std::string &pkgName, const std return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("Check credential to device completed."); + LOGI("Completed."); return DM_OK; } @@ -1141,8 +1232,7 @@ int32_t DeviceManagerImpl::ImportCredential(const std::string &pkgName, const st LOGE("import the credential is invalid para."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::ImportCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("start to ImportCredential."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::map requestParam; requestParam.emplace(DM_CREDENTIAL_TYPE, DM_TYPE_MINE); requestParam.emplace(DM_CREDENTIAL_REQJSONSTR, reqJsonStr); @@ -1164,7 +1254,7 @@ int32_t DeviceManagerImpl::ImportCredential(const std::string &pkgName, const st return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("import credential to device completed."); + LOGI("Completed."); return DM_OK; } @@ -1175,8 +1265,7 @@ int32_t DeviceManagerImpl::DeleteCredential(const std::string &pkgName, const st LOGE("Delete the credential is invalid para."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::DeleteCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("start to DeleteCredential."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::map requestParam; requestParam.emplace(DM_CREDENTIAL_TYPE, DM_TYPE_MINE); requestParam.emplace(DM_CREDENTIAL_REQJSONSTR, reqJsonStr); @@ -1198,13 +1287,13 @@ int32_t DeviceManagerImpl::DeleteCredential(const std::string &pkgName, const st return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("Delete credential to device completed."); + LOGI("Completed."); return DM_OK; } int32_t DeviceManagerImpl::OnDmServiceDied() { - LOGI("OnDmServiceDied begin"); + LOGI("Start"); int32_t ret = ipcClientProxy_->OnDmServiceDied(); if (ret != DM_OK) { LOGE("OnDmServiceDied failed, ret: %{public}d", ret); @@ -1221,7 +1310,7 @@ int32_t DeviceManagerImpl::GetEncryptedUuidByNetworkId(const std::string &pkgNam "%{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetEncryptedUuidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1240,7 +1329,7 @@ int32_t DeviceManagerImpl::GetEncryptedUuidByNetworkId(const std::string &pkgNam return ret; } uuid = rsp->GetUuid(); - LOGI("GetEncryptedUuidByNetworkId complete, uuid: %{public}s", GetAnonyString(uuid).c_str()); + LOGI("Complete, uuid: %{public}s", GetAnonyString(uuid).c_str()); return DM_OK; } @@ -1251,7 +1340,7 @@ int32_t DeviceManagerImpl::GenerateEncryptedUuid(const std::string &pkgName, con LOGE("DeviceManagerImpl::GenerateEncryptedUuid error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GenerateEncryptedUuid start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1271,79 +1360,83 @@ int32_t DeviceManagerImpl::GenerateEncryptedUuid(const std::string &pkgName, con return ret; } encryptedUuid = rsp->GetUuid(); - LOGI("GenerateEncryptedUuid complete, encryptedUuid: %{public}s", GetAnonyString(encryptedUuid).c_str()); + LOGI("Complete, encryptedUuid: %{public}s", GetAnonyString(encryptedUuid).c_str()); return DM_OK; } int32_t DeviceManagerImpl::CheckAPIAccessPermission() { - LOGI("DeviceManagerImpl::CheckAPIAccessPermission"); + LOGI("Start"); return CheckApiPermission(SYSTEM_BASIC); } int32_t DeviceManagerImpl::CheckNewAPIAccessPermission() { - LOGI("DeviceManagerImpl::CheckNewAPIAccessPermission"); + LOGI("Start"); return CheckApiPermission(NORMAL); } int32_t DeviceManagerImpl::GetLocalDeviceNetWorkId(const std::string &pkgName, std::string &networkId) { - LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceNetWorkId", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } networkId = std::string(info.networkId); - LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId end, pkgName : %{public}s, networkId : %{public}s", - pkgName.c_str(), GetAnonyString(networkId).c_str()); + LOGI("End, networkId : %{public}s", GetAnonyString(networkId).c_str()); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceNetWorkId", info, DM_OK); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceId(const std::string &pkgName, std::string &deviceId) { - LOGI("DeviceManagerImpl::GetLocalDeviceId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceId", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } deviceId = std::string(info.deviceId); - LOGI("DeviceManagerImpl::GetLocalDeviceId end, pkgName : %{public}s, deviceId : %{public}s", pkgName.c_str(), - GetAnonyString(deviceId).c_str()); + LOGI("End, deviceId : %{public}s", GetAnonyString(deviceId).c_str()); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceId", info, DM_OK); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceName(const std::string &pkgName, std::string &deviceName) { - LOGI("DeviceManagerImpl::GetLocalDeviceName start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceName", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } deviceName = std::string(info.deviceName); - LOGI("DeviceManagerImpl::GetLocalDeviceName end, pkgName : %{public}s, deviceName : %{public}s", pkgName.c_str(), - GetAnonyString(deviceName).c_str()); + LOGI("End, deviceName : %{public}s", GetAnonyString(deviceName).c_str()); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceName", info, DM_OK); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceType(const std::string &pkgName, int32_t &deviceType) { - LOGI("DeviceManagerImpl::GetLocalDeviceType start, pkgName : %{public}s", pkgName.c_str()); + LOGI("Start, pkgName : %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceType", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } deviceType = info.deviceTypeId; - LOGI("DeviceManagerImpl::GetLocalDeviceType end, pkgName : %{public}s, deviceType : %{public}d", pkgName.c_str(), - deviceType); + LOGI("End, deviceType : %{public}d", deviceType); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceType", info, DM_OK); return DM_OK; } @@ -1353,12 +1446,14 @@ int32_t DeviceManagerImpl::GetDeviceName(const std::string &pkgName, const std:: DmDeviceInfo deviceInfo; int32_t ret = GetDeviceInfo(pkgName, networkId, deviceInfo); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceName", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceName error, failed ret: %{public}d", ret); return ret; } deviceName = std::string(deviceInfo.deviceName); - LOGI("DeviceManagerImpl::GetDeviceName end, pkgName : %{public}s, networkId : %{public}s, deviceName = %{public}s", + LOGI("End, pkgName : %{public}s, networkId : %{public}s, deviceName = %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str(), GetAnonyString(deviceName).c_str()); + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceName", deviceInfo, DM_OK); return DM_OK; } @@ -1367,12 +1462,14 @@ int32_t DeviceManagerImpl::GetDeviceType(const std::string &pkgName, const std:: DmDeviceInfo deviceInfo; int32_t ret = GetDeviceInfo(pkgName, networkId, deviceInfo); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceType", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceType error, failed ret: %{public}d", ret); return ret; } deviceType = deviceInfo.deviceTypeId; - LOGI("DeviceManagerImpl::GetDeviceType end, pkgName : %{public}s, networkId : %{public}s, deviceType = %{public}d", + LOGI("End, pkgName : %{public}s, networkId : %{public}s, deviceType = %{public}d", pkgName.c_str(), GetAnonyString(networkId).c_str(), deviceType); + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceType", deviceInfo, DM_OK); return DM_OK; } @@ -1384,11 +1481,19 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy return ERR_DM_INPUT_PARA_INVALID; } LOGI("BindDevice start, pkgName: %{public}s", pkgName.c_str()); + nlohmann::json paramJson = nlohmann::json::parse(bindParam, nullptr, false); + if (paramJson.is_discarded()) { + LOGE("BindDevice bindParam %{public}s.", bindParam.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + paramJson[TOKENID] = std::to_string(OHOS::IPCSkeleton::GetSelfTokenID()); +#endif DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, deviceId, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetBindParam(bindParam); + req->SetBindParam(SafetyDump(paramJson)); req->SetBindType(bindType); req->SetDeviceId(deviceId); int32_t ret = ipcClientProxy_->SendRequest(BIND_DEVICE, req, rsp); @@ -1403,7 +1508,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy return ret; } DmTraceEnd(); - LOGI("BindDevice end, pkgName: %{public}s", pkgName.c_str()); + LOGI("End"); return DM_OK; } @@ -1413,7 +1518,7 @@ int32_t DeviceManagerImpl::UnBindDevice(const std::string &pkgName, const std::s LOGE("UnBindDevice error: Invalid para. pkgName %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnBindDevice start, pkgName: %{public}s, deviceId: %{public}s", pkgName.c_str(), + LOGI("Start, pkgName: %{public}s, deviceId: %{public}s", pkgName.c_str(), GetAnonyString(std::string(deviceId)).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1430,7 +1535,7 @@ int32_t DeviceManagerImpl::UnBindDevice(const std::string &pkgName, const std::s return ret; } - LOGI("UnBindDevice end, pkgName: %{public}s", pkgName.c_str()); + LOGI("End"); return DM_OK; } @@ -1442,7 +1547,7 @@ int32_t DeviceManagerImpl::GetNetworkTypeByNetworkId(const std::string &pkgName, "%{public}d", pkgName.c_str(), GetAnonyString(netWorkId).c_str(), netWorkType); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetNetworkTypeByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1471,7 +1576,7 @@ int32_t DeviceManagerImpl::ImportAuthCode(const std::string &pkgName, const std: GetAnonyString(authCode).c_str(), pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("ImportAuthCode start, authCode: %{public}s", GetAnonyString(authCode).c_str()); + LOGI("Start, authCode: %{public}s", GetAnonyString(authCode).c_str()); int32_t length = static_cast(authCode.length()); if (length != DM_IMPORT_AUTH_CODE_LENGTH) { LOGE("ImportAuthCode error: Invalid para, authCode size error."); @@ -1506,7 +1611,7 @@ int32_t DeviceManagerImpl::ImportAuthCode(const std::string &pkgName, const std: int32_t DeviceManagerImpl::ExportAuthCode(std::string &authCode) { - LOGI("ExportAuthCode start"); + LOGI("Start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1524,82 +1629,7 @@ int32_t DeviceManagerImpl::ExportAuthCode(std::string &authCode) } authCode = rsp->GetAuthCode(); - LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); - return DM_OK; -} - -int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, - std::map &discoverParam, const std::map &filterOptions, - std::shared_ptr callback) -{ - if (pkgName.empty() || callback == nullptr) { - LOGE("DeviceManagerImpl::StartDiscovering failed: input callback is null or pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - LOGI("StartDiscovering start, pkgName: %{public}s", pkgName.c_str()); - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - - uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); - discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); - std::string discParaStr = ConvertMapToJsonString(discoverParam); - std::string filterOpStr = ConvertMapToJsonString(filterOptions); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFirstParam(discParaStr); - req->SetSecondParam(filterOpStr); - int32_t ret = ipcClientProxy_->SendRequest(START_DISCOVERING, req, rsp); - if (ret != DM_OK) { - LOGE("StartDiscovering error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDiscovering error: Failed with ret %{public}d", ret); - return ret; - } - - DmTraceEnd(); - LOGI("StartDiscovering completed, pkgName: %{public}s", pkgName.c_str()); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; -} - -int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, - std::map &discoverParam) -{ - if (pkgName.empty()) { - LOGE("DeviceManagerImpl::StopDiscovering failed: input pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - LOGI("StopDiscovering start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); - if (subscribeId == DM_INVALID_FLAG_ID) { - LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); - return ERR_DM_INPUT_PARA_INVALID; - } - discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); - std::string discParaStr = ConvertMapToJsonString(discoverParam); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFirstParam(discParaStr); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); - if (ret != DM_OK) { - LOGE("StopDiscovering error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StopDiscovering error: Failed with ret %{public}d", ret); - return ret; - } - - LOGI("StopDiscovering completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); return DM_OK; } @@ -1611,16 +1641,15 @@ int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, LOGE("DeviceManagerImpl::RegisterDiscoveryCallback failed: input callback is null or pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("RegisterDiscoveryCallback start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + uint16_t subscribeId = AddDiscoveryCallback(pkgName, discoverParam, callback); discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); std::string discParaStr = ConvertMapToJsonString(discoverParam); std::string filterOpStr = ConvertMapToJsonString(filterOptions); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); req->SetFirstParam(discParaStr); req->SetSecondParam(filterOpStr); int32_t ret = ipcClientProxy_->SendRequest(REGISTER_DISCOVERY_CALLBACK, req, rsp); @@ -1633,20 +1662,24 @@ int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, LOGE("RegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } - LOGI("RegisterDiscoveryCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDiscoveryCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::UnRegisterDiscoveryCallback failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDiscoveryCallback start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + std::string pkgNameTemp = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + uint16_t subscribeId = GetSubscribeIdFromMap(pkgNameTemp); if (subscribeId == DM_INVALID_FLAG_ID) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDiscoveryCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::UnRegisterDiscoveryCallback failed: cannot find pkgName in cache map."); return ERR_DM_INPUT_PARA_INVALID; } @@ -1656,19 +1689,23 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); req->SetFirstParam(extraParaStr); int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_DISCOVERY_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } - LOGI("UnRegisterDiscoveryCallback completed, pkgName: %{public}s", pkgName.c_str()); + RemoveDiscoveryCallback(pkgNameTemp); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "UnRegisterDiscoveryCallback", DM_OK); + LOGI("Completed"); return DM_OK; } @@ -1679,7 +1716,7 @@ int32_t DeviceManagerImpl::StartAdvertising(const std::string &pkgName, LOGE("DeviceManagerImpl::StartAdvertising error: pkgName %{public}s invalid para", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::StartAdvertising start, pkgName %{public}s", pkgName.c_str()); + LOGI("Start, pkgName %{public}s", pkgName.c_str()); int32_t publishId; if (advertiseParam.find(PARAM_KEY_PUBLISH_ID) == advertiseParam.end()) { @@ -1705,7 +1742,7 @@ int32_t DeviceManagerImpl::StartAdvertising(const std::string &pkgName, return ret; } DeviceManagerNotify::GetInstance().RegisterPublishCallback(pkgName, publishId, callback); - LOGI("DeviceManagerImpl::StartAdvertising completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1716,7 +1753,7 @@ int32_t DeviceManagerImpl::StopAdvertising(const std::string &pkgName, LOGE("DeviceManagerImpl::StopAdvertising failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::StopAdvertising start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); int32_t publishId; if (advertiseParam.find(PARAM_KEY_PUBLISH_ID) == advertiseParam.end()) { @@ -1746,7 +1783,7 @@ int32_t DeviceManagerImpl::StopAdvertising(const std::string &pkgName, return ret; } DeviceManagerNotify::GetInstance().UnRegisterPublishCallback(pkgName, publishId); - LOGI("DeviceManagerImpl::StopAdvertising completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1758,8 +1795,11 @@ int32_t DeviceManagerImpl::BindTarget(const std::string &pkgName, const PeerTarg return ERR_DM_INPUT_PARA_INVALID; } LOGI("DeviceManagerImpl::BindTarget start, pkgName: %{public}s", pkgName.c_str()); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + bindParam[TOKENID] = std::to_string(OHOS::IPCSkeleton::GetSelfTokenID()); +#endif std::string bindParamStr = ConvertMapToJsonString(bindParam); - + DeviceManagerNotify::GetInstance().RegisterBindCallback(pkgName, targetId, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -1775,9 +1815,8 @@ int32_t DeviceManagerImpl::BindTarget(const std::string &pkgName, const PeerTarg LOGE("BindTarget error: Failed with ret %{public}d", ret); return ret; } - DeviceManagerNotify::GetInstance().RegisterBindCallback(pkgName, targetId, callback); - LOGI("DeviceManagerImpl::BindTarget completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1788,7 +1827,7 @@ int32_t DeviceManagerImpl::UnbindTarget(const std::string &pkgName, const PeerTa LOGE("DeviceManagerImpl::UnbindTarget failed: input pkgName or targetId is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::UnbindTarget start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::string unbindParamStr = ConvertMapToJsonString(unbindParam); std::shared_ptr req = std::make_shared(); @@ -1808,7 +1847,7 @@ int32_t DeviceManagerImpl::UnbindTarget(const std::string &pkgName, const PeerTa } DeviceManagerNotify::GetInstance().RegisterUnbindCallback(pkgName, targetId, callback); - LOGI("DeviceManagerImpl::UnbindTarget completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1829,11 +1868,14 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, { (void)extraParam; if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::RegisterDeviceStateCallback failed: input pkgName or callback is empty."); return ERR_DM_INPUT_PARA_INVALID; } + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); - LOGI("DeviceManagerImpl::RegisterDeviceStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } @@ -1841,24 +1883,38 @@ int32_t DeviceManagerImpl::CheckAccessToTarget(uint64_t tokenId, const std::stri { (void)tokenId; (void)targetId; - LOGI("DeviceManagerImpl::CheckAccessToTarget start"); + LOGI("Start"); return ERR_DM_UNSUPPORTED_METHOD; } uint16_t DeviceManagerImpl::AddDiscoveryCallback(const std::string &pkgName, - std::shared_ptr callback) + std::map &discoverParam, std::shared_ptr callback) { + if (discoverParam.empty() || callback == nullptr) { + LOGE("input param invalid."); + return DM_INVALID_FLAG_ID; + } uint16_t subscribeId = DM_INVALID_FLAG_ID; + if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { + subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); + } + std::string pkgNameTemp = ComposeStr(pkgName, subscribeId); { std::lock_guard autoLock(subMapLock); - if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { - subscribeId = pkgName2SubIdMap_[pkgName]; - } else { + auto item = pkgName2SubIdMap_.find(pkgNameTemp); + if (item == pkgName2SubIdMap_.end() && subscribeId == DM_INVALID_FLAG_ID) { subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); - pkgName2SubIdMap_[pkgName] = subscribeId; + pkgName2SubIdMap_[pkgNameTemp] = subscribeId; + } else if (item == pkgName2SubIdMap_.end() && subscribeId != DM_INVALID_FLAG_ID) { + pkgName2SubIdMap_[pkgNameTemp] = subscribeId; + } else if (item != pkgName2SubIdMap_.end()) { + subscribeId = pkgName2SubIdMap_[pkgNameTemp]; + } else { + LOGE("subscribeId is unreasonable"); } } - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); + DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgNameTemp, subscribeId, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "AddDiscoveryCallback", DM_OK); return subscribeId; } @@ -1873,6 +1929,7 @@ uint16_t DeviceManagerImpl::RemoveDiscoveryCallback(const std::string &pkgName) } } DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RemoveDiscoveryCallback", DM_OK); return subscribeId; } @@ -1888,6 +1945,7 @@ int32_t DeviceManagerImpl::AddPublishCallback(const std::string &pkgName) pkgName2PubIdMap_[pkgName] = publishId; } } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "AddPublishCallback", DM_OK); return publishId; } @@ -1901,7 +1959,7 @@ int32_t DeviceManagerImpl::RemovePublishCallback(const std::string &pkgName) pkgName2PubIdMap_.erase(pkgName); } } - + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RemovePublishCallback", DM_OK); return publishId; } @@ -1909,6 +1967,8 @@ int32_t DeviceManagerImpl::RegisterPinHolderCallback(const std::string &pkgName, std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegisterPinHolderCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterPinHolderCallback error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } @@ -1919,14 +1979,17 @@ int32_t DeviceManagerImpl::RegisterPinHolderCallback(const std::string &pkgName, int32_t ret = ipcClientProxy_->SendRequest(REGISTER_PIN_HOLDER_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterPinHolderCallback", ret); LOGI("RegisterPinHolderCallback Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterPinHolderCallback", ret); LOGE("RegisterPinHolderCallback Failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterPinHolderCallback", DM_OK); return DM_OK; } @@ -1992,7 +2055,7 @@ int32_t DeviceManagerImpl::DestroyPinHolder(const std::string &pkgName, const Pe int32_t DeviceManagerImpl::DpAclAdd(const int64_t accessControlId, const std::string &udid, const int32_t bindType) { - LOGI("DpAclAdd start."); + LOGI("Start."); if (bindType != IDENTICAL_ACCOUNT) { LOGI("DeviceManagerImpl::DpAclAdd is not identical account"); return DM_OK; @@ -2010,7 +2073,7 @@ int32_t DeviceManagerImpl::DpAclAdd(const int64_t accessControlId, const std::st LOGE("DpAclAdd error: Failed with ret %{public}d", ret); return ret; } - LOGI("DeviceManagerImpl::DpAclAdd completed"); + LOGI("Completed"); return DM_OK; } @@ -2018,11 +2081,12 @@ int32_t DeviceManagerImpl::GetDeviceSecurityLevel(const std::string &pkgName, co int32_t &securityLevel) { if (pkgName.empty() || networkId.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::GetDeviceSecurityLevel error: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::GetDeviceSecurityLevel start: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), + LOGI("Start: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); std::shared_ptr req = std::make_shared(); @@ -2032,22 +2096,25 @@ int32_t DeviceManagerImpl::GetDeviceSecurityLevel(const std::string &pkgName, co int32_t ret = ipcClientProxy_->SendRequest(GET_SECURITY_LEVEL, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", ret); LOGE("GetDeviceSecurityLevel Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", ret); LOGE("GetDeviceSecurityLevel Failed with ret %{public}d", ret); return ret; } securityLevel = rsp->GetSecurityLevel(); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", DM_OK); return DM_OK; } int32_t DeviceManagerImpl::CheckApiPermission(int32_t permissionLevel) { - LOGI("DeviceManagerImpl::CheckApiPermission permissionLevel: %{public}d", permissionLevel); + LOGI("PermissionLevel: %{public}d", permissionLevel); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPermissionLevel(permissionLevel); @@ -2062,7 +2129,7 @@ int32_t DeviceManagerImpl::CheckApiPermission(int32_t permissionLevel) LOGE("Check permission failed with ret: %{public}d", ret); return ret; } - LOGI("The caller declare the DM permission!"); + LOGD("The caller declare the DM permission!"); return DM_OK; } @@ -2090,41 +2157,47 @@ bool DeviceManagerImpl::IsSameAccount(const std::string &netWorkId) bool DeviceManagerImpl::CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) { - LOGI("DeviceManagerImpl::CheckAccessControl"); + LOGI("Start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetAccessCaller(caller); req->SetAccessCallee(callee); int32_t ret = ipcClientProxy_->SendRequest(CHECK_ACCESS_CONTROL, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckAccessControl", ret); LOGE("CheckAccessControl Send Request failed ret: %{public}d", ret); return false; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckAccessControl", ret); LOGE("CheckAccessControl Failed with ret: %{public}d", ret); return false; } + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckAccessControl", DM_OK); return true; } bool DeviceManagerImpl::CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) { - LOGI("DeviceManagerImpl::CheckIsSameAccount"); + LOGI("Start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetAccessCaller(caller); req->SetAccessCallee(callee); int32_t ret = ipcClientProxy_->SendRequest(CHECK_SAME_ACCOUNT, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckIsSameAccount", ret); LOGE("CheckIsSameAccount Send Request failed ret: %{public}d", ret); return false; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckIsSameAccount", ret); LOGE("CheckIsSameAccount Failed with ret: %{public}d", ret); return false; } + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckIsSameAccount", DM_OK); return true; } @@ -2139,22 +2212,258 @@ int32_t DeviceManagerImpl::GetErrCode(int32_t errCode) int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) { - LOGI("ShiftLNNGear start. for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start. pkgName = %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); int32_t ret = ipcClientProxy_->SendRequest(SHIFT_LNN_GEAR, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "ShiftLNNGear", ret); LOGE("ShiftLNNGear error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "ShiftLNNGear", ret); LOGE("ShiftLNNGear error: Failed with ret %{public}d", ret); return ret; } - LOGI("DeviceManagerImpl::ShiftLNNGear completed"); + LOGI("Completed"); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "ShiftLNNGear", DM_OK); + return DM_OK; +} + +int32_t DeviceManagerImpl::SetDnPolicy(const std::string &pkgName, std::map &policy) +{ + const size_t SET_DN_POLICY_PARAM_SIZE = 2; + if (pkgName.empty() || policy.size() != SET_DN_POLICY_PARAM_SIZE) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "SetDnPolicy", ERR_DM_INPUT_PARA_INVALID); + LOGE("Para invalid: policy is less than two or pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start"); + std::string strategy = ConvertMapToJsonString(policy); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetFirstParam(strategy); + int32_t ret = ipcClientProxy_->SendRequest(SET_DN_POLICY, req, rsp); + if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "SetDnPolicy", ret); + LOGE("Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "SetDnPolicy", ret); + LOGE("Failed with ret %{public}d", ret); + return ret; + } + LOGI("Completed"); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "SetDnPolicy", DM_OK); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Error: Invalid para"); + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegDevTrustChangeCallback", ERR_DM_INPUT_PARA_INVALID); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("PkgName %{public}s.", pkgName.c_str()); + SyncCallbackToService(DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE, pkgName); + DeviceManagerNotify::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegDevTrustChangeCallback", DM_OK); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE, pkgName); + DeviceManagerNotify::GetInstance().RegisterDeviceScreenStatusCallback(pkgName, callback); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_DEVICE_SCREEN_STATE, pkgName); + DeviceManagerNotify::GetInstance().UnRegisterDeviceScreenStatusCallback(pkgName); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) +{ + if (pkgName.empty() || networkId.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetNetWorkId(networkId); + + int32_t ret = ipcClientProxy_->SendRequest(GET_DEVICE_SCREEN_STATUS, req, rsp); + if (ret != DM_OK) { + LOGE("Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("Failed with ret %{public}d", ret); + return ret; + } + screenStatus = rsp->GetScreenStatus(); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, + std::string &networkId) +{ + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerImpl::GetNetworkIdByUdid error: Invalid para, pkgName: %{public}s, udid: %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGD("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetUdid(udid); + + int32_t ret = ipcClientProxy_->SendRequest(GET_NETWORKID_BY_UDID, req, rsp); + if (ret != DM_OK) { + LOGI("GetNetworkIdByUdid Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("GetNetworkIdByUdid Failed with ret %{public}d", ret); + return ret; + } + networkId = rsp->GetNetWorkId(); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + SyncCallbackToService(DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY, pkgName); + DeviceManagerNotify::GetInstance().RegisterCredentialAuthStatusCallback(pkgName, callback); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_CREDENTIAL_AUTH_STATUS_NOTIFY, pkgName); + DeviceManagerNotify::GetInstance().UnRegisterCredentialAuthStatusCallback(pkgName); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().RegisterSinkBindCallback(pkgName, callback); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterSinkBindCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().UnRegisterSinkBindCallback(pkgName); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } + +uint16_t DeviceManagerImpl::GetSubscribeIdFromMap(const std::string &pkgName) +{ + { + std::lock_guard autoLock(subMapLock); + if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { + return pkgName2SubIdMap_[pkgName]; + } + } + return DM_INVALID_FLAG_ID; +} + +void DeviceManagerImpl::SyncCallbackToService(DmCommonNotifyEvent dmCommonNotifyEvent, const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + if (!IsDmCommonNotifyEventValid(dmCommonNotifyEvent)) { + LOGE("Invalid dmCommonNotifyEvent: %{public}d.", dmCommonNotifyEvent); + return; + } + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetDmCommonNotifyEvent(static_cast(dmCommonNotifyEvent)); + int32_t ret = ipcClientProxy_->SendRequest(SYNC_CALLBACK, req, rsp); + if (ret != DM_OK) { + LOGI("Send Request failed ret: %{public}d", ret); + return; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("Failed with ret %{public}d", ret); + return; + } +} + +void DeviceManagerImpl::SyncCallbacksToService(std::map> &callbackMap) +{ + if (callbackMap.size() == 0) { + LOGI("callbackMap is empty."); + return; + } + for (auto iter : callbackMap) { + if (iter.second.size() == 0) { + continue; + } + for (auto item : iter.second) { + SyncCallbackToService(iter.first, item); + } + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp index 8db463b927298cb9de7d7639de6a890e67906ded..d8584b2b3ee3ec4bcb978b792ffb29ce4596205f 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp @@ -84,6 +84,8 @@ int32_t IpcClientManager::UnInit(const std::string &pkgName) int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { + CHECK_NULL_RETURN(req, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(rsp, ERR_DM_POINT_NULL); std::string pkgName = req->GetPkgName(); if (!IsInit(pkgName)) { return ERR_DM_INIT_FAILED; diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp index 248628c0da2f24a76587fdaaf931949f2b2a9b74..a3c291e938360fe97e89476a1f714c167ef19204 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp @@ -30,8 +30,7 @@ #include "ipc_register_listener_req.h" #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" +#include "ipc_sync_callback_req.h" #include "securec.h" namespace OHOS { @@ -163,44 +162,6 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, - size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string extra = pReq->GetFilterOption(); - uint16_t subscribeId = pReq->GetSubscribeId(); - - IpcIoInit(&request, buffer, buffLen, 0); - WriteString(&request, pkgName.c_str()); - WriteString(&request, extra.c_str()); - WriteUint16(&request, subscribeId); - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVERY, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - return SetRspErrCode(reply, pBaseRsp); -} - -ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, - size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - - IpcIoInit(&request, buffer, buffLen, 0); - WriteString(&request, pkgName.c_str()); - WriteUint16(&request, subscribeId); - return DM_OK; -} - -ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - return SetRspErrCode(reply, pBaseRsp); -} - ON_IPC_SET_REQUEST(REQUEST_CREDENTIAL, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, size_t buffLen) { @@ -370,5 +331,23 @@ ON_IPC_CMD(SERVER_DISCOVER_FINISH, IpcIo &reply) DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); } } + +ON_IPC_SET_REQUEST(SYNC_CALLBACK, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t dmCommonNotifyEvent = pReq->GetDmCommonNotifyEvent(); + + IpcIoInit(&request, buffer, buffLen, 0); + WriteString(&request, pkgName.c_str()); + WriteInt32(&request, dmCommonNotifyEvent); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SYNC_CALLBACK, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + return SetRspErrCode(reply, pBaseRsp); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/dm_service_load.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/dm_service_load.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e447d93f1dc540efcc54732c1652db82564b039 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/dm_service_load.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_service_load.h" + +#include "dm_constants.h" +#include "dm_log.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DmServiceLoad); + +int32_t DmServiceLoad::LoadDMService(void) +{ + LOGI("LoadDMService start"); + if (isDMServiceLoading_) { + LOGI("DM service is loading."); + return DM_OK; + } + isDMServiceLoading_ = true; + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + isDMServiceLoading_ = false; + LOGE("failed to get system ability mgr."); + return ERR_DM_POINT_NULL; + } + sptr dmLoadCallback_(new DMLoadCallback()); + int32_t ret = samgr->LoadSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, dmLoadCallback_); + if (ret != DM_OK) { + isDMServiceLoading_ = false; + LOGE("Failed to Load DM service, ret code:%{public}d", ret); + return ret; + } + return DM_OK; +} + +void DmServiceLoad::SetLoadFinish(void) +{ + isDMServiceLoading_ = false; +} + +void DMLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, + const sptr &remoteObject) +{ + LOGI("Load DM service success remoteObject result:%{public}s", (remoteObject != nullptr) ? "true" : "false"); + DmServiceLoad::GetInstance().SetLoadFinish(); + if (remoteObject == nullptr) { + LOGE("remoteObject is nullptr"); + return; + } +} + +void DMLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) +{ + LOGE("Load DM service failed."); + DmServiceLoad::GetInstance().SetLoadFinish(); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 111132e2a0910d01ee78ca100edb5df2c442b8b3..3624d5b4b53c016c9003a014968994eaa1c42f5d 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include + #include "ipc_client_manager.h" #include "device_manager_ipc_interface_code.h" @@ -20,6 +22,7 @@ #include "device_manager_impl.h" #include "dm_constants.h" #include "dm_log.h" +#include "dm_service_load.h" #include "ipc_client_server_proxy.h" #include "ipc_client_stub.h" #include "ipc_register_listener_req.h" @@ -35,11 +38,12 @@ void DmDeathRecipient::OnRemoteDied(const wptr &remote) { LOGW("DmDeathRecipient : OnRemoteDied"); (void)remote; + DeviceManagerNotify::GetInstance().OnRemoteDied(); } int32_t IpcClientManager::ClientInit() { - LOGI("InitDeviceManagerService start"); + LOGI("Start"); if (dmInterface_ != nullptr) { LOGI("DeviceManagerService Already Init"); return DM_OK; @@ -54,6 +58,7 @@ int32_t IpcClientManager::ClientInit() auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); if (object == nullptr) { LOGE("Get DeviceManager SystemAbility Failed"); + DmServiceLoad::GetInstance().LoadDMService(); return ERR_DM_INIT_FAILED; } @@ -64,7 +69,7 @@ int32_t IpcClientManager::ClientInit() LOGE("InitDeviceManagerService: AddDeathRecipient Failed"); } dmInterface_ = iface_cast(object); - LOGI("DeviceManager::InitDeviceManagerService completed"); + LOGI("Completed"); return DM_OK; } @@ -145,9 +150,9 @@ int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr r if (req == nullptr || rsp == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } - LOGI("IpcClientManager::SendRequest in"); + std::lock_guard autoLock(lock_); if (dmInterface_ != nullptr) { - LOGI("IpcClientManager::SendRequest cmdCode: %{public}d", cmdCode); + LOGD("IpcClientManager::SendRequest cmdCode: %{public}d", cmdCode); return dmInterface_->SendCmd(cmdCode, req, rsp); } else { LOGE("dmInterface_ is not init."); @@ -214,8 +219,8 @@ void IpcClientManager::SystemAbilityListener::OnAddSystemAbility(int32_t systemA { LOGI("sa %{public}d is added.", systemAbilityId); if (systemAbilityId == DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID) { - std::map> dmInitCallback - = DeviceManagerNotify::GetInstance().GetDmInitCallback(); + std::map> dmInitCallback = + DeviceManagerNotify::GetInstance().GetDmInitCallback(); if (dmInitCallback.size() == 0) { LOGI("dmInitCallback is empty when ReInit"); return; @@ -223,6 +228,13 @@ void IpcClientManager::SystemAbilityListener::OnAddSystemAbility(int32_t systemA for (auto iter : dmInitCallback) { DeviceManagerImpl::GetInstance().InitDeviceManager(iter.first, iter.second); } + std::map> callbackMap; + DeviceManagerNotify::GetInstance().GetCallBack(callbackMap); + if (callbackMap.size() == 0) { + LOGE("callbackMap is empty when ReInit"); + return; + } + DeviceManagerImpl::GetInstance().SyncCallbacksToService(callbackMap); } } } // namespace DistributedHardware diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index b07d8a6bdbc09ef83c8969260c1dff67412fbebe..d70d3cd3ae4412ced2eecb61f254ffa6f19ac1b7 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -32,6 +32,8 @@ #include "ipc_export_auth_code_rsp.h" #include "ipc_generate_encrypted_uuid_req.h" #include "ipc_get_device_info_rsp.h" +#include "ipc_get_device_screen_status_req.h" +#include "ipc_get_device_screen_status_rsp.h" #include "ipc_get_encrypted_uuid_req.h" #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" @@ -46,9 +48,7 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" +#include "ipc_sync_callback_req.h" #include "ipc_permission_req.h" #include "ipc_publish_req.h" #include "ipc_unbind_device_req.h" @@ -172,6 +172,10 @@ ON_IPC_READ_RESPONSE(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &reply, std ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, MessageParcel &data) { + if (pBaseReq == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } std::string pkgName = pBaseReq->GetPkgName(); if (!data.WriteString(pkgName)) { LOGE("write papam failed"); @@ -308,86 +312,6 @@ ON_IPC_READ_RESPONSE(GET_UUID_BY_NETWORK, MessageParcel &reply, std::shared_ptr< return DM_OK; } -ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string extra = pReq->GetExtra(); - const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteString(extra)) { - LOGE("write extra failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo))) { - LOGE("write subscribe info failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - -ON_IPC_SET_REQUEST(START_DEVICE_DISCOVERY, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string filterOption = pReq->GetFilterOption(); - const uint16_t subscribeId = pReq->GetSubscribeId(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteString(filterOption)) { - LOGE("write filterOption failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteUint16(subscribeId)) { - LOGE("write subscribe id failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVERY, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - -ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteInt16((int16_t)subscribeId)) { - LOGE("write subscribeId failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - if (pBaseRsp == nullptr) { - LOGE("pBaseRsp is null"); - return ERR_DM_FAILED; - } - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - ON_IPC_SET_REQUEST(PUBLISH_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); @@ -1390,6 +1314,61 @@ ON_IPC_READ_RESPONSE(DESTROY_PIN_HOLDER, MessageParcel &reply, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string policy = pReq->GetFirstParam(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(policy)) { + LOGE("write setDnPolicy parameter failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SET_DN_POLICY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(STOP_AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(STOP_AUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_CMD(SERVER_CREATE_PIN_HOLDER, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); @@ -1605,5 +1584,134 @@ ON_IPC_READ_RESPONSE(SHIFT_LNN_GEAR, MessageParcel &reply, std::shared_ptrSetErrCode(reply.ReadInt32()); return DM_OK; } + +ON_IPC_CMD(REMOTE_DEVICE_TRUST_CHANGE, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string udid = data.ReadString(); + int32_t authForm = data.ReadInt32(); + std::string uuid = data.ReadString(); + DeviceManagerNotify::GetInstance().OnDeviceTrustChange(pkgName, udid, uuid, authForm); + reply.WriteInt32(DM_OK); + return DM_OK; +} + +ON_IPC_CMD(SERVER_DEVICE_SCREEN_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + DmDeviceInfo dmDeviceInfo; + DecodeDmDeviceInfo(data, dmDeviceInfo); + DeviceManagerNotify::GetInstance().OnDeviceScreenStatus(pkgName, dmDeviceInfo); + + reply.WriteInt32(DM_OK); + return DM_OK; +} + +ON_IPC_SET_REQUEST(GET_DEVICE_SCREEN_STATUS, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string networkId = pReq->GetNetWorkId(); + if (!data.WriteString(pkgName)) { + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(networkId)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_DEVICE_SCREEN_STATUS, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + pRsp->SetScreenStatus(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(GET_NETWORKID_BY_UDID, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string udid = pReq->GetUdid(); + if (!data.WriteString(pkgName)) { + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(udid)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + pRsp->SetNetWorkId(reply.ReadString()); + return DM_OK; +} + +ON_IPC_CMD(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string deviceList = data.ReadString(); + uint16_t deviceTypeId = data.ReadUint16(); + int32_t errCode = data.ReadInt32(); + DeviceManagerNotify::GetInstance().OnCredentialAuthStatus(pkgName, deviceList, deviceTypeId, errCode); + + reply.WriteInt32(DM_OK); + return DM_OK; +} + +ON_IPC_CMD(SINK_BIND_TARGET_RESULT, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + PeerTargetId targetId; + DecodePeerTargetId(data, targetId); + int32_t result = data.ReadInt32(); + int32_t status = data.ReadInt32(); + std::string content = data.ReadString(); + + DeviceManagerNotify::GetInstance().OnSinkBindResult(pkgName, targetId, result, status, content); + reply.WriteInt32(DM_OK); + return DM_OK; +} + +ON_IPC_SET_REQUEST(REGISTER_DEV_STATE_CALLBACK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(REGISTER_DEV_STATE_CALLBACK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SYNC_CALLBACK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(pReq->GetDmCommonNotifyEvent())) { + LOGE("write notify event failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SYNC_CALLBACK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c b/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c index d99d72c977e059051826385c067a1983ca223aed..033b7466e96c7481f97e0f0a0e95619eb9527b41 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c +++ b/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c @@ -23,7 +23,6 @@ #include "device_manager_common.h" #include "hichain_adapter.h" -#include "softbus_adapter.h" static const char * const FILED_PKG_NAME = "pkgName"; static const char * const FILED_BIND_TYPE = "bindType"; diff --git a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c index 55d6dc537514f490db0bd6377893cea516d2759a..67734a8838c5eff9a70659059c73dc37fe12a8fd 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c +++ b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c @@ -13,14 +13,11 @@ * limitations under the License. */ -#include "softbus_adapter.h" - #include #include #include "cJSON.h" #include "cmsis_os2.h" -#include "discovery_service.h" #include "hichain_adapter.h" #include "inner_session.h" #include "los_config.h" @@ -414,6 +411,10 @@ int GetSoftbusTrustedDeviceList(const char *pkgName, DmDeviceBasicInfo *deviceLi return ERR_DM_SOFTBUS_GET_ALL_DEVICE_INFO; } int minLen = (deviceListLen > *trustListLen ? *trustListLen : deviceListLen); + if (minLen > DM_MAX_DEVICE_SIZE) { + DMLOGE("invalid device len."); + return ERR_DM_INPUT_INVALID_VALUE; + } for (int i = 0; i < minLen; i++) { NodeBasicInfoCopyToDmDevice(&deviceList[i], &nodeInfo[i]); } @@ -742,6 +743,7 @@ static int DeleteSoftbusSemaphoreAndMutex(void) static int FilterDevice(const DmDeviceInfo *dmDeviceInfo) { DMLOGI("FilterDevice start."); + CHECK_NULL_RETURN(dmDeviceInfo, ERR_DM_POINT_NULL); int ret = DM_OK; if (g_discoveryCallbackMap.filterOption.isTrusted != NOT_FILTER && dmDeviceInfo->isLocalExistCredential != g_discoveryCallbackMap.filterOption.isTrusted) { @@ -996,15 +998,21 @@ static void OnSoftbusDeviceOffline(NodeBasicInfo *deviceInfo) static void NodeBasicInfoCopyToDmDevice(DmDeviceBasicInfo *dmDeviceInfo, const NodeBasicInfo *nodeBasicInfo) { - (void)memset_s(dmDeviceInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - errno_t retValue = strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), nodeBasicInfo->deviceName); - if (retValue != EOK) { - DMLOGE("failed to copy device name with ret: %d.", retValue); + if (memset_s(dmDeviceInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + LOGE("NodeBasicInfoCopyToDmDevice memset_s failed."); + return; } - retValue = strcpy_s(dmDeviceInfo->networkId, sizeof(dmDeviceInfo->networkId), nodeBasicInfo->networkId); - if (retValue != EOK) { - DMLOGE("failed to copy networkId with ret: %d.", retValue); + + if (strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), nodeBasicInfo->deviceName) != EOK) { + DMLOGE("failed to copy device name."); + return; + } + + if (strcpy_s(dmDeviceInfo->networkId, sizeof(dmDeviceInfo->networkId), nodeBasicInfo->networkId) != EOK) { + DMLOGE("failed to copy networkId."); + return; } + GetDeviceIdByNetworkId(nodeBasicInfo->networkId, dmDeviceInfo->deviceId); dmDeviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; } @@ -1012,14 +1020,19 @@ static void NodeBasicInfoCopyToDmDevice(DmDeviceBasicInfo *dmDeviceInfo, const N static void DeviceInfoCopyToDmDevice(DmDeviceInfo *dmDeviceInfo, const DeviceInfo *deviceInfo) { const size_t arrayStartPosition = 0; - (void)memset_s(dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - errno_t retValue = strcpy_s(dmDeviceInfo->deviceId, sizeof(dmDeviceInfo->deviceId), deviceInfo->devId); - if (retValue != EOK) { - DMLOGE("failed to copy device id with ret: %d.", retValue); + if (memset_s(dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + DMLOGE("failed to memset device id."); + return; } - retValue = strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), deviceInfo->devName); - if (retValue != EOK) { - DMLOGE("failed to copy device name with ret: %d.", retValue); + + if (strcpy_s(dmDeviceInfo->deviceId, sizeof(dmDeviceInfo->deviceId), deviceInfo->devId) != EOK) { + DMLOGE("failed to copy device id."); + return; + } + + if (strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), deviceInfo->devName) != EOK) { + DMLOGE("failed to copy device name."); + return; } dmDeviceInfo->credible = deviceInfo->isOnline; dmDeviceInfo->deviceTypeId = deviceInfo->devType; @@ -1037,18 +1050,21 @@ static void DeviceInfoCopyToDmDevice(DmDeviceInfo *dmDeviceInfo, const DeviceInf static void DmDeviceInfoToDmBasicInfo(const DmDeviceInfo *dmDeviceInfo, DmDeviceBasicInfo *dmBasicInfo) { - (void)memset_s(dmBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - errno_t retValue = strcpy_s(dmBasicInfo->deviceId, sizeof(dmBasicInfo->deviceId), dmDeviceInfo->deviceId); - if (retValue != EOK) { - DMLOGE("failed to copy device id with ret: %d.", retValue); + if (memset_s(dmBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + DMLOGE("DmDeviceInfoToDmBasicInfo memset_s failed"); + return; } - retValue = strcpy_s(dmBasicInfo->deviceName, sizeof(dmBasicInfo->deviceName), dmDeviceInfo->deviceName); - if (retValue != EOK) { - DMLOGE("failed to copy device name with ret: %d.", retValue); + if (strcpy_s(dmBasicInfo->deviceId, sizeof(dmBasicInfo->deviceId), dmDeviceInfo->deviceId) != EOK) { + DMLOGE("failed to copy device id."); + return; } - retValue = strcpy_s(dmBasicInfo->networkId, sizeof(dmBasicInfo->networkId), dmDeviceInfo->networkId); - if (retValue != EOK) { - DMLOGE("failed to copy device networkId with ret: %d.", retValue); + if (strcpy_s(dmBasicInfo->deviceName, sizeof(dmBasicInfo->deviceName), dmDeviceInfo->deviceName) != EOK) { + DMLOGE("failed to copy device name."); + return; + } + if (strcpy_s(dmBasicInfo->networkId, sizeof(dmBasicInfo->networkId), dmDeviceInfo->networkId) != EOK) { + DMLOGE("failed to copy device networkId."); + return; } dmBasicInfo->deviceTypeId = dmDeviceInfo->deviceTypeId; } diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 997e277c594bcbfd7f29ca8f9001603cf36855b1..ad9113f72f5e6cd7260edd92dbb5904081c456d8 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -18,22 +18,21 @@ #include "device_manager.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); -constexpr uint32_t WAIT_BINDIND_TIME_OUT_SECOND = 1; #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEVICE_ONLINE = "deviceOnline"; constexpr const char* DEVICE_OFFLINE = "deviceOffline"; constexpr const char* DEVICEINFO_CHANGE = "deviceInfoChange"; constexpr const char* DEVICE_READY = "deviceReady"; -#else -constexpr const char* DEVICE_STATE_INIT_QUEUE = "deviceStateInitQueue"; +constexpr const char* DEVICE_TRUST_CHANGE = "deviceTrustChange"; #endif - +const uint16_t DM_INVALID_FLAG_ID = 0; void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback) { @@ -43,19 +42,6 @@ void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgN } std::lock_guard autoLock(lock_); dmInitCallback_[pkgName] = dmInitCallback; - -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - LOGI("DeviceManagerNotify ffrtQueue has created!"); - return; - } - ffrtQueue_ = std::make_shared(DEVICE_STATE_INIT_QUEUE, - ffrt::queue_attr().qos(ffrt::qos_default)); - if (ffrtQueue_ == nullptr) { - LOGE("DeviceManagerNotify ffrtQueue create failed!"); - return; - } -#endif } void DeviceManagerNotify::UnRegisterDeathRecipientCallback(const std::string &pkgName) @@ -209,10 +195,16 @@ void DeviceManagerNotify::UnRegisterPackageCallback(const std::string &pkgName) std::lock_guard autoLock(lock_); deviceStateCallback_.erase(pkgName); deviceStatusCallback_.erase(pkgName); - deviceDiscoveryCallbacks_.erase(pkgName); devicePublishCallbacks_.erase(pkgName); authenticateCallback_.erase(pkgName); dmInitCallback_.erase(pkgName); + for (auto it = deviceDiscoveryCallbacks_.begin(); it != deviceDiscoveryCallbacks_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + it = deviceDiscoveryCallbacks_.erase(it); + } else { + ++it; + } + } } void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName, @@ -267,8 +259,8 @@ void DeviceManagerNotify::RegisterPinHolderCallback(const std::string &pkgName, void DeviceManagerNotify::OnRemoteDied() { LOGW("DeviceManagerNotify::OnRemoteDied"); - std::lock_guard autoLock(lock_); - for (auto iter : dmInitCallback_) { + std::map> dmInitCallback = GetDmInitCallback(); + for (auto iter : dmInitCallback) { LOGI("DeviceManagerNotify::OnRemoteDied, pkgName:%{public}s", iter.first.c_str()); if (iter.second != nullptr) { iter.second->OnRemoteDied(); @@ -282,7 +274,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOnline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Online with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); @@ -298,9 +290,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoOnline(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoOnline(deviceInfo, tempCbk); }); #else std::thread deviceOnline([=]() { DeviceInfoOnline(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceOnline.native_handle(), DEVICE_ONLINE) != DM_OK) { @@ -316,25 +306,23 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOnline with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Online with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); auto iter = deviceStatusCallback_.find(pkgName); if (iter == deviceStatusCallback_.end()) { - LOGE("OnDeviceOnline error, device status callback not register."); + LOGE("Error, device status callback not register."); return; } tempCbk = iter->second; } if (tempCbk == nullptr) { - LOGE("OnDeviceOnline error, registered device status callback is nullptr."); + LOGE("Error, registered device status callback is nullptr."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoOnline(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoOnline(deviceBasicInfo, tempCbk); }); #else std::thread deviceOnline([=]() { DeviceBasicInfoOnline(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceOnline.native_handle(), DEVICE_ONLINE) != DM_OK) { @@ -350,25 +338,24 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOffline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Offline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); auto iter = deviceStateCallback_.find(pkgName); if (iter == deviceStateCallback_.end()) { - LOGE("OnDeviceOffline error, device state callback not register."); + LOGE("Error, device state callback not register."); return; } tempCbk = iter->second; } if (tempCbk == nullptr) { - LOGE("OnDeviceOffline error, registered device state callback is nullptr."); + LOGE("Error, registered device state callback is nullptr."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); + LOGI("Completed, Offline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); #else std::thread deviceOffline([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceOffline.native_handle(), DEVICE_OFFLINE) != DM_OK) { @@ -384,25 +371,23 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOffline with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Offline with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); auto iter = deviceStatusCallback_.find(pkgName); if (iter == deviceStatusCallback_.end()) { - LOGE("OnDeviceOffline error, device status callback not register."); + LOGE("Error, device status callback not register."); return; } tempCbk = iter->second; } if (tempCbk == nullptr) { - LOGE("OnDeviceOffline error, registered device status callback is nullptr."); + LOGE("Error, registered device status callback is nullptr."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoOffline(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoOffline(deviceBasicInfo, tempCbk); }); #else std::thread deviceOffline([=]() { DeviceBasicInfoOffline(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceOffline.native_handle(), DEVICE_OFFLINE) != DM_OK) { @@ -434,9 +419,7 @@ void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDe return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoChanged(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoChanged(deviceInfo, tempCbk); }); #else std::thread deviceChanged([=]() { DeviceInfoChanged(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceChanged.native_handle(), DEVICEINFO_CHANGE) != DM_OK) { @@ -468,9 +451,7 @@ void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDe return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoChanged(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoChanged(deviceBasicInfo, tempCbk); }); #else std::thread deviceChanged([=]() { DeviceBasicInfoChanged(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceChanged.native_handle(), DEVICEINFO_CHANGE) != DM_OK) { @@ -502,9 +483,7 @@ void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDevi return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoReady(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoReady(deviceInfo, tempCbk); }); #else std::thread deviceReady([=]() { DeviceInfoReady(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceReady.native_handle(), DEVICE_READY) != DM_OK) { @@ -536,9 +515,7 @@ void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDevi return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoReady(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoReady(deviceBasicInfo, tempCbk); }); #else std::thread deviceReady([=]() { DeviceBasicInfoReady(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceReady.native_handle(), DEVICE_READY) != DM_OK) { @@ -551,68 +528,34 @@ void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDevi void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { + LOGD("pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } - - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDeviceFound error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDeviceFound error, no register deviceDiscoveryCallback for subscribeId %{public}d.", - (int32_t)subscribeId); - return; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGI("DeviceManagerNotify::OnDeviceFound complete with DmDeviceInfo, pkgName:%{public}s, subscribeId:%{public}d.", - pkgName.c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceInfo); } void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo) { + LOGD("pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } - - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDeviceFound error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDeviceFound error, no register deviceDiscoveryCallback for subscribeId %{public}d.", - (int32_t)subscribeId); - return; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGI("DeviceManagerNotify::OnDeviceFound complete with DmDeviceBasicInfo, pkgName:%{public}s," - "subscribeId:%{public}d.", pkgName.c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceBasicInfo); } @@ -624,23 +567,7 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t } LOGI("DeviceManagerNotify::OnDiscoveryFailed in, pkgName:%{public}s, subscribeId %{public}d, failed" "reason %{public}d", pkgName.c_str(), (int32_t)subscribeId, failedReason); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDiscoveryFailed error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDiscoveryFailed error, device discovery callback not register for subscribeId %{public}d.", - subscribeId); - return; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoveryFailed error, registered device discovery callback is nullptr."); return; @@ -654,25 +581,8 @@ void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_ LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDiscoverySuccess in, pkgName:%{public}s, subscribeId:%{public}d.", pkgName.c_str(), - subscribeId); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("OnDiscoverySuccess error, device discovery callback not register for pkgName %{public}s.", - pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDiscoverySuccess error, device discovery callback not register for subscribeId %{public}d.", - (int32_t)subscribeId); - return; - } - tempCbk = iter->second; - } + LOGI("PkgName:%{public}s, subscribeId:%{public}d.", GetAnonyString(pkgName).c_str(), subscribeId); + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoverySuccess error, registered device discovery callback is nullptr."); return; @@ -810,9 +720,7 @@ void DeviceManagerNotify::RegisterBindCallback(const std::string &pkgName, const pkgName.c_str()); return; } - std::unique_lock ulk(bindLock_); - cv_.wait_for(ulk, std::chrono::seconds(WAIT_BINDIND_TIME_OUT_SECOND), [this]() {return !binding_; }); - binding_ = true; + std::lock_guard autoLock(bindLock_); if (bindCallback_.count(pkgName) == 0) { bindCallback_[pkgName] = std::map>(); } @@ -844,7 +752,7 @@ void DeviceManagerNotify::OnBindResult(const std::string &pkgName, const PeerTar LOGI("DeviceManagerNotify::OnBindResult in, pkgName:%{public}s, result:%{public}d", pkgName.c_str(), result); std::shared_ptr tempCbk; { - std::lock_guard glk(bindLock_); + std::lock_guard autoLock(bindLock_); if (bindCallback_.count(pkgName) == 0) { LOGE("DeviceManagerNotify::OnBindResult error, callback not register for pkgName %{public}s.", pkgName.c_str()); @@ -857,14 +765,12 @@ void DeviceManagerNotify::OnBindResult(const std::string &pkgName, const PeerTar return; } tempCbk = iter->second; - if (result != DM_OK || status > STATUS_DM_CLOSE_PIN_INPUT_UI || status < STATUS_DM_SHOW_AUTHORIZE_UI) { + if (result != DM_OK || status == STATUS_DM_AUTH_FINISH || status == STATUS_DM_AUTH_DEFAULT) { LOGI("notify end, result: %{public}d, status: %{public}d", result, status); bindCallback_[pkgName].erase(targetId); if (bindCallback_[pkgName].empty()) { bindCallback_.erase(pkgName); } - binding_ = false; - cv_.notify_one(); } } if (tempCbk == nullptr) { @@ -1082,5 +988,259 @@ void DeviceManagerNotify::DeviceBasicInfoReady(const DmDeviceBasicInfo &deviceBa { tempCbk->OnDeviceReady(deviceBasicInfo); } + +void DeviceManagerNotify::RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + devTrustChangeCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, + const std::string &uuid, int32_t authForm) +{ + LOGI("PkgName %{public}s, udid %{public}s, uuid %{public}s, authForm %{public}d", pkgName.c_str(), + GetAnonyString(udid).c_str(), GetAnonyString(uuid).c_str(), authForm); + if (pkgName.empty() || authForm < static_cast(INVALID_TYPE) || + authForm > static_cast(ACROSS_ACCOUNT)) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + auto iter = devTrustChangeCallback_.find(pkgName); + if (iter == devTrustChangeCallback_.end()) { + LOGE("PkgName %{public}s device_trust_change callback not register.", pkgName.c_str()); + return; + } + tempCbk = iter->second; + } + if (tempCbk == nullptr) { + LOGE("OnDeviceReady error, registered device status callback is nullptr."); + return; + } + DmAuthForm dmAuthForm = static_cast(authForm); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { DeviceTrustChange(udid, uuid, dmAuthForm, tempCbk); }); +#else + std::thread deviceTrustChange([=]() { DeviceTrustChange(udid, uuid, dmAuthForm, tempCbk); }); + if (pthread_setname_np(deviceTrustChange.native_handle(), DEVICE_TRUST_CHANGE) != DM_OK) { + LOGE("deviceTrustChange set name failed."); + } + deviceTrustChange.detach(); +#endif +} + +void DeviceManagerNotify::DeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm, + std::shared_ptr tempCbk) +{ + if (tempCbk == nullptr) { + LOGE("Callback ptr is nullptr."); + return; + } + tempCbk->OnDeviceTrustChange(udid, uuid, authForm); +} + +void DeviceManagerNotify::RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + deviceScreenStatusCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::lock_guard autoLock(lock_); + deviceScreenStatusCallback_.erase(pkgName); +} + +void DeviceManagerNotify::OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + LOGI("In, pkgName:%{public}s", pkgName.c_str()); + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + if (deviceScreenStatusCallback_.count(pkgName) == 0) { + LOGE("error, device screen status not register."); + return; + } + tempCbk = deviceScreenStatusCallback_[pkgName]; + } + if (tempCbk == nullptr) { + LOGE("error, registered device screen status callback is nullptr."); + return; + } + tempCbk->OnDeviceScreenStatus(deviceInfo); +} + +void DeviceManagerNotify::RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + credentialAuthStatusCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::lock_guard autoLock(lock_); + credentialAuthStatusCallback_.erase(pkgName); +} + +void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, + uint16_t deviceTypeId, int32_t errcode) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + LOGI("In, pkgName:%{public}s", pkgName.c_str()); + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + if (credentialAuthStatusCallback_.find(pkgName) == credentialAuthStatusCallback_.end()) { + LOGE("error, credential auth statusnot register."); + return; + } + tempCbk = credentialAuthStatusCallback_[pkgName]; + } + if (tempCbk == nullptr) { + LOGE("error, registered credential auth status callback is nullptr."); + return; + } + tempCbk->OnCredentialAuthStatus(deviceList, deviceTypeId, errcode); +} + +void DeviceManagerNotify::RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + sinkBindTargetCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterSinkBindCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::lock_guard autoLock(lock_); + sinkBindTargetCallback_.erase(pkgName); +} + +void DeviceManagerNotify::OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, + int32_t result, int32_t status, std::string content) +{ + if (pkgName.empty()) { + LOGE("Invalid para, pkgName: %{public}s.", pkgName.c_str()); + return; + } + LOGI("DeviceManagerNotify::OnSinkBindResult in, pkgName:%{public}s, result:%{public}d", pkgName.c_str(), result); + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + if (sinkBindTargetCallback_.find(pkgName) == sinkBindTargetCallback_.end()) { + LOGE("error, sink bind callback not register."); + return; + } + tempCbk = sinkBindTargetCallback_[pkgName]; + } + if (tempCbk == nullptr) { + LOGE("error, registered sink bind callback is nullptr."); + return; + } + tempCbk->OnBindResult(targetId, result, status, content); +} + +std::shared_ptr DeviceManagerNotify::GetDiscoveryCallback(const std::string &pkgName, + uint16_t subscribeId) +{ + std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); + std::lock_guard autoLock(lock_); + auto iter = deviceDiscoveryCallbacks_.find(discWithSubscribeId); + if (iter != deviceDiscoveryCallbacks_.end()) { + auto subIter = iter->second.find(subscribeId); + if (subIter != iter->second.end()) { + return subIter->second; + } + return nullptr; + } + std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + iter = deviceDiscoveryCallbacks_.find(discNoSubscribeId); + if (iter != deviceDiscoveryCallbacks_.end()) { + auto subIter = iter->second.find(subscribeId); + if (subIter != iter->second.end()) { + return subIter->second; + } + } + return nullptr; +} + +void DeviceManagerNotify::GetCallBack(std::map> &callbackMap) +{ + std::lock_guard autoLock(lock_); + std::set statePkgnameSet; + for (auto it : deviceStateCallback_) { + statePkgnameSet.insert(it.first); + } + for (auto it : deviceStatusCallback_) { + statePkgnameSet.insert(it.first); + } + if (statePkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_DEVICE_STATE] = statePkgnameSet; + } + + std::set trustChangePkgnameSet; + for (auto it : devTrustChangeCallback_) { + trustChangePkgnameSet.insert(it.first); + } + if (trustChangePkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE] = trustChangePkgnameSet; + } + + std::set screenStatusPkgnameSet; + for (auto it : deviceScreenStatusCallback_) { + screenStatusPkgnameSet.insert(it.first); + } + if (screenStatusPkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE] = screenStatusPkgnameSet; + } + + std::set authStatusPkgnameSet; + for (auto it : credentialAuthStatusCallback_) { + authStatusPkgnameSet.insert(it.first); + } + if (authStatusPkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY] = authStatusPkgnameSet; + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index a1419e45c4c9da74ddf850751a0f8ab6f44da51a..c10dbe0a2932d2f904acd88002e209c4c99513eb 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -58,7 +58,6 @@ ohos_shared_library("devicemanager") { "ipc:ipc_core", "json:nlohmann_json_static", "napi:ace_napi", - "node:node_header_notice", ] subsystem_name = "distributedhardware" diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index d50a45f651348355524e6572b5e528358e135e93..ebe81431fe2a7b46669188b4756b19db70c56851 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -32,7 +32,7 @@ #include "napi/native_node_api.h" #include "nlohmann/json.hpp" #define DM_NAPI_BUF_LENGTH (256) -#define DM_NAPI_CREDENTIAL_BUF_LENGTH (12000) +#define DM_NAPI_CREDENTIAL_BUF_LENGTH (64000) #define DM_NAPI_DESCRIPTION_BUF_LENGTH (16384) struct AsyncCallbackInfo { @@ -320,6 +320,7 @@ public: static void JsObjectToInt(const napi_env &env, const napi_value &object, const std::string &fieldStr, int32_t &fieldRef); static std::string JsObjectToString(const napi_env &env, const napi_value ¶m); + static bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, std::string &strValue); static int32_t JsToDmSubscribeInfo(const napi_env &env, const napi_value &object, OHOS::DistributedHardware::DmSubscribeInfo &info); static void JsToDmPublishInfo(const napi_env &env, const napi_value &object, diff --git a/interfaces/kits/js/src/dm_native_event.cpp b/interfaces/kits/js/src/dm_native_event.cpp index d0c3f9bb9afc10992136c4e2856f03d29f13e612..dc76ab0798475dc8aa66722c09b8b9757d71b23d 100644 --- a/interfaces/kits/js/src/dm_native_event.cpp +++ b/interfaces/kits/js/src/dm_native_event.cpp @@ -30,7 +30,9 @@ DmNativeEvent::~DmNativeEvent() { for (auto iter = eventMap_.begin(); iter != eventMap_.end(); iter++) { auto listener = iter->second; - napi_delete_reference(env_, listener->handlerRef); + if (listener != nullptr) { + napi_delete_reference(env_, listener->handlerRef); + } } eventMap_.clear(); napi_delete_reference(env_, thisVarRef_); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 37102786b2f49e404189cd3a0b260d453e00549b..410ae5b502b817d4aad09743b22aed0a79a63c76 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -56,6 +56,7 @@ const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7; const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0; const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_OSD = 1; +constexpr int32_t DM_MAX_DEVICE_SIZE = 100; napi_ref deviceTypeEnumConstructor_ = nullptr; napi_ref deviceStateChangeActionEnumConstructor_ = nullptr; @@ -81,10 +82,10 @@ std::mutex g_publishCallbackMapMutex; std::mutex g_authCallbackMapMutex; std::mutex g_dmUiCallbackMapMutex; -enum DMBussinessErrorCode { +enum class DMBussinessErrorCode : int32_t { // Permission verify failed. ERR_NO_PERMISSION = 201, - //The caller is not a system application. + // The caller is not a system application. ERR_NOT_SYSTEM_APP = 202, // Input parameter error. ERR_INVALID_PARAMS = 401, @@ -127,7 +128,8 @@ bool CheckArgsVal(napi_env env, bool assertion, const std::string ¶m, const { if (!(assertion)) { std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The value of " + param + ": " + msg; - napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + napi_throw_error(env, std::to_string( + static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS)).c_str(), errMsg.c_str()); return false; } return true; @@ -137,7 +139,8 @@ bool CheckArgsCount(napi_env env, bool assertion, const std::string &message) { if (!(assertion)) { std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + message; - napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + napi_throw_error(env, std::to_string( + static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS)).c_str(), errMsg.c_str()); return false; } return true; @@ -148,7 +151,8 @@ bool CheckArgsType(napi_env env, bool assertion, const std::string ¶mName, c if (!(assertion)) { std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The type of " + paramName + " must be " + type; - napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + napi_throw_error(env, std::to_string( + static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS)).c_str(), errMsg.c_str()); return false; } return true; @@ -171,30 +175,37 @@ napi_value CreateBusinessError(napi_env env, int32_t errCode, bool isAsync = tru napi_value error = nullptr; switch (errCode) { case ERR_DM_NO_PERMISSION: - error = CreateErrorForCall(env, ERR_NO_PERMISSION, ERR_MESSAGE_NO_PERMISSION, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::ERR_NO_PERMISSION), + ERR_MESSAGE_NO_PERMISSION, isAsync); break; case ERR_DM_DISCOVERY_REPEATED: - error = CreateErrorForCall(env, DM_ERR_DISCOVERY_INVALID, ERR_MESSAGE_DISCOVERY_INVALID, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_DISCOVERY_INVALID), + ERR_MESSAGE_DISCOVERY_INVALID, isAsync); break; case ERR_DM_PUBLISH_REPEATED: - error = CreateErrorForCall(env, DM_ERR_PUBLISH_INVALID, ERR_MESSAGE_PUBLISH_INVALID, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_PUBLISH_INVALID), + ERR_MESSAGE_PUBLISH_INVALID, isAsync); break; case ERR_DM_AUTH_BUSINESS_BUSY: - error = CreateErrorForCall(env, DM_ERR_AUTHENTICALTION_INVALID, + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_AUTHENTICALTION_INVALID), ERR_MESSAGE_AUTHENTICALTION_INVALID, isAsync); break; case ERR_DM_INPUT_PARA_INVALID: case ERR_DM_UNSUPPORTED_AUTH_TYPE: - error = CreateErrorForCall(env, ERR_INVALID_PARAMS, ERR_MESSAGE_INVALID_PARAMS, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS), + ERR_MESSAGE_INVALID_PARAMS, isAsync); break; case ERR_DM_INIT_FAILED: - error = CreateErrorForCall(env, DM_ERR_OBTAIN_SERVICE, ERR_MESSAGE_OBTAIN_SERVICE, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_OBTAIN_SERVICE), + ERR_MESSAGE_OBTAIN_SERVICE, isAsync); break; - case ERR_NOT_SYSTEM_APP: - error = CreateErrorForCall(env, ERR_NOT_SYSTEM_APP, ERR_MESSAGE_NOT_SYSTEM_APP, isAsync); + case ERR_DM_NOT_SYSTEM_APP: + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP), + ERR_MESSAGE_NOT_SYSTEM_APP, isAsync); break; default: - error = CreateErrorForCall(env, DM_ERR_FAILED, ERR_MESSAGE_FAILED, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_FAILED), + ERR_MESSAGE_FAILED, isAsync); break; } return error; @@ -842,6 +853,7 @@ void DeviceManagerNapi::OnCredentialResult(int32_t &action, const std::string &c if (handler != nullptr) { napi_call_function(env_, nullptr, handler, DM_NAPI_ARGS_ONE, &result, &callResult); napi_delete_reference(env_, creAsyncCallbackInfo_.callback); + creAsyncCallbackInfo_.callback = nullptr; } else { LOGE("handler is nullptr"); } @@ -964,7 +976,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAu napi_create_object(env, &extraInfo); SetValueInt32(env, "direction", authParam.direction, extraInfo); SetValueInt32(env, "authType", authParam.authType, paramResult); - SetValueInt32(env, "pinToken", stoi(authParam.authToken), extraInfo); + SetValueInt32(env, "pinToken", atoi(authParam.authToken.c_str()), extraInfo); if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); @@ -1190,9 +1202,8 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec jsonObj[APP_OPERATION] = appOperationStr; jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr; jsonObj[BIND_LEVEL] = bindLevel; - jsonObj[TOKENID] = OHOS::IPCSkeleton::GetSelfTokenID(); JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(); + extra = SafetyDump(jsonObj); LOGI("appOperationLen %{public}zu, customDescriptionLen %{public}zu", appOperationStr.size(), customDescriptionStr.size()); } @@ -1263,7 +1274,7 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob jsonObj[AUTH_TYPE] = authType; jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(); + extra = SafetyDump(jsonObj); } void DeviceManagerNapi::JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra) @@ -1483,7 +1494,7 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i { LOGI("SetUserOperationSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -1527,6 +1538,11 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { + CHECK_NULL_VOID(deviceInfoListAsyncCallbackInfo); + if (deviceInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { + LOGE("CallGetTrustedDeviceListStatusSync invalid devList size"); + return; + } for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) { LOGI("DeviceManager::GetTrustedDeviceList deviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", GetAnonyString(deviceInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(), @@ -1614,6 +1630,11 @@ void DeviceManagerNapi::OnDmUiCall(const std::string ¶mJson) void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { + CHECK_NULL_VOID(deviceInfoListAsyncCallbackInfo); + if (deviceInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { + LOGE("CallGetTrustedDeviceListStatus invalid devList size"); + return; + } for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) { LOGI("DeviceManager::GetTrustedDeviceList deviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", GetAnonyString(deviceInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(), @@ -2025,7 +2046,7 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListByFilter(napi_env env, napi_ca napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2072,7 +2093,7 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback { LOGI("GetLocalDeviceInfoSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2110,7 +2131,7 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfo(napi_env env, napi_callback_inf { LOGI("GetLocalDeviceInfo in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } if (DeviceManager::GetInstance().CheckAPIAccessPermission() != 0) { @@ -2162,7 +2183,7 @@ napi_value DeviceManagerNapi::UnAuthenticateDevice(napi_env env, napi_callback_i { LOGI("UnAuthenticateDevice"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } napi_value result = nullptr; @@ -2215,7 +2236,7 @@ bool DeviceManagerNapi::CheckPermissions(napi_env env) { LOGI("CheckPermissions in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return false; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2253,7 +2274,7 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac { LOGI("StartDeviceDiscoverSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } std::string extra = ""; @@ -2291,7 +2312,7 @@ napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback { LOGI("StopDeviceDiscoverSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); @@ -2333,7 +2354,7 @@ napi_value DeviceManagerNapi::PublishDeviceDiscoverySync(napi_env env, napi_call { LOGI("PublishDeviceDiscoverySync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); @@ -2384,7 +2405,7 @@ napi_value DeviceManagerNapi::UnPublishDeviceDiscoverySync(napi_env env, napi_ca { LOGI("UnPublishDeviceDiscoverySync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); @@ -2422,7 +2443,7 @@ napi_value DeviceManagerNapi::UnPublishDeviceDiscoverySync(napi_env env, napi_ca napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); @@ -2478,7 +2499,7 @@ napi_value DeviceManagerNapi::RequestCredential(napi_env env, napi_callback_info LOGI("RequestCredential function has been discarded"); return nullptr; if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -2550,7 +2571,7 @@ napi_value DeviceManagerNapi::ImportCredential(napi_env env, napi_callback_info { LOGI("ImportCredential start."); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -2603,7 +2624,7 @@ napi_value DeviceManagerNapi::DeleteCredential(napi_env env, napi_callback_info LOGE("DeleteCredential function has been discarded"); return nullptr; if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -2703,7 +2724,7 @@ napi_value DeviceManagerNapi::JsOnFrench(napi_env env, int32_t num, napi_value t napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2789,7 +2810,7 @@ napi_value DeviceManagerNapi::JsOffFrench(napi_env env, int32_t num, napi_value napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } size_t argc = 0; @@ -2871,7 +2892,7 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i { LOGI("ReleaseDeviceManager in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -3067,10 +3088,32 @@ void DeviceManagerNapi::DeviceInfotoJsByNetworkId(const napi_env &env, const DmD SetValueInt32(env, "deviceType", (int)nidDevInfo.deviceTypeId, result); } +bool DeviceManagerNapi::JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, + std::string &strValue) +{ + napi_valuetype deviceIdType = napi_undefined; + napi_typeof(env, value, &deviceIdType); + if (!CheckArgsType(env, deviceIdType == napi_string, valueName, "string")) { + return false; + } + size_t valueLen = 0; + napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen); + if (!CheckArgsVal(env, valueLen > 0, valueName, "len == 0")) { + return false; + } + if (!CheckArgsVal(env, valueLen < DM_NAPI_BUF_LENGTH, valueName, "len >= MAXLEN")) { + return false; + } + char temp[DM_NAPI_BUF_LENGTH] = {0}; + napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + strValue = temp; + return true; +} + napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } napi_value result = nullptr; @@ -3081,23 +3124,20 @@ napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info inf NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); NAPI_ASSERT(env, ((argc >= DM_NAPI_ARGS_ONE) && (argc <= DM_NAPI_ARGS_TWO)), "requires 1 or 2 parameter"); - napi_valuetype networkIdValueType = napi_undefined; - napi_typeof(env, argv[0], &networkIdValueType); - if (!CheckArgsType(env, networkIdValueType == napi_string, "networkId", "string")) { + std::string networkId; + if (!JsToStringAndCheck(env, argv[0], "networkId", networkId)) { return nullptr; } - size_t networkIdLen = 0; - napi_get_value_string_utf8(env, argv[0], nullptr, 0, &networkIdLen); - NAPI_ASSERT(env, networkIdLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN"); - char networkIdValue[DM_NAPI_BUF_LENGTH] = {0}; - napi_get_value_string_utf8(env, argv[0], networkIdValue, networkIdLen + 1, &networkIdLen); DeviceManagerNapi *deviceManagerWrapper = nullptr; - napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) { + napi_create_uint32(env, ERR_DM_POINT_NULL, &result); + return result; + } auto *networkIdAsyncCallbackInfo = new NetworkIdAsyncCallbackInfo(); networkIdAsyncCallbackInfo->env = env; networkIdAsyncCallbackInfo->deviceInfo = deviceInfo; networkIdAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; - networkIdAsyncCallbackInfo->networkId = std::string(networkIdValue); + networkIdAsyncCallbackInfo->networkId = networkId; if (argc == DM_NAPI_ARGS_ONE) { // promise napi_deferred deferred; @@ -3122,7 +3162,7 @@ napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_in { LOGI("CreateDeviceManager in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -3178,7 +3218,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) size_t typeLen = 0; napi_get_value_string_utf8(env, argv[0], bundleName, sizeof(bundleName), &typeLen); - LOGI("create DeviceManagerNapi for packageName:%{public}s", bundleName); + LOGI("create DeviceManagerNapi for packageName:%{public}s", GetAnonyString(bundleName).c_str()); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); if (obj == nullptr) { return nullptr; @@ -3187,7 +3227,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) obj->bundleName_ = std::string(bundleName); std::lock_guard autoLock(g_deviceManagerMapMutex); g_deviceManagerMap[obj->bundleName_] = obj; - napi_wrap( + napi_status status = napi_wrap( env, thisVar, reinterpret_cast(obj), [](napi_env env, void *data, void *hint) { (void)env; @@ -3198,6 +3238,12 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) LOGI("delete deviceManager"); }, nullptr, nullptr); + if (status != napi_ok) { + delete obj; + obj = nullptr; + LOGE("failed to wrap JS object"); + return nullptr; + } return thisVar; } diff --git a/interfaces/kits/js4.0/BUILD.gn b/interfaces/kits/js4.0/BUILD.gn index 07a13f4c8f4556d44f7b79be8fabb0d38aa7cfb7..7e787590261aa5192613e73b0e0e94d4a2af927b 100644 --- a/interfaces/kits/js4.0/BUILD.gn +++ b/interfaces/kits/js4.0/BUILD.gn @@ -60,7 +60,6 @@ ohos_shared_library("distributeddevicemanager") { "ipc:ipc_core", "json:nlohmann_json_static", "napi:ace_napi", - "node:node_header_notice", ] subsystem_name = "distributedhardware" diff --git a/interfaces/kits/js4.0/include/dm_native_util.h b/interfaces/kits/js4.0/include/dm_native_util.h index c4d97572df809ed0f58eb6b540e28b2c848a06c7..5ddde1ede626cbfba3906031dd4a727a1fc7e085 100644 --- a/interfaces/kits/js4.0/include/dm_native_util.h +++ b/interfaces/kits/js4.0/include/dm_native_util.h @@ -32,7 +32,7 @@ namespace DistributedHardware { enum DMBussinessErrorCode { // Permission verify failed. ERR_NO_PERMISSION = 201, - //The caller is not a system application. + // The caller is not a system application. ERR_NOT_SYSTEM_APP = 202, // Input parameter error. ERR_INVALID_PARAMS = 401, diff --git a/interfaces/kits/js4.0/include/native_devicemanager_js.h b/interfaces/kits/js4.0/include/native_devicemanager_js.h index 2d1faa73f135cb9ec1d82cedd206eac72b08009c..4e2e12e1e4e469824b92f1757a93872318514fad 100644 --- a/interfaces/kits/js4.0/include/native_devicemanager_js.h +++ b/interfaces/kits/js4.0/include/native_devicemanager_js.h @@ -271,7 +271,8 @@ private: static int32_t BindTargetWarpper(const std::string &pkgName, const std::string &deviceId, const std::string &bindParam, std::shared_ptr callback); static void RegisterDevStatusCallback(napi_env env, std::string &bundleName); - + static int32_t DumpDeviceInfo(DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo); + private: napi_env env_; static thread_local napi_ref sConstructor_; diff --git a/interfaces/kits/js4.0/src/dm_native_event.cpp b/interfaces/kits/js4.0/src/dm_native_event.cpp index d0c3f9bb9afc10992136c4e2856f03d29f13e612..10d7dd77e5ada44c6e76d9ce973419ff7eec8878 100644 --- a/interfaces/kits/js4.0/src/dm_native_event.cpp +++ b/interfaces/kits/js4.0/src/dm_native_event.cpp @@ -30,6 +30,7 @@ DmNativeEvent::~DmNativeEvent() { for (auto iter = eventMap_.begin(); iter != eventMap_.end(); iter++) { auto listener = iter->second; + CHECK_NULL_VOID(listener); napi_delete_reference(env_, listener->handlerRef); } eventMap_.clear(); diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index bf6a82ec2afd4a2c3d3c05df753825c8c3a5e5b8..a3b0eb5c89dd848f077c41ea7b223f35d0590d56 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -40,10 +40,14 @@ const int32_t DM_NAPI_DISCOVER_EXTRA_INIT_ONE = -1; const int32_t DM_NAPI_DISCOVER_EXTRA_INIT_TWO = -2; const int32_t DM_NAPI_DESCRIPTION_BUF_LENGTH = 16384; const int32_t DM_NAPI_BUF_LENGTH = 256; +const int32_t MAX_OBJECT_LEN = 4096; void JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr, char *dest, const int32_t destLen) { + if (dest == nullptr || destLen < 0 || destLen > MAX_OBJECT_LEN) { + return; + } bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); if (hasProperty) { @@ -327,8 +331,7 @@ void JsToBindParam(const napi_env &env, const napi_value &object, std::string &b jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP); jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort; jsonObj[BIND_LEVEL] = bindLevel; - jsonObj[TOKENID] = OHOS::IPCSkeleton::GetSelfTokenID(); - bindParam = jsonObj.dump(); + bindParam = SafetyDump(jsonObj); } bool IsSystemApp() @@ -393,7 +396,7 @@ void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::st if (deviceType != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) { jsonObj["deviceType"] = deviceType; } - extra = jsonObj.dump(); + extra = SafetyDump(jsonObj); LOGI("JsToDmDiscoveryExtra, extra :%{public}s", extra.c_str()); } @@ -428,6 +431,10 @@ void InsertMapParames(nlohmann::json &bindParamObj, std::map(); bindParamMap.insert(std::pair(PARAM_KEY_AUTH_TOKEN, authToken)); } + if (IsInt32(bindParamObj, BIND_LEVEL)) { + int32_t bindLevel = bindParamObj[BIND_LEVEL].get(); + bindParamMap.insert(std::pair(BIND_LEVEL, std::to_string(bindLevel))); + } } bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, std::string &strValue) @@ -438,7 +445,10 @@ bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &value return false; } size_t valueLen = 0; - napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen); + napi_status stat = napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen); + if (stat != napi_ok) { + return false; + } if (!CheckArgsVal(env, valueLen > 0, valueName, "len == 0")) { return false; } @@ -446,7 +456,10 @@ bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &value return false; } char temp[DM_NAPI_BUF_LENGTH] = {0}; - napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + napi_status status = napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + if (status != napi_ok) { + return false; + } strValue = temp; return true; } diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp index e8a67d9203feb0b66d411141db11722a1807a21b..88e602eb947f32da7ec4f3b223e23f8d8510e0bc 100644 --- a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -54,6 +54,7 @@ const int32_t DM_NAPI_ARGS_ONE = 1; const int32_t DM_NAPI_ARGS_TWO = 2; const int32_t DM_NAPI_ARGS_THREE = 3; const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7; +const int32_t DM_MAX_DEVICE_SIZE = 100; napi_ref deviceStateChangeActionEnumConstructor_ = nullptr; @@ -989,16 +990,29 @@ void DmNapiBindTargetCallback::OnBindResult(const PeerTargetId &targetId, int32_ } } -void DeviceManagerNapi::CallGetAvailableDeviceListStatus(napi_env env, napi_status &status, +int32_t DeviceManagerNapi::DumpDeviceInfo( DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo) { + CHECK_NULL_RETURN(deviceBasicInfoListAsyncCallbackInfo, ERR_DM_POINT_NULL); + if (deviceBasicInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { + LOGE("CallGetAvailableDeviceListStatus invalid devList size"); + return DM_ERR_FAILED; + } for (unsigned int i = 0; i < deviceBasicInfoListAsyncCallbackInfo->devList.size(); i++) { - LOGI("DeviceManager::GetAvailableDeviceList deviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", + LOGI("DeviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", GetAnonyString(deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(), GetAnonyString(deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceName).c_str(), deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceTypeId); } + return DM_OK; +} +void DeviceManagerNapi::CallGetAvailableDeviceListStatus(napi_env env, napi_status &status, + DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo) +{ + if (DumpDeviceInfo(deviceBasicInfoListAsyncCallbackInfo) != DM_OK) { + return; + } napi_value array[DM_NAPI_ARGS_TWO] = {0}; bool isArray = false; NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &array[1])); @@ -1013,7 +1027,7 @@ void DeviceManagerNapi::CallGetAvailableDeviceListStatus(napi_env env, napi_stat } LOGI("devList is OK"); } else { - LOGE("devList is null"); //CB come here + LOGE("devList is null"); // CB come here } } else { array[0] = CreateBusinessError(env, deviceBasicInfoListAsyncCallbackInfo->ret, false); @@ -1096,7 +1110,7 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in napi_value DeviceManagerNapi::GetAvailableDeviceListSync(napi_env env, napi_callback_info info) { - LOGI("GetAvailableDeviceListSync in"); + LOGI("In"); int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); if (ret != 0) { CreateBusinessError(env, ret); @@ -1125,7 +1139,7 @@ napi_value DeviceManagerNapi::GetAvailableDeviceListSync(napi_env env, napi_call CreateBusinessError(env, ret); return result; } - LOGI("DeviceManager::GetAvailableDeviceListSync"); + LOGD("DeviceManager::GetAvailableDeviceListSync"); if (devList.size() > 0) { for (size_t i = 0; i != devList.size(); ++i) { DeviceBasicInfoToJsArray(env, devList, (int32_t)i, result); @@ -1887,7 +1901,7 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_info info) { - LOGI("CreateDeviceManager in"); + LOGI("In"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); if (!CheckArgsCount(env, argc == DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1")) { return nullptr; @@ -1921,7 +1935,7 @@ napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_in napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) { - LOGI("DeviceManagerNapi Constructor in"); + LOGI("In"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1")) { return nullptr; @@ -1931,7 +1945,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) return nullptr; } - LOGI("create DeviceManagerNapi for packageName:%{public}s", bundleName.c_str()); + LOGI("Create for packageName:%{public}s", bundleName.c_str()); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); if (obj == nullptr) { return nullptr; @@ -1940,7 +1954,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) obj->bundleName_ = bundleName; std::lock_guard autoLock(g_deviceManagerMapMutex); g_deviceManagerMap[obj->bundleName_] = obj; - napi_wrap( + napi_status status = napi_wrap( env, thisVar, reinterpret_cast(obj), [](napi_env env, void *data, void *hint) { (void)env; @@ -1951,6 +1965,12 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) LOGI("delete deviceManager"); }, nullptr, nullptr); + if (status != napi_ok) { + delete obj; + obj = nullptr; + LOGE("failed to wrap JS object"); + return nullptr; + } return thisVar; } diff --git a/radar/BUILD.gn b/radar/BUILD.gn index ebdd6420d2fae82d8cc7bf5a5dd0fd35d428782c..4df9d2608f731288103f55c97f4b1da8a3365f4c 100644 --- a/radar/BUILD.gn +++ b/radar/BUILD.gn @@ -25,7 +25,6 @@ if (defined(ohos_lite)) { "${common_path}/include", "${innerkits_path}/native_cpp/include", "${c_utils_path}/include", - "${utils_path}/include/crypto", "//third_party/cJSON", ] @@ -38,7 +37,6 @@ if (defined(ohos_lite)) { ] deps = [ - "${utils_path}:devicemanagerutils", "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", "//base/startup/init/interfaces/innerkits:libbegetutil", "//commonlibrary/utils_lite:utils", @@ -52,7 +50,6 @@ if (defined(ohos_lite)) { "include", "${common_path}/include", "${innerkits_path}/native_cpp/include", - "${utils_path}/include/crypto", ] sources = [ "src/dm_radar_helper.cpp" ] @@ -63,14 +60,16 @@ if (defined(ohos_lite)) { "LOG_DOMAIN=0xD004110", ] - deps = [ "${utils_path}:devicemanagerutils" ] - external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "cJSON:cjson", "c_utils:utils", "hilog:libhilog", "hisysevent:libhisysevent", "init:libbegetutil", + "ipc:ipc_core", + "ipc:ipc_single", ] subsystem_name = "distributedhardware" diff --git a/radar/include/dm_radar_helper.h b/radar/include/dm_radar_helper.h index f5bc49c295a1731f7cd1682dcedd5fe95c042275..66060c2caf67b2ea5ad1d5998168cef29740f889 100644 --- a/radar/include/dm_radar_helper.h +++ b/radar/include/dm_radar_helper.h @@ -35,12 +35,20 @@ const std::string DM_AUTHCATION_BEHAVIOR = "DM_AUTHCATION_BEHAVIOR"; constexpr int32_t SUBSYS_DISTRIBUTEDHARDWARE_DM = 204; constexpr int32_t INVALID_UDID_LENGTH = 10; constexpr int32_t SUBSTR_UDID_LENGTH = 5; -enum class BizScene : int32_t { +constexpr int32_t DEFAULT_STAGE = 1; +enum class DiscoverScene : int32_t { DM_DISCOVER = 0x1, - DM_AUTHCATION = 0x2, - DM_NETWORK = 0x3, - DM_DELET_TRUST_RELATION = 0x4, - DM_PIN_HOLDER = 0x5, + DM_GET_TRUST_DEVICE_LIST = 0x2, + DM_GET_LOCAL_DEVICE_INFO = 0x3, + DM_GET_DEVICE_INFO = 0x4, + DM_BEHAVIOR = 0x5, +}; + +enum class AuthScene : int32_t { + DM_AUTHCATION = 0x1, + DM_NETWORK = 0x2, + DM_DELET_TRUST_RELATION = 0x3, + DM_PIN_HOLDER = 0x4, }; enum class StageRes : int32_t { @@ -85,10 +93,11 @@ enum class DeleteTrust : int32_t { enum class PinHolderStage : int32_t { CREATE_PIN_HOLDER = 0x1, - SEND_CREATE_PIN_HOLDER_MSG = 0x2, - RECEIVE_CREATE_PIN_HOLDER_MSG = 0x3, - DESTROY_PIN_HOLDER = 0x4, - RECEIVE_DESTROY_PIN_HOLDER_MSG = 0x5, + SESSION_OPENED = 0x2, + SEND_CREATE_PIN_HOLDER_MSG = 0x3, + RECEIVE_CREATE_PIN_HOLDER_MSG = 0x4, + DESTROY_PIN_HOLDER = 0x5, + RECEIVE_DESTROY_PIN_HOLDER_MSG = 0x6, }; enum class GetTrustDeviceList : int32_t { @@ -100,6 +109,12 @@ enum class TrustStatus : int32_t { IS_TRUST = 0x1, }; +enum class ApiType : int32_t { + API_UNKNOW = 0x0, + API_JS = 0x1, + API_NATIVE = 0x2, +}; + enum class CommServ : int32_t { NOT_USE_SOFTBUS = 0x0, USE_SOFTBUS = 0x1, @@ -156,14 +171,19 @@ public: virtual bool ReportNetworkOnline(struct RadarInfo &info) = 0; virtual bool ReportNetworkOffline(struct RadarInfo &info) = 0; virtual bool ReportDeleteTrustRelation(struct RadarInfo &info) = 0; - virtual bool ReportGetTrustDeviceList(struct RadarInfo &info) = 0; + virtual void ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) = 0; virtual void ReportCreatePinHolder(std::string hostName, int32_t channelId, std::string peerUdid, int32_t errCode, int32_t stageRes) = 0; virtual void ReportDestroyPinHolder(std::string hostName, std::string peerUdid, int32_t errCode, int32_t stageRes) = 0; - virtual void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) = 0; + virtual void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) = 0; + virtual void ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) = 0; + virtual void ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) = 0; + virtual void ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) = 0; virtual std::string GetDeviceInfoList(std::vector &deviceInfoList) = 0; - virtual std::string GetUdidHashByUdid(std::string udid) = 0; }; class DmRadarHelper : public IDmRadarHelper { @@ -187,19 +207,25 @@ public: bool ReportNetworkOnline(struct RadarInfo &info) override; bool ReportNetworkOffline(struct RadarInfo &info) override; bool ReportDeleteTrustRelation(struct RadarInfo &info) override; - bool ReportGetTrustDeviceList(struct RadarInfo &info) override; + void ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) override; void ReportCreatePinHolder(std::string hostName, int32_t channelId, std::string peerUdid, int32_t errCode, int32_t stageRes) override; void ReportDestroyPinHolder(std::string hostName, std::string peerUdid, int32_t errCode, int32_t stageRes) override; - void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) override; + void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) override; + void ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) override; + void ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) override; + void ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) override; std::string GetDeviceInfoList(std::vector &deviceInfoList) override; - std::string GetUdidHashByUdid(std::string udid) override; std::string ConvertHexToString(uint16_t hex); int32_t GetErrCode(int32_t errCode); private: std::string GetAnonyUdid(std::string udid); - std::string GetLocalUdid(); + std::string GetAnonyLocalUdid(); + int32_t GetApiType(); }; extern "C" IDmRadarHelper *CreateDmRadarInstance(); diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index 946a9bf168f2bf83aaf280bfefba7c8b4c8f8e2c..e2e2c32d2184b7f49f319ba45ed709eb08082252 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -21,13 +21,17 @@ #include #include #include - #include "hisysevent.h" #include "dm_constants.h" -#include "dm_crypto.h" #include "dm_log.h" #include "parameter.h" - +#include "accesstoken_kit.h" +#include "access_token.h" +#include "hap_token_info.h" +#include "ipc_skeleton.h" +#include "native_token_info.h" +#include "tokenid_kit.h" +using namespace OHOS::Security::AccessToken; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DmRadarHelper); @@ -42,7 +46,8 @@ bool DmRadarHelper::ReportDiscoverRegCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -55,7 +60,8 @@ bool DmRadarHelper::ReportDiscoverRegCallback(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -81,11 +87,12 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", SOFTBUSNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "COMM_SERV", static_cast(CommServ::USE_SOFTBUS), "PEER_NET_ID", GetAnonyUdid(info.peerNetId)); } else { @@ -96,10 +103,13 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", SOFTBUSNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "COMM_SERV", static_cast(CommServ::USE_SOFTBUS), "ERROR_CODE", info.errCode); } @@ -122,7 +132,8 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -134,7 +145,8 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END)); @@ -146,7 +158,8 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -169,13 +182,14 @@ bool DmRadarHelper::ReportAuthStart(const std::string &peerUdid, const std::stri "ORG_PKG", ORGPKGNAME, "FUNC", "AuthenticateDevice", "HOST_PKG", pkgName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_START), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_START), "IS_TRUST", static_cast(TrustStatus::NOT_TRUST), - "PEER_UDID", GetUdidHashByUdid(peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid())); + "PEER_UDID", GetAnonyUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid()); if (res != DM_OK) { LOGE("ReportAuthStart error, res:%{public}d", res); return false; @@ -193,11 +207,11 @@ bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "STAGE_RES", info.stageRes, - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "CH_ID", info.channelId, "IS_TRUST", info.isTrust, "COMM_SERV", info.commServ, @@ -210,12 +224,12 @@ bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "BIZ_STATE", info.bizState, "STAGE_RES", info.stageRes, - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "CH_ID", info.channelId, "IS_TRUST", info.isTrust, "COMM_SERV", info.commServ, @@ -238,9 +252,11 @@ bool DmRadarHelper::ReportAuthSessionOpenCb(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "STAGE_RES", info.stageRes, + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "CH_ID", info.channelId); if (res != DM_OK) { LOGE("ReportAuthSessionOpenCb error, res:%{public}d", res); @@ -257,7 +273,7 @@ bool DmRadarHelper::ReportAuthSendRequest(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_SEND_REQUEST), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "TO_CALL_PKG", SOFTBUSNAME, @@ -279,7 +295,7 @@ bool DmRadarHelper::ReportAuthPullAuthBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_AUTH_BOX), "STAGE_RES", info.stageRes); if (res != DM_OK) { @@ -299,7 +315,7 @@ bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_AUTH_BOX), "STAGE_RES", info.stageRes); } else { @@ -309,7 +325,7 @@ bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_AUTH_BOX), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -332,10 +348,10 @@ bool DmRadarHelper::ReportAuthCreateGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", info.stageRes, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "TO_CALL_PKG", info.toCallPkg); } else { res = HiSysEventWrite( @@ -344,12 +360,12 @@ bool DmRadarHelper::ReportAuthCreateGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, "TO_CALL_PKG", info.toCallPkg, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "ERROR_CODE", info.errCode); } if (res != DM_OK) { @@ -369,7 +385,7 @@ bool DmRadarHelper::ReportAuthCreateGroupCb(std::string funcName, int32_t stageR HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", stageRes, "HOST_PKG", HICHAINNAME); @@ -380,7 +396,7 @@ bool DmRadarHelper::ReportAuthCreateGroupCb(std::string funcName, int32_t stageR HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", stageRes, "HOST_PKG", HICHAINNAME, @@ -402,7 +418,7 @@ bool DmRadarHelper::ReportAuthPullPinBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_PIN_BOX_START), "STAGE_RES", info.stageRes); if (res != DM_OK) { @@ -422,7 +438,7 @@ bool DmRadarHelper::ReportAuthInputPinBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_PIN_INPUT_BOX_END), "STAGE_RES", info.stageRes); } else { @@ -432,7 +448,7 @@ bool DmRadarHelper::ReportAuthInputPinBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_PIN_INPUT_BOX_END), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -455,11 +471,11 @@ bool DmRadarHelper::ReportAuthAddGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", info.stageRes, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "TO_CALL_PKG", HICHAINNAME); } else { res = HiSysEventWrite( @@ -468,11 +484,11 @@ bool DmRadarHelper::ReportAuthAddGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", info.stageRes, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "TO_CALL_PKG", HICHAINNAME, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "ERROR_CODE", info.errCode); @@ -494,7 +510,7 @@ bool DmRadarHelper::ReportAuthAddGroupCb(std::string funcName, int32_t stageRes) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -506,7 +522,7 @@ bool DmRadarHelper::ReportAuthAddGroupCb(std::string funcName, int32_t stageRes) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", stageRes, "HOST_PKG", HICHAINNAME, @@ -528,12 +544,12 @@ bool DmRadarHelper::ReportNetworkOnline(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_NETWORK), + "BIZ_SCENE", static_cast(AuthScene::DM_NETWORK), "BIZ_STAGE", static_cast(NetworkStage::NETWORK_ONLINE), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "PEER_NET_ID", GetAnonyUdid(info.peerNetId), "IS_TRUST", info.isTrust); if (res != DM_OK) { @@ -551,12 +567,12 @@ bool DmRadarHelper::ReportNetworkOffline(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_NETWORK), + "BIZ_SCENE", static_cast(AuthScene::DM_NETWORK), "BIZ_STAGE", static_cast(NetworkStage::NETWORK_OFFLINE), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "PEER_NET_ID", GetAnonyUdid(info.peerNetId)); if (res != DM_OK) { LOGE("ReportNetworkOffline error, res:%{public}d", res); @@ -574,12 +590,13 @@ bool DmRadarHelper::ReportDeleteTrustRelation(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DELET_TRUST_RELATION), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(AuthScene::DM_DELET_TRUST_RELATION), "BIZ_STAGE", static_cast(DeleteTrust::DELETE_TRUST), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "PEER_NET_ID", GetAnonyUdid(info.peerNetId), "TO_CALL_PKG", info.toCallPkg); if (res != DM_OK) { @@ -601,13 +618,14 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "CreatePinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::CREATE_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_START), "CH_ID", channelId, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportDeleteTrustRelation error, res:%{public}d", res); @@ -621,13 +639,14 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "CreatePinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::CREATE_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "CH_ID", channelId, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME, "ERROR_CODE", errCode); if (res != DM_OK) { @@ -650,11 +669,12 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "DestroyPinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportDeleteTrustRelation error, res:%{public}d", res); @@ -668,12 +688,13 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "DestroyPinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME, "ERROR_CODE", errCode); if (res != DM_OK) { @@ -684,7 +705,7 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, return; } -void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) +void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) { int32_t res = DM_OK; if (bizStage == static_cast(PinHolderStage::RECEIVE_DESTROY_PIN_HOLDER_MSG)) { @@ -694,10 +715,12 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", bizStage, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportSendOrReceiveHolderMsg error, res:%{public}d", res); @@ -710,9 +733,11 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", bizStage, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportSendOrReceiveHolderMsg error, res:%{public}d", res); @@ -722,42 +747,189 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f return; } -bool DmRadarHelper::ReportGetTrustDeviceList(struct RadarInfo &info) +void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) { int32_t res = DM_OK; - if (info.stageRes == static_cast(StageRes::STAGE_SUCC)) { + std::string discoverDevList = GetDeviceInfoList(deviceInfoList); + if (errCode == DM_OK) { + int32_t deviceCount = static_cast(deviceInfoList.size()); + static std::string TrustCallerName = ""; + if (deviceCount > 0 && TrustCallerName != hostName) { + TrustCallerName = hostName; + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_TRUST_DEVICE_LIST), + "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "DISCOVERY_DEVICE_LIST", discoverDevList); + } + } else { res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, - DM_AUTHCATION_BEHAVIOR, + DM_DISCOVER_BEHAVIOR, HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, - "FUNC", "GetTrustedDeviceList", - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_TRUST_DEVICE_LIST), "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), - "STAGE_RES", info.stageRes, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "DISCOVERY_DEVICE_LIST", info.discoverDevList); + "LOCAL_UDID", GetAnonyLocalUdid(), + "DISCOVERY_DEVICE_LIST", discoverDevList, + "ERROR_CODE", GetErrCode(errCode)); + } + if (res != DM_OK) { + LOGE("ReportGetTrustDeviceList error, res:%{public}d", res); + return; + } +} + +void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) +{ + int32_t res = DM_OK; + if (errCode == DM_OK) { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_BEHAVIOR), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid()); } else { res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, - DM_AUTHCATION_BEHAVIOR, + DM_DISCOVER_BEHAVIOR, HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, - "FUNC", "GetTrustedDeviceList", - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), - "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), - "STAGE_RES", info.stageRes, + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_BEHAVIOR), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "DISCOVERY_DEVICE_LIST", info.discoverDevList, - "ERROR_CODE", info.errCode); + "LOCAL_UDID", GetAnonyLocalUdid(), + "ERROR_CODE", GetErrCode(errCode)); } if (res != DM_OK) { - LOGE("ReportDeleteTrustRelation error, res:%{public}d", res); - return false; + LOGE("ReportDmBehavior error, res:%{public}d", res); + return; + } +} + +void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) +{ + int32_t res = DM_OK; + static std::string localCallerName = ""; + if (localCallerName != hostName) { + localCallerName = hostName; + if (errCode == DM_OK) { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_LOCAL_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), + "LOCAL_UDID", GetAnonyLocalUdid(), + "LOCAL_NET_ID", GetAnonyUdid(info.networkId)); + } else { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_LOCAL_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), + "LOCAL_UDID", GetAnonyLocalUdid(), + "LOCAL_NET_ID", GetAnonyUdid(info.networkId), + "ERROR_CODE", GetErrCode(errCode)); + } + } + if (res != DM_OK) { + LOGE("ReportGetLocalDevInfo error, res:%{public}d", res); + return; + } +} + +void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) +{ + int32_t res = DM_OK; + static std::string callerName = ""; + if (callerName != hostName) { + callerName = hostName; + if (errCode == DM_OK) { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), + "PEER_UDID", GetAnonyUdid(info.deviceId), + "PEER_NET_ID", GetAnonyUdid(info.networkId)); + } else { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "API_TYPE", GetApiType(), + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), + "PEER_UDID", GetAnonyUdid(info.deviceId), + "PEER_NET_ID", GetAnonyUdid(info.networkId), + "ERROR_CODE", GetErrCode(errCode)); + } + } + if (res != DM_OK) { + LOGE("ReportGetDeviceInfo error, res:%{public}d", res); + return; } - return true; } std::string DmRadarHelper::ConvertHexToString(uint16_t hex) @@ -784,13 +956,8 @@ std::string DmRadarHelper::GetDeviceInfoList(std::vector &deviceIn cJSON_Delete(deviceInfoJson); return ""; } - std::string udidHash = GetUdidHashByUdid(std::string(deviceInfoList[i].deviceId)); - cJSON_AddStringToObject(object, "PEER_UDID", udidHash.c_str()); - std::string peerNetId = GetAnonyUdid(deviceInfoList[i].networkId); - cJSON_AddStringToObject(object, "PEER_NET_ID", peerNetId.c_str()); std::string devType = ConvertHexToString(deviceInfoList[i].deviceTypeId); cJSON_AddStringToObject(object, "PEER_DEV_TYPE", devType.c_str()); - cJSON_AddStringToObject(object, "PEER_DEV_NAME", deviceInfoList[i].deviceName); cJSON_AddItemToArray(deviceInfoJson, object); } char *deviceInfoStr = cJSON_PrintUnformatted(deviceInfoJson); @@ -805,15 +972,6 @@ std::string DmRadarHelper::GetDeviceInfoList(std::vector &deviceIn return devInfoStr; } -std::string DmRadarHelper::GetUdidHashByUdid(std::string udid) -{ - char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetUdidHash(udid, reinterpret_cast(udidHash)) != DM_OK) { - return ""; - } - return GetAnonyUdid(std::string(udidHash)); -} - std::string DmRadarHelper::GetAnonyUdid(std::string udid) { if (udid.empty() || udid.length() < INVALID_UDID_LENGTH) { @@ -822,11 +980,11 @@ std::string DmRadarHelper::GetAnonyUdid(std::string udid) return udid.substr(0, SUBSTR_UDID_LENGTH) + "**" + udid.substr(udid.length() - SUBSTR_UDID_LENGTH); } -std::string DmRadarHelper::GetLocalUdid() +std::string DmRadarHelper::GetAnonyLocalUdid() { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - return std::string(localDeviceId); + return GetAnonyUdid(std::string(localDeviceId)); } int32_t DmRadarHelper::GetErrCode(int32_t errCode) @@ -838,6 +996,22 @@ int32_t DmRadarHelper::GetErrCode(int32_t errCode) return flag->second; } +int32_t DmRadarHelper::GetApiType() +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("GetApiType GetCallingTokenID error."); + return static_cast(ApiType::API_UNKNOW); + } + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_HAP) { + return static_cast(ApiType::API_JS); + } else if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + return static_cast(ApiType::API_NATIVE); + } + return static_cast(ApiType::API_UNKNOW); +} + IDmRadarHelper *CreateDmRadarInstance() { return &DmRadarHelper::GetInstance(); diff --git a/radar/src/lite/dm_radar_helper.cpp b/radar/src/lite/dm_radar_helper.cpp index 2106be41e3eff847aef50346b51054fc1062f302..091c5d7147375446ed2e4a6c0e9f691c06a36cd4 100644 --- a/radar/src/lite/dm_radar_helper.cpp +++ b/radar/src/lite/dm_radar_helper.cpp @@ -20,7 +20,6 @@ #include #include #include "dm_constants.h" -#include "dm_crypto.h" #include "dm_log.h" #include "parameter.h" @@ -117,9 +116,10 @@ bool DmRadarHelper::ReportDeleteTrustRelation(struct RadarInfo &info) return true; } -bool DmRadarHelper::ReportGetTrustDeviceList(struct RadarInfo &info) +void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) { - return true; + return; } void DmRadarHelper::ReportCreatePinHolder(std::string hostName, @@ -134,7 +134,24 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, return; } -void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) +void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) +{ + return; +} + +void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) +{ + return; +} + +void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) +{ + return; +} + +void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) { return; } @@ -151,27 +168,7 @@ std::string DmRadarHelper::ConvertHexToString(uint16_t hex) std::string DmRadarHelper::GetDeviceInfoList(std::vector &deviceInfoList) { - cJSON* deviceInfoJson = cJSON_CreateArray(); - for (size_t i = 0; i < deviceInfoList.size(); i++) { - cJSON* object = cJSON_CreateObject(); - std::string udidHash = GetUdidHashByUdid(std::string(deviceInfoList[i].deviceId)); - cJSON_AddStringToObject(object, "PEER_UDID", udidHash.c_str()); - cJSON_AddStringToObject(object, "PEER_NET_ID", deviceInfoList[i].networkId); - std::string devType = ConvertHexToString(deviceInfoList[i].deviceTypeId); - cJSON_AddStringToObject(object, "PEER_DEV_TYPE", devType.c_str()); - cJSON_AddStringToObject(object, "PEER_DEV_NAME", deviceInfoList[i].deviceName); - cJSON_AddItemToArray(deviceInfoJson, object); - } - return std::string(cJSON_PrintUnformatted(deviceInfoJson)); -} - -std::string DmRadarHelper::GetUdidHashByUdid(std::string udid) -{ - char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetUdidHash(udid, reinterpret_cast(udidHash)) != DM_OK) { - return ""; - } - return GetAnonyUdid(std::string(udidHash)); + return ""; } std::string DmRadarHelper::GetAnonyUdid(std::string udid) @@ -182,11 +179,11 @@ std::string DmRadarHelper::GetAnonyUdid(std::string udid) return udid.substr(0, SUBSTR_UDID_LENGTH) + "**" + udid.substr(udid.length() - SUBSTR_UDID_LENGTH); } -std::string DmRadarHelper::GetLocalUdid() +std::string DmRadarHelper::GetAnonyLocalUdid() { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - return std::string(localDeviceId); + return GetAnonyUdid(std::string(localDeviceId)); } int32_t DmRadarHelper::GetErrCode(int32_t errCode) diff --git a/sa_profile/device_manager.cfg b/sa_profile/device_manager.cfg index d69548366a7a3b40a10a35e14a967512ccd2b411..f0632a81e17c93caa585f4f1ae812562e461c6f8 100644 --- a/sa_profile/device_manager.cfg +++ b/sa_profile/device_manager.cfg @@ -1,17 +1,32 @@ { + "jobs":[{ + "name" : "service:device_manager", + "cmds" : [ + "mkdir /data/service/el1/public/database 0711 ddms ddms", + "mkdir /data/service/el1/public/database/distributed_device_manager_service 02770 device_manager ddms" + ] + } + ], "services" : [{ "name" : "device_manager", "path" : ["/system/bin/sa_main", "/system/profile/device_manager.json"], "uid" : "device_manager", - "gid" : ["device_manager"], - "start-mode" : "boot", + "gid" : ["device_manager", "access_token"], "apl" : "system_basic", + "start-on-demand" : { + "commonevent" : [ + { + "name" : "usual.event.BOOT_COMPLETED" + } + ] + }, "permission" : [ "ohos.permission.DISTRIBUTED_DATASYNC", "ohos.permission.DISTRIBUTED_SOFTBUS_CENTER", "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", "ohos.permission.ENABLE_DISTRIBUTED_HARDWARE", "ohos.permission.MANAGE_LOCAL_ACCOUNTS", + "ohos.permission.MANAGE_SECURE_SETTINGS", "ohos.permission.ACCESS_BLUETOOTH", "ohos.permission.MANAGE_BLUETOOTH", "ohos.permission.MANAGE_SETTINGS", @@ -20,8 +35,13 @@ "ohos.permission.GET_BUNDLE_RESOURCES", "ohos.permission.GET_WIFI_INFO", "ohos.permission.SET_TIME", - "ohos.permission.SET_TIME_ZONE" + "ohos.permission.SET_TIME_ZONE", + "ohos.permission.ALLOW_CONNECT_CAR", + "ohos.permission.ACCESS_SERVICE_DP" ], + "jobs" : { + "on-start" : "service:device_manager" + }, "secon" : "u:r:device_manager:s0" } ] diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 7fde856211c72d961a3800111efccc7f51a52d3a..737475f96f127a299b77ad6074528ff6b4e9dceb 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -168,6 +168,7 @@ if (defined(ohos_lite)) { "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/dependency/commonevent/dm_common_event_manager.cpp", + "src/dependency/deviceprofile/dp_inited_callback.cpp", "src/dependency/hichain/hichain_auth_connector.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/hichain/mine_hichain_connector.cpp", @@ -212,6 +213,7 @@ if (defined(ohos_lite)) { "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index f521c8f9af4bbc621081a07491d2638df2213914..e5eb58829b8e7c28cbcdfc9a3ea5493db6d99ab2 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -71,6 +71,8 @@ constexpr const char* TAG_DATA = "data"; constexpr const char* TAG_DATA_LEN = "dataLen"; constexpr const char* TAG_IMPORT_AUTH_CODE = "IMPORT_AUTH_CODE"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; +constexpr const char* TAG_EDITION = "edition"; +constexpr const char* TAG_BUNDLE_NAME = "bundleName"; class DmAuthManager; struct DmAuthRequestContext; @@ -107,8 +109,6 @@ private: void ParsePkgNegotiateMessage(const nlohmann::json &json); void CreatePublicKeyMessageExt(nlohmann::json &json); void ParsePublicKeyMessageExt(nlohmann::json &json); - void CreateSyncDeleteMessageExt(nlohmann::json &json); - void ParseSyncDeleteMessageExt(nlohmann::json &json); void GetJsonObj(nlohmann::json &jsonObj); private: diff --git a/services/implementation/include/authentication/auth_request_state.h b/services/implementation/include/authentication/auth_request_state.h index 21327c4ac7b1d48172371e544b6cb3eedf2d6e0c..05b4642dfe4545f1347c80674f6da2952c3e0055 100644 --- a/services/implementation/include/authentication/auth_request_state.h +++ b/services/implementation/include/authentication/auth_request_state.h @@ -193,24 +193,6 @@ public: int32_t GetStateType() override; int32_t Enter() override; }; - -class AuthRequestDeleteInit : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestSyncDeleteAcl : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestSyncDeleteAclNone : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_AUTH_REQUEST_STATE_H diff --git a/services/implementation/include/authentication/auth_response_state.h b/services/implementation/include/authentication/auth_response_state.h index 53c395f3f99cc3399f44d104a492052dfbd11934..c84a83aeb422c8f73b7725d5e1ce55d02bd5b1ae 100644 --- a/services/implementation/include/authentication/auth_response_state.h +++ b/services/implementation/include/authentication/auth_response_state.h @@ -112,18 +112,6 @@ public: int32_t GetStateType() override; int32_t Enter() override; }; - -class AuthResponseSyncDeleteAcl : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthResponseSyncDeleteAclNone : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_AUTH_RESPONSE_STATE_H diff --git a/services/implementation/include/authentication/auth_ui_state_manager.h b/services/implementation/include/authentication/auth_ui_state_manager.h index badf235d6e846e96dae919f76d1fe800a7d4aa30..2a7bdbc6d762a9ed90aece6608c5c9013c8a7f19 100644 --- a/services/implementation/include/authentication/auth_ui_state_manager.h +++ b/services/implementation/include/authentication/auth_ui_state_manager.h @@ -42,7 +42,7 @@ public: void UnRegisterUiStateCallback(const std::string pkgName); void UpdateUiState(const DmUiStateMsg msg); private: - std::set pkgSet_; + std::set pkgSet_; std::mutex pkgSetMutex_; std::shared_ptr listener_; }; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 4ae25cbd3224365d4ad07653fbf70f36ba0dace5..75d1875612cc03550732e50f4d20c947f46224e2 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -47,9 +47,6 @@ typedef enum AuthState { AUTH_REQUEST_FINISH, AUTH_REQUEST_CREDENTIAL, AUTH_REQUEST_CREDENTIAL_DONE, - AUTH_REQUEST_DELETE_INIT, - AUTH_REQUEST_SYNCDELETE, - AUTH_REQUEST_SYNCDELETE_DONE, AUTH_RESPONSE_INIT = 20, AUTH_RESPONSE_NEGOTIATE, @@ -58,8 +55,6 @@ typedef enum AuthState { AUTH_RESPONSE_SHOW, AUTH_RESPONSE_FINISH, AUTH_RESPONSE_CREDENTIAL, - AUTH_RESPONSE_SYNCDELETE, - AUTH_RESPONSE_SYNCDELETE_DONE, } AuthState; enum DmMsgType : int32_t { @@ -79,8 +74,6 @@ enum DmMsgType : int32_t { MSG_TYPE_RESP_AUTH_EXT, MSG_TYPE_REQ_PUBLICKEY, MSG_TYPE_RESP_PUBLICKEY, - MSG_TYPE_REQ_SYNC_DELETE, - MSG_TYPE_REQ_SYNC_DELETE_DONE, MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE = 600, MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE = 700, }; @@ -92,6 +85,7 @@ enum DmAuthType : int32_t { AUTH_TYPE_NFC, AUTH_TYPE_NO_INTER_ACTION, AUTH_TYPE_IMPORT_AUTH_CODE, + AUTH_TYPE_UNKNOW, }; typedef struct DmAuthRequestContext { @@ -109,6 +103,7 @@ typedef struct DmAuthRequestContext { std::string cryptoVer; std::string hostPkgName; std::string targetPkgName; + std::string bundleName; std::string appOperation; std::string appDesc; std::string appName; @@ -127,7 +122,7 @@ typedef struct DmAuthRequestContext { int64_t tokenId; std::string remoteAccountId; int32_t remoteUserId; - std::string ip; + std::string addr; std::string hostPkgLabel; } DmAuthRequestContext; @@ -151,6 +146,7 @@ typedef struct DmAuthResponseContext { std::string groupName; std::string hostPkgName; std::string targetPkgName; + std::string bundleName; std::string appOperation; std::string appDesc; std::string customDesc; @@ -172,6 +168,7 @@ typedef struct DmAuthResponseContext { std::string localAccountId; int32_t localUserId; int64_t tokenId; + int64_t remoteTokenId; bool authed; std::string dmVersion; std::vector bindType; @@ -181,6 +178,7 @@ typedef struct DmAuthResponseContext { std::string importAuthCode; std::string hostPkgLabel; bool isFinish = false; + std::string edition; } DmAuthResponseContext; class AuthMessageProcessor; @@ -209,7 +207,7 @@ public: * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); /** * @brief UnBind device. @@ -217,7 +215,7 @@ public: * @param deviceId device id. * @return Return 0 if success. */ - int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); /** * @tc.name: DmAuthManager::OnSessionOpened @@ -373,13 +371,6 @@ public: */ void HandleAuthenticateTimeout(std::string name); - /** - * @tc.name: DmAuthManager::CancelDisplay - * @tc.desc: Cancel Display of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void CancelDisplay(); - /** * @tc.name: DmAuthManager::GeneratePincode * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager @@ -415,13 +406,6 @@ public: */ int32_t OnUserOperation(int32_t action, const std::string ¶ms); - /** - * @tc.name: DmAuthManager::UserSwitchEventCallback - * @tc.desc: User Switch Event Callback of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void UserSwitchEventCallback(int32_t userId); - /** * @tc.name: DmAuthManager::SetPageId * @tc.desc: Set PageId of the DeviceManager Authenticate Manager @@ -476,6 +460,7 @@ public: private: int32_t CheckAuthParamVaild(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra); + int32_t CheckAuthParamVaildExtra(const std::string &extra); void ProcessSourceMsg(); void ProcessSinkMsg(); std::string GetAccountGroupIdHash(); @@ -492,57 +477,61 @@ private: void InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra); void CompatiblePutAcl(); - void ProRespNegotiateExt(const int32_t &sessionId); - void ProRespNegotiate(const int32_t &sessionId); - void AccountIdLogoutEventCallback(int32_t userId); - void UserChangeEventCallback(int32_t userId); + void ProcRespNegotiateExt(const int32_t &sessionId); + void ProcRespNegotiate(const int32_t &sessionId); void GetAuthRequestContext(); void SinkAuthDeviceFinish(); void SrcAuthDeviceFinish(); - void SrcSyncDeleteAclDone(); - void SinkSyncDeleteAclDone(); int32_t CheckTrustState(); + void ProcIncompatible(const int32_t &sessionId); + void MemberJoinAuthRequest(int64_t requestId, int32_t status); public: void RequestCredential(); void GenerateCredential(std::string &publicKey); void RequestCredentialDone(); - void RequestSyncDeleteAcl(); void ResponseCredential(); - void ResponseSyncDeleteAcl(); bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); void AuthDeviceFinish(int64_t requestId); void AuthDeviceError(int64_t requestId, int32_t errorCode); void GetRemoteDeviceId(std::string &deviceId); - int32_t EstablishUnbindChannel(const std::string &deviceIdHash); - void SyncDeleteAclDone(); void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); - void CommonEventCallback(int32_t userId, std::string commonEventType); void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); - void BindSocketSuccess(int32_t socket); - void BindSocketFail(); void OnScreenLocked(); void HandleDeviceNotTrust(const std::string &udid); + int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId); + int32_t StopAuthenticateDevice(const std::string &pkgName); private: int32_t ImportCredential(std::string &deviceId, std::string &publicKey); void GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra); - void HandleSyncDeleteTimeout(std::string name); - int32_t DeleteAcl(const std::string &pkgName, const std::string &deviceId); + int32_t DeleteAcl(const std::string &pkgName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel); void ProcessAuthRequestExt(const int32_t &sessionId); + bool IsAuthFinish(); void ProcessAuthRequest(const int32_t &sessionId); int32_t ConfirmProcess(const int32_t &action); int32_t ConfirmProcessExt(const int32_t &action); int32_t AddMember(int32_t pinCode); int32_t AuthDevice(int32_t pinCode); - void SyncDeleteAcl(const std::string &pkgName, const std::string &deviceId); - int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); void PutAccessControlList(); void SinkAuthenticateFinish(); void SrcAuthenticateFinish(); std::string GetBundleLable(const std::string &bundleName); bool IsScreenLocked(); + std::string ConvertSrcVersion(const std::string &version, const std::string &edition); + std::string ConvertSinkVersion(const std::string &version); + void NegotiateRespMsg(const std::string &version); + void SetAuthType(int32_t authType); + int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); + void GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash); + void DeleteOffLineTimer(int32_t sessionId); + bool IsAllowDeviceBind(); + int32_t GetBindLevel(int32_t bindLevel); + std::string GetBundleName(nlohmann::json &jsonObject); + int32_t GetBinderInfo(); + void SetProcessInfo(); private: std::shared_ptr softbusConnector_; @@ -552,6 +541,7 @@ private: std::shared_ptr adapterMgr_; std::map> authenticationMap_; std::shared_ptr authRequestState_ = nullptr; + std::shared_ptr authRequestStateTemp_ = nullptr; std::shared_ptr authResponseState_ = nullptr; std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; @@ -575,6 +565,10 @@ private: bool isAuthDevice_ = false; bool isAuthenticateDevice_ = false; int32_t authForm_ = DmAuthForm::ACROSS_ACCOUNT; + std::string remoteVersion_ = ""; + std::atomic authType_ = AUTH_TYPE_UNKNOW; + std::string remoteUdidHash_ = ""; + ProcessInfo processInfo_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/credential/dm_credential_manager.h b/services/implementation/include/credential/dm_credential_manager.h index b20c09bfbde9bff567b4a7051c0e54742e273efe..3b933fec6665a313add64938f8308603b71d60a7 100644 --- a/services/implementation/include/credential/dm_credential_manager.h +++ b/services/implementation/include/credential/dm_credential_manager.h @@ -95,7 +95,7 @@ public: int32_t DeleteCredential(const std::string &pkgName, const std::string &deleteInfo); /** - * @tc.name: HiChainConnector::OnCredentialResult + * @tc.name: HiChainConnector::OnGroupResult * @tc.desc: Credential Result of the DmCredential Manager * @tc.type: FUNC */ @@ -103,6 +103,7 @@ public: int32_t ImportRemoteCredentialExt(const std::string &credentialInfo); void OnGroupResultExt(int32_t action, const std::string &resultInfo); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); private: std::shared_ptr hiChainConnector_; @@ -110,7 +111,7 @@ private: std::vector credentialVec_; int64_t requestId_ = 0; std::mutex locks_; - std::string pkgName_; + ProcessInfo processInfo_; private: int32_t GetCredentialData(const std::string &credentialInfo, const CredentialData &inputCreData, nlohmann::json &jsonOutObj); diff --git a/services/implementation/include/dependency/deviceprofile/dp_inited_callback.h b/services/implementation/include/dependency/deviceprofile/dp_inited_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..24978b22012a02df915f53c280e79c7f23eb51bf --- /dev/null +++ b/services/implementation/include/dependency/deviceprofile/dp_inited_callback.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DP_INITED_LISTENER_H +#define OHOS_DP_INITED_LISTENER_H + +#include "dp_inited_callback_stub.h" +#include "dm_device_info.h" +#include "trusted_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class DpInitedCallback : public DistributedDeviceProfile::DpInitedCallbackStub { +public: + DpInitedCallback(); + ~DpInitedCallback(); + int32_t OnDpInited() override; +private: + void PutAllTrustedDevices(); + bool ConvertToTrustedDeviceInfo(const std::unordered_map &authFormMap, + const DmDeviceInfo &deviceInfo, DistributedDeviceProfile::TrustedDeviceInfo &trustedDeviceInfo); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DP_INITED_LISTENER_H \ No newline at end of file diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index c4e0e2df673c65155847ffc3dc50327fbb3210a0..c5b2c45e78685a00a9798512b3866fe28e15d1a0 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -166,8 +166,12 @@ public: * @tc.desc: Get GroupInfo of the HiChain Connector * @tc.type: FUNC */ - int32_t GetGroupInfo(const int32_t userId, const std::string &queryParams, std::vector &groupList); + bool GetGroupInfo(const int32_t userId, const std::string &queryParams, std::vector &groupList); + + bool GetGroupInfoExt(const int32_t userId, const std::string &queryParams, std::vector &groupList); + bool GetGroupInfoCommon(const int32_t userId, const std::string &queryParams, const char* pkgName, + std::vector &groupList); /** * @tc.name: HiChainConnector::GetGroupType * @tc.desc: Get GroupType of the HiChain Connector @@ -228,16 +232,21 @@ public: int32_t addMultiMembersExt(const std::string &credentialInfo); void DeleteAllGroup(int32_t userId); - - void DeleteP2PGroup(int32_t userId); - + int32_t GetRelatedGroups(int32_t userId, const std::string &deviceId, std::vector &groupList); int32_t GetRelatedGroupsExt(const std::string &deviceId, std::vector &groupList); int32_t DeleteGroupExt(std::string &groupId); int32_t GetRelatedGroupsCommon(const std::string &deviceId, const char* pkgName, std::vector &groupList); + int32_t GetRelatedGroupsCommon(int32_t userId, const std::string &deviceId, const char* pkgName, + std::vector &groupList); void DeleteAllGroupByUdid(const std::string &udid); + int32_t DeleteGroupByACL(std::vector> &delACLInfoVec, + std::vector &userIdVec); + bool IsNeedDelete(std::string &groupName, int32_t userId, + std::vector> &delACLInfoVec); + private: int64_t GenRequestId(); int32_t SyncGroups(std::string deviceId, std::vector &remoteGroupIdList); diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 099e7d791bd07b2b783840992bedf390acebdd59..49b417ce1911884303289e6e8b23127f4619926e 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -143,12 +143,13 @@ public: std::string GetNetworkIdByDeviceId(const std::string &deviceId); void HandleDeviceOnline(std::string deviceId, int32_t authForm); void HandleDeviceOffline(std::string deviceId); - void SetPkgName(std::string pkgName); + void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); - void SetPkgNameVec(std::vector pkgNameVec); - std::vector GetPkgName(); - void ClearPkgName(); + void SetProcessInfoVec(std::vector processInfoVec); + std::vector GetProcessInfo(); + void ClearProcessInfo(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); + void DeleteOffLineTimer(std::string &udidHash); private: static void ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo); @@ -162,6 +163,7 @@ private: ALLOW_BE_DISCOVERY = 1, NOT_ALLOW_BE_DISCOVERY = 2, }; + static std::string remoteUdidHash_; static PulishStatus publishStatus; static IRefreshCallback softbusDiscoveryCallback_; static IRefreshCallback softbusDiscoveryByIdCallback_; @@ -175,11 +177,11 @@ private: std::shared_ptr deviceStateManagerCallback_; static std::queue discoveryDeviceIdQueue_; static std::unordered_map deviceUdidMap_; - static std::vector pkgNameVec_; + static std::vector processInfoVec_; static std::mutex discoveryCallbackMutex_; static std::mutex discoveryDeviceInfoMutex_; static std::mutex deviceUdidLocks_; - static std::mutex pkgNameVecMutex_; + static std::mutex processInfoVecMutex_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/dependency/softbus/softbus_discovery_callback.h b/services/implementation/include/dependency/softbus/softbus_discovery_callback.h index 72ac4280ae15a31de330f20336b29536e82c89c0..6457d1a49a6a3d9e350604975091f85a2df0a8d7 100644 --- a/services/implementation/include/dependency/softbus/softbus_discovery_callback.h +++ b/services/implementation/include/dependency/softbus/softbus_discovery_callback.h @@ -22,7 +22,13 @@ class ISoftbusDiscoveryCallback { public: virtual void OnDeviceFound(const std::string &pkgName, DmDeviceInfo &info, bool isOnline) = 0; virtual void OnDeviceFound(const std::string &pkgName, DmDeviceBasicInfo &info, - const int32_t range, bool isOnline) {}; + const int32_t range, bool isOnline) + { + (void)pkgName; + (void)info; + (void)range; + (void)isOnline; + }; virtual void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) = 0; virtual void OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) = 0; }; diff --git a/services/implementation/include/dependency/softbus/softbus_session.h b/services/implementation/include/dependency/softbus/softbus_session.h index b78281ac8a0e20e7e0bd0a3cd7ce3f4b29ea0c59..99387bb7618119b0596fd902370fec8c7c563128 100644 --- a/services/implementation/include/dependency/softbus/softbus_session.h +++ b/services/implementation/include/dependency/softbus/softbus_session.h @@ -34,7 +34,6 @@ public: static int OnSessionOpened(int sessionId, int result); static void OnSessionClosed(int sessionId); static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); - static void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); public: SoftbusSession(); @@ -81,8 +80,6 @@ public: * @tc.type: FUNC */ int32_t GetPeerDeviceId(int32_t sessionId, std::string &peerDevId); - int32_t OpenUnbindSession(const std::string &netWorkId); - int32_t CloseUnbindSession(int32_t socket); int32_t SendHeartbeatData(int32_t sessionId, std::string &message); private: diff --git a/services/implementation/include/dependency/softbus/softbus_session_callback.h b/services/implementation/include/dependency/softbus/softbus_session_callback.h index d267f26b2e26b57e9fb1e26a2dce369ee7cf3899..c3f90824c69b07fd167772c4df368563b4216084 100644 --- a/services/implementation/include/dependency/softbus/softbus_session_callback.h +++ b/services/implementation/include/dependency/softbus/softbus_session_callback.h @@ -24,10 +24,7 @@ public: virtual void OnSessionClosed(int32_t sessionId) = 0; virtual void OnDataReceived(int32_t sessionId, std::string message) = 0; virtual bool GetIsCryptoSupport() = 0; - virtual void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) = 0; virtual void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) = 0; - virtual void BindSocketSuccess(int32_t socket) = 0; - virtual void BindSocketFail() = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/dependency/softbus/softbus_state_callback.h b/services/implementation/include/dependency/softbus/softbus_state_callback.h index 70ac7f3c93dec60b00cb82902347a66c802ef87e..b80a27bde518ee5aecf08799c4cb705897519f7d 100644 --- a/services/implementation/include/dependency/softbus/softbus_state_callback.h +++ b/services/implementation/include/dependency/softbus/softbus_state_callback.h @@ -22,6 +22,7 @@ class ISoftbusStateCallback { public: virtual void OnDeviceOnline(std::string deviceId, int32_t authForm) = 0; virtual void OnDeviceOffline(std::string deviceId) = 0; + virtual void DeleteOffLineTimer(std::string udidHash) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 09d1fe4ea8d268204e53931492a94aefb77438fd..12c09caa2e893218d9627bc80903feb27b2dfd2f 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -28,6 +28,7 @@ #include "dm_device_state_manager.h" #include "dm_discovery_manager.h" #include "dm_publish_manager.h" +#include "dp_inited_callback.h" #include "idevice_manager_service_impl.h" #include "dm_single_instance.h" #include "softbus_connector.h" @@ -56,15 +57,9 @@ public: int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId); - int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); - - int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam); - - int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); @@ -123,25 +118,44 @@ public: const std::map &bindParam); std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); - void OnUnbindSessionCloseed(int32_t socket); - void OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen); int32_t DpAclAdd(const std::string &udid); int32_t IsSameAccount(const std::string &udid); - void AccountCommonEventCallback(int32_t userId, std::string commonEventType); void ScreenCommonEventCallback(std::string commonEventType); int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); void HandleDeviceNotTrust(const std::string &udid); + int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId); + void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, + int32_t peerUserId); + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + int32_t StopAuthenticateDevice(const std::string &pkgName); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); + void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid); + void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId); + std::multimap GetDeviceIdAndUserId(int32_t localUserId); + int32_t SaveOnlineDeviceInfo(const std::vector &deviceList); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); void HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo); void HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo); void PutIdenticalAccountToAcl(std::string requestDeviceId, std::string trustDeviceId); + std::map GetDeviceIdAndBindLevel(int32_t userId); + std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId); + void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid); + void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); + void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); + void HandleUserRemoved(int32_t preUserId); + void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); + DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); private: std::shared_ptr authMgr_; @@ -155,6 +169,9 @@ private: std::shared_ptr credentialMgr_; std::shared_ptr commonEventManager_; std::shared_ptr hiChainAuthConnector_; + std::shared_ptr listener_; + std::atomic isCredentialType_ = false; + sptr dpInitedCallback_ = nullptr; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index b7c7de380866a9866e1ebed34e94c671d116e989..3c7fa5d01bb505f910e9ccfe53ffba9f6f2aded5 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -50,16 +50,10 @@ public: int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId); - int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); - - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); - - int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam); - - int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); void HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo); @@ -122,20 +116,37 @@ public: int32_t DestroyPinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload); std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); - void OnUnbindSessionOpened(int32_t sessionId, PeerSocketInfo info); - void OnUnbindSessionCloseed(int32_t sessionId); - void OnUnbindBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); int32_t DpAclAdd(const std::string &udid); int32_t IsSameAccount(const std::string &udid); - void AccountCommonEventCallback(int32_t userId, std::string commonEventType); void ScreenCommonEventCallback(std::string commonEventType); int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); void HandleDeviceNotTrust(const std::string &udid); - + int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId); + std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId); + void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid); + void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); + void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); + void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, + int32_t peerUserId); + void HandleUserRemoved(int32_t preUserId); + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId); + int32_t StopAuthenticateDevice(const std::string &pkgName); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); + void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid); + void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); + std::map GetDeviceIdAndBindLevel(int32_t userId); + std::multimap GetDeviceIdAndUserId(int32_t localUserId); + int32_t SaveOnlineDeviceInfo(const std::vector &deviceList); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index bf4e4d7d897dcfd42b1f3385c0a98aa276c50975..8e6806ef456bfab8f58703b0e0723e344f332ba5 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -94,7 +94,8 @@ public: void OnDeviceOffline(std::string deviceId); std::string GetUdidByNetWorkId(std::string networkId); bool CheckIsOnline(const std::string &udid); - + void DeleteOffLineTimer(std::string udidHash); + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); private: void StartEventThread(); void StopEventThread(); @@ -115,6 +116,7 @@ private: std::map remoteDeviceInfos_; std::map stateDeviceInfos_; std::map stateTimerInfoMap_; + std::map udidhash2udidMap_; std::shared_ptr timer_; std::shared_ptr hiChainConnector_; std::shared_ptr hiChainAuthConnector_; diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 54fdd0d0bdc03ff2b138bc60cdac4a3eb0451159..28cbb121feb788d2b413dcb7a6d9face52a6c083 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -26,6 +26,9 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "dm_single_instance.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -111,12 +114,16 @@ void DmDialogManager::ShowPinDialog(const std::string param) bundleName_ = DM_UI_BUNDLE_NAME; abilityName_ = PIN_ABILITY_NAME; pinCode_ = param; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([]() { ConnectExtension(); }); +#else std::thread pinDilog([]() { ConnectExtension(); }); int32_t ret = pthread_setname_np(pinDilog.native_handle(), CONNECT_PIN_DIALOG.c_str()); if (ret != DM_OK) { LOGE("pinDilog setname failed."); } pinDilog.detach(); +#endif } void DmDialogManager::ShowInputDialog(const std::string param) @@ -194,7 +201,8 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param["deviceType"] = DmDialogManager::GetDeviceType(); param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); - std::string paramStr = param.dump(); + param["disableUpGesture"] = 1; + std::string paramStr = SafetyDump(param); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index d3ef269869623b2a1f586c1212ee135644c55d37..e7a2cb9028b22769afca9e1c84f89faba2ce8974 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -42,6 +42,10 @@ AuthMessageProcessor::~AuthMessageProcessor() void AuthMessageProcessor::GetJsonObj(nlohmann::json &jsonObj) { + if (authResponseContext_ == nullptr || authResponseContext_->bindType.size() > MAX_BINDTYPE_SIZE) { + LOGE("GetJsonObj invalid bindType size."); + return; + } jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH; jsonObj[TAG_INDEX] = 0; @@ -83,7 +87,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1; jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; GetJsonObj(jsonObj); - jsonStrVec.push_back(jsonObj.dump()); + jsonStrVec.push_back(SafetyDump(jsonObj)); for (int32_t idx = 0; idx < thumbnailSlice; idx++) { nlohmann::json jsonThumbnailObj; jsonThumbnailObj[TAG_VER] = DM_ITF_VER; @@ -97,7 +101,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() LOGI("TAG_APP_THUMBNAIL encode, idx %{public}d, sliceLen %{public}d, thumbnailSize %{public}d", idx, (uint32_t)sliceLen, thumbnailSize); jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); - jsonStrVec.push_back(jsonThumbnailObj.dump()); + jsonStrVec.push_back(SafetyDump(jsonThumbnailObj)); } return jsonStrVec; } @@ -125,27 +129,16 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) CreateResponseAuthMessageExt(jsonObj); break; case MSG_TYPE_REQ_AUTH_TERMINATE: - case MSG_TYPE_REQ_SYNC_DELETE_DONE: CreateResponseFinishMessage(jsonObj); break; case MSG_TYPE_REQ_PUBLICKEY: case MSG_TYPE_RESP_PUBLICKEY: CreatePublicKeyMessageExt(jsonObj); break; - case MSG_TYPE_REQ_SYNC_DELETE: - CreateSyncDeleteMessageExt(jsonObj); - break; default: break; } - return jsonObj.dump(); -} - -void AuthMessageProcessor::CreateSyncDeleteMessageExt(nlohmann::json &json) -{ - json[TAG_LOCAL_DEVICE_ID] = authResponseContext_->localDeviceId; - json[TAG_HOST_PKGNAME] = authResponseContext_->hostPkgName; - json[TAG_REPLY] = DM_OK; + return SafetyDump(jsonObj); } void AuthMessageProcessor::CreatePublicKeyMessageExt(nlohmann::json &json) @@ -183,10 +176,12 @@ void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) json[TAG_AUTHED] = authResponseContext_->authed; json[TAG_DMVERSION] = authResponseContext_->dmVersion; json[TAG_HOST] = authResponseContext_->hostPkgName; + json[TAG_BUNDLE_NAME] = authResponseContext_->bundleName; json[TAG_TOKENID] = authResponseContext_->tokenId; json[TAG_IDENTICAL_ACCOUNT] = authResponseContext_->isIdenticalAccount; json[TAG_HAVE_CREDENTIAL] = authResponseContext_->haveCredential; json[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; + json[TAG_EDITION] = authResponseContext_->edition; } void AuthMessageProcessor::CreateRespNegotiateMessage(nlohmann::json &json) @@ -207,6 +202,7 @@ void AuthMessageProcessor::CreateRespNegotiateMessage(nlohmann::json &json) json[TAG_LOCAL_ACCOUNTID] = authResponseContext_->localAccountId; json[TAG_LOCAL_USERID] = authResponseContext_->localUserId; + json[TAG_TOKENID] = authResponseContext_->tokenId; json[TAG_ISONLINE] = authResponseContext_->isOnline; json[TAG_AUTHED] = authResponseContext_->authed; json[TAG_DMVERSION] = authResponseContext_->dmVersion; @@ -293,35 +289,18 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) ParseAuthResponseMessageExt(jsonObject); break; case MSG_TYPE_REQ_AUTH_TERMINATE: - case MSG_TYPE_REQ_SYNC_DELETE_DONE: ParseResponseFinishMessage(jsonObject); break; case MSG_TYPE_REQ_PUBLICKEY: case MSG_TYPE_RESP_PUBLICKEY: ParsePublicKeyMessageExt(jsonObject); break; - case MSG_TYPE_REQ_SYNC_DELETE: - ParseSyncDeleteMessageExt(jsonObject); - break; default: break; } return DM_OK; } -void AuthMessageProcessor::ParseSyncDeleteMessageExt(nlohmann::json &json) -{ - if (IsString(json, TAG_LOCAL_DEVICE_ID)) { - authResponseContext_->localDeviceId = json[TAG_LOCAL_DEVICE_ID].get(); - } - if (IsString(json, TAG_HOST_PKGNAME)) { - authResponseContext_->hostPkgName = json[TAG_HOST_PKGNAME].get(); - } - if (IsInt32(json, TAG_REPLY)) { - authResponseContext_->reply = json[TAG_REPLY].get(); - } -} - void AuthMessageProcessor::ParsePublicKeyMessageExt(nlohmann::json &json) { if (IsString(json, TAG_PUBLICKEY)) { @@ -485,7 +464,7 @@ void AuthMessageProcessor::ParsePkgNegotiateMessage(const nlohmann::json &json) authResponseContext_->authed = json[TAG_AUTHED].get(); } if (IsInt64(json, TAG_TOKENID)) { - authResponseContext_->tokenId = json[TAG_TOKENID].get(); + authResponseContext_->remoteTokenId = json[TAG_TOKENID].get(); } if (IsString(json, TAG_DMVERSION)) { authResponseContext_->dmVersion = json[TAG_DMVERSION].get(); @@ -545,6 +524,12 @@ void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) if (IsString(json, TAG_HOST)) { authResponseContext_->hostPkgName = json[TAG_HOST].get(); } + if (IsString(json, TAG_EDITION)) { + authResponseContext_->edition = json[TAG_EDITION].get(); + } + if (IsString(json, TAG_BUNDLE_NAME)) { + authResponseContext_->bundleName = json[TAG_BUNDLE_NAME].get(); + } ParsePkgNegotiateMessage(json); } @@ -608,7 +593,7 @@ std::string AuthMessageProcessor::CreateDeviceAuthMessage(int32_t msgType, const std::string authDataStr = std::string(reinterpret_cast(data), dataLen); jsonObj[TAG_DATA] = authDataStr; jsonObj[TAG_DATA_LEN] = dataLen; - return jsonObj.dump(); + return SafetyDump(jsonObj); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_request_state.cpp b/services/implementation/src/authentication/auth_request_state.cpp index 1d479538ae72aae1591f9e68ebe240b6783f78b9..7181d29470a0bce50db328800e0953c0081b97af 100644 --- a/services/implementation/src/authentication/auth_request_state.cpp +++ b/services/implementation/src/authentication/auth_request_state.cpp @@ -172,7 +172,7 @@ int32_t AuthRequestFinishState::Enter() return DM_OK; } -//pkgbind +// pkgbind int32_t AuthRequestCredential::GetStateType() { return AuthState::AUTH_REQUEST_CREDENTIAL; @@ -204,53 +204,5 @@ int32_t AuthRequestCredentialDone::Enter() stateAuthManager->RequestCredentialDone(); return DM_OK; } - -int32_t AuthRequestDeleteInit::GetStateType() -{ - return AuthState::AUTH_REQUEST_DELETE_INIT; -} - -int32_t AuthRequestDeleteInit::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return ERR_DM_FAILED; - } - stateAuthManager->EstablishUnbindChannel(context_->deviceId); - return DM_OK; -} - -int32_t AuthRequestSyncDeleteAcl::GetStateType() -{ - return AuthState::AUTH_REQUEST_SYNCDELETE; -} - -int32_t AuthRequestSyncDeleteAcl::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return ERR_DM_FAILED; - } - stateAuthManager->RequestSyncDeleteAcl(); - return DM_OK; -} - -int32_t AuthRequestSyncDeleteAclNone::GetStateType() -{ - return AuthState::AUTH_REQUEST_SYNCDELETE_DONE; -} - -int32_t AuthRequestSyncDeleteAclNone::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return ERR_DM_FAILED; - } - stateAuthManager->SyncDeleteAclDone(); - return DM_OK; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_response_state.cpp b/services/implementation/src/authentication/auth_response_state.cpp index fae9f86ebaff387322f04fcbe3365c2823e937dc..7f1803fa0414bca0b27d141b842c267002d5173c 100644 --- a/services/implementation/src/authentication/auth_response_state.cpp +++ b/services/implementation/src/authentication/auth_response_state.cpp @@ -162,43 +162,11 @@ int32_t AuthResponseCredential::Enter() { std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { - LOGE("AuthResponseFinishState authManager_ is null"); + LOGE("AuthResponseCredential authManager_ is null"); return ERR_DM_FAILED; } stateAuthManager->ResponseCredential(); return DM_OK; } - -int32_t AuthResponseSyncDeleteAcl::GetStateType() -{ - return AuthState::AUTH_RESPONSE_SYNCDELETE; -} - -int32_t AuthResponseSyncDeleteAcl::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthResponseFinishState authManager_ is null"); - return ERR_DM_FAILED; - } - stateAuthManager->ResponseSyncDeleteAcl(); - return DM_OK; -} - -int32_t AuthResponseSyncDeleteAclNone::GetStateType() -{ - return AuthState::AUTH_RESPONSE_SYNCDELETE_DONE; -} - -int32_t AuthResponseSyncDeleteAclNone::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthResponseFinishState authManager_ is null"); - return ERR_DM_FAILED; - } - stateAuthManager->SyncDeleteAclDone(); - return DM_OK; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index ab4d5e415eadf376eb60fb4bb5d2765c0408aa14..ed9e95d7af5c18c54ff0f6f5910a962cc6ee2d82 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -14,9 +14,12 @@ */ #include "auth_ui_state_manager.h" +#include "dm_anonymous.h" #include "dm_log.h" #include "nlohmann/json.hpp" - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { constexpr const char* UI_STATE_MSG = "uiStateMsg"; @@ -27,18 +30,28 @@ AuthUiStateManager::AuthUiStateManager(std::shared_ptr lock(pkgSetMutex_); - pkgSet_.emplace(pkgName); + pkgSet_.emplace(processInfo); } void AuthUiStateManager::UnRegisterUiStateCallback(const std::string pkgName) { + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = pkgName; std::lock_guard lock(pkgSetMutex_); - if (pkgSet_.find(pkgName) == pkgSet_.end()) { - LOGE("AuthUiStateManager UnRegisterUiStateCallback pkgName is not exist."); + if (pkgSet_.find(processInfo) == pkgSet_.end()) { + LOGE("AuthUiStateManager UnRegisterUiStateCallback processInfo is not exist."); return; } - pkgSet_.erase(pkgName); + pkgSet_.erase(processInfo); } void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) @@ -49,10 +62,10 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) } nlohmann::json jsonObj; jsonObj[UI_STATE_MSG] = msg; - std::string paramJson = jsonObj.dump(); + std::string paramJson = SafetyDump(jsonObj); std::lock_guard lock(pkgSetMutex_); - for (auto pkgName : pkgSet_) { - listener_->OnUiCall(pkgName, paramJson); + for (auto item : pkgSet_) { + listener_->OnUiCall(item, paramJson); } LOGI("AuthUiStateManager::UpdateUiState complete."); } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index d2221fc044e589b010d6750a0fc565b9e5cf9ce2..a7772eb63753190f5f8a358b5789fdc64d28a164 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -15,6 +15,7 @@ #include "dm_auth_manager.h" +#include #include #include #include @@ -26,6 +27,7 @@ #endif #include "system_ability_definition.h" +#include "app_manager.h" #include "auth_message_processor.h" #include "common_event_support.h" #include "dm_ability_manager.h" @@ -41,6 +43,9 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "show_confirm.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -51,6 +56,13 @@ const int32_t INPUT_TIMEOUT = 60; const int32_t ADD_TIMEOUT = 10; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; const int32_t DEVICE_ID_HALF = 2; const int32_t MAX_AUTH_TIMES = 3; @@ -61,18 +73,31 @@ const int32_t MAX_PIN_CODE = 999999; const int32_t DM_AUTH_TYPE_MAX = 5; const int32_t DM_AUTH_TYPE_MIN = 0; const int32_t AUTH_SESSION_SIDE_SERVER = 0; -const int32_t USLEEP_TIME_MS = 500000; // 500ms -const int32_t SYNC_DELETE_TIMEOUT = 60; +const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms const int32_t AUTH_DEVICE_TIMEOUT = 10; const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; +const int32_t STRTOLL_BASE_10 = 10; + +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; -constexpr const char* DM_VERSION = "4.1.5.1"; -constexpr const char* DM_NEW_VERSION = "5.0.1"; +constexpr const char* BUNDLE_NAME_KEY = "bundleName"; +constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; +constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; +constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; std::mutex g_authFinishLock; DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, @@ -88,7 +113,7 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, authUiStateMgr_ = std::make_shared(listener_); authenticationMap_[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; authenticationMap_[AUTH_TYPE_CRE] = nullptr; - dmVersion_ = DM_NEW_VERSION; + dmVersion_ = DM_VERSION_5_0_2; } DmAuthManager::~DmAuthManager() @@ -116,30 +141,50 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a if (!IsAuthTypeSupported(authType)) { LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_UNSUPPORTED_AUTH_TYPE); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_UNSUPPORTED_AUTH_TYPE; } if (authRequestState_ != nullptr || authResponseState_ != nullptr) { LOGE("DmAuthManager::CheckAuthParamVaild %{public}s is request authentication.", pkgName.c_str()); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_AUTH_BUSINESS_BUSY); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_AUTH_BUSINESS_BUSY, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_AUTH_BUSINESS_BUSY; } if (!softbusConnector_->HaveDeviceInMap(deviceId)) { LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_INPUT_PARA_INVALID); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_INPUT_PARA_INVALID; } if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(pkgName))) { LOGE("Auth code not exist."); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_INPUT_PARA_INVALID); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra) +{ + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (jsonObject.is_discarded() || jsonObject.find(TAG_BIND_LEVEL) == jsonObject.end() || + !IsInt32(jsonObject, TAG_BIND_LEVEL)) { + return DM_OK; + } + int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { + LOGE("bindlevel error %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (static_cast(bindLevel) == DEVICE && !IsAllowDeviceBind()) { + LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); return ERR_DM_INPUT_PARA_INVALID; } return DM_OK; @@ -159,12 +204,13 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId(); authRequestContext_->localDeviceId = localUdid; authRequestContext_->deviceId = deviceId; - authRequestContext_->ip = deviceId; - authRequestContext_->dmVersion = DM_NEW_VERSION; - authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); - MultipleUserConnector::SetSwitchOldAccountId(authRequestContext_->localAccountId); - authRequestContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); - MultipleUserConnector::SetSwitchOldUserId(authRequestContext_->localUserId); + authRequestContext_->addr = deviceId; + authRequestContext_->dmVersion = DM_VERSION_5_0_2; + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId); + authRequestContext_->tokenId = static_cast(tokenId); + authRequestContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); authRequestContext_->isOnline = false; authRequestContext_->authed = !authRequestContext_->bindType.empty(); authRequestContext_->bindLevel = INVALIED_TYPE; @@ -182,25 +228,27 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, if (IsString(jsonObject, APP_THUMBNAIL)) { authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); } - if (IsInt64(jsonObject, TAG_TOKENID)) { - authRequestContext_->tokenId = jsonObject[TAG_TOKENID].get(); - } if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { authRequestContext_->bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } + authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); } + authRequestContext_->bundleName = GetBundleName(jsonObject); authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); } void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - authPtr_ = authenticationMap_[authType]; + if (authenticationMap_.find(authType) != authenticationMap_.end()) { + authPtr_ = authenticationMap_[authType]; + } + if (timer_ == nullptr) { timer_ = std::make_shared(); } - timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), AUTHENTICATE_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); authMessageProcessor_ = std::make_shared(shared_from_this()); @@ -211,7 +259,7 @@ void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, authRequestState_ = std::make_shared(); authRequestState_->SetAuthManager(shared_from_this()); authRequestState_->SetAuthContext(authRequestContext_); - if (!DmRadarHelper::GetInstance().ReportAuthStart(deviceId, pkgName)) { + if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) { LOGE("ReportAuthStart failed"); } authRequestState_->Enter(); @@ -222,122 +270,164 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au const std::string &deviceId, const std::string &extra) { LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + processInfo_.pkgName = pkgName; + processInfo_.userId = userId; int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); if (ret != DM_OK) { LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild."); return ret; } + ret = CheckAuthParamVaildExtra(extra); + if (ret != DM_OK) { + LOGE("CheckAuthParamVaildExtra failed, param is invaild."); + return ret; + } isAuthenticateDevice_ = true; if (authType == AUTH_TYPE_CRE) { LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly."); softbusConnector_->JoinLnn(deviceId); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); - listener_->OnBindResult(pkgName, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); return DM_OK; } InitAuthState(pkgName, authType, deviceId, extra); return DM_OK; } -int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) +int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_FAILED; } - if (authRequestState_!= nullptr || authResponseContext_ != nullptr) { - if (isAuthenticateDevice_) { - LOGI("Stop previous AuthenticateDevice."); - authRequestContext_->reason = STOP_BIND; - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestState_->TransitionTo(std::make_shared()); - return DM_OK; - } else { - LOGE("UnBindDevice is syncchronizing sink acl data."); - return ERR_DM_FAILED; - } - } - std::string deviceUdid = ""; - int32_t ret = SoftbusConnector::GetUdidByNetworkId(networkId.c_str(), deviceUdid); - if (ret != DM_OK) { - LOGE("UnAuthenticateDevice GetNodeKeyInfo failed"); - return ret; - } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); struct RadarInfo info = { .funcName = "UnAuthenticateDevice", .toCallPkg = HICHAINNAME, .hostName = pkgName, - .peerNetId = networkId, - .localUdid = localDeviceId, - .peerUdid = deviceUdid, + .peerUdid = udid, }; if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) { LOGE("ReportDeleteTrustRelation failed"); } - if (!DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, deviceUdid)) { - LOGE("The pkgName %{public}s cannot unbind.", pkgName.c_str()); - return ERR_DM_FAILED; + remoteDeviceId_ = udid; + if (bindLevel == DEVICE) { + DeleteGroup(pkgName, udid); } - remoteDeviceId_ = deviceUdid; - SyncDeleteAcl(pkgName, deviceUdid); - return DM_OK; + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel); } -int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udidHash) +int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) { - if (pkgName.empty()) { + if (pkgName.empty() || authRequestContext_ == nullptr || authResponseContext_ == nullptr) { LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) || + (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) && + isAuthenticateDevice_) { + LOGI("Stop previous AuthenticateDevice."); + authRequestContext_->reason = STOP_BIND; + authResponseContext_->state = authRequestState_->GetStateType(); + authResponseContext_->reply = STOP_BIND; + authRequestState_->TransitionTo(std::make_shared()); + } + return DM_OK; +} + +int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel) +{ + LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the pkgname bind data."); return ERR_DM_FAILED; } - if (authRequestState_!= nullptr || authResponseContext_ != nullptr) { - if (isAuthenticateDevice_) { - LOGI("Stop previous AuthenticateDevice."); - authRequestContext_->reason = STOP_BIND; - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestState_->TransitionTo(std::make_shared()); + if (bindLevel == APP) { + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (offlineParam.leftAclNumber != 0) { + LOGI("The pkgName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return DM_OK; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The pkgName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); return DM_OK; - } else { - LOGE("UnBindDevice is syncchronizing sink acl data."); - return ERR_DM_FAILED; } } - remoteDeviceId_ = SoftbusConnector::GetDeviceUdidByUdidHash(udidHash); + if (bindLevel == DEVICE && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + return DM_OK; + } + if (bindLevel == DEVICE && offlineParam.leftAclNumber == 0) { + LOGI("Unbind deivce-level, retain null."); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + return ERR_DM_FAILED; +} + +int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - if (!DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId_)) { - LOGE("The pkgname %{public}s cannot unbind.", pkgName.c_str()); - return ERR_DM_FAILED; + if (bindLevel == DEVICE) { + DeleteGroup(pkgName, udid); } - SyncDeleteAcl(pkgName, remoteDeviceId_); - return DM_OK; + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel); } -void DmAuthManager::SyncDeleteAcl(const std::string &pkgName, const std::string &deviceId) +void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash) { - LOGI("SyncDeleteAcl start."); - authMessageProcessor_ = std::make_shared(shared_from_this()); - authResponseContext_ = std::make_shared(); - authRequestContext_ = std::make_shared(); + std::string peerUdid = ""; + int32_t ret = softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); + if (ret != DM_OK) { + LOGE("DmAuthManager::GetPeerUdidHash failed."); + peerUdidHash = ""; + return; + } + char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(peerUdid, reinterpret_cast(udidHashTmp)) != DM_OK) { + LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(peerUdid).c_str()); + peerUdidHash = ""; + return; + } + peerUdidHash = std::string(udidHashTmp); +} - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = static_cast(localDeviceId); - authRequestContext_->localDeviceId = localUdid; - authRequestContext_->hostPkgName = pkgName; - authRequestContext_->deviceId = deviceId; - authMessageProcessor_->SetRequestContext(authRequestContext_); - authRequestState_ = std::make_shared(); - authRequestState_->SetAuthManager(shared_from_this()); - authRequestState_->SetAuthContext(authRequestContext_); - authRequestState_->Enter(); +void DmAuthManager::DeleteOffLineTimer(int32_t sessionId) +{ + GetPeerUdidHash(sessionId, remoteUdidHash_); + if (remoteUdidHash_.empty()) { + LOGE("DeleteOffLineTimer remoteUdidHash is empty."); + return; + } + if (softbusConnector_ != nullptr) { + softbusConnector_->DeleteOffLineTimer(remoteUdidHash_); + } } void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { LOGI("DmAuthManager::OnSessionOpened, sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); + DeleteOffLineTimer(sessionId); if (sessionSide == AUTH_SESSION_SIDE_SERVER) { if (authResponseState_ == nullptr && authRequestState_ == nullptr) { authMessageProcessor_ = std::make_shared(shared_from_this()); @@ -348,12 +438,12 @@ void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int3 if (timer_ == nullptr) { timer_ = std::make_shared(); } - timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), AUTHENTICATE_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); - timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), WAIT_NEGOTIATE_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), + GetTaskTimeout(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } else { @@ -372,10 +462,8 @@ void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int3 authMessageProcessor_->SetRequestContext(authRequestContext_); authRequestState_->SetAuthContext(authRequestContext_); authRequestState_->TransitionTo(std::make_shared()); - struct RadarInfo info = { - .funcName = "OnSessionOpened", - .channelId = sessionId, - }; + struct RadarInfo info = { .funcName = "OnSessionOpened" }; + info.channelId = sessionId; if (!DmRadarHelper::GetInstance().ReportAuthSendRequest(info)) { LOGE("ReportAuthSendRequest failed"); } @@ -422,13 +510,6 @@ void DmAuthManager::ProcessSourceMsg() authRequestState_->TransitionTo(std::make_shared()); } break; - case MSG_TYPE_REQ_SYNC_DELETE_DONE: - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_SYNCDELETE) { - timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK)); - isFinishOfLocal_ = false; - authRequestState_->TransitionTo(std::make_shared()); - } - break; default: break; } @@ -443,18 +524,18 @@ void DmAuthManager::ProcessSinkMsg() switch (authResponseContext_->msgType) { case MSG_TYPE_NEGOTIATE: if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { - timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); + } authResponseState_->TransitionTo(std::make_shared()); - } else { - LOGE("Device manager auth state error"); } break; case MSG_TYPE_REQ_AUTH: if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { - timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + } authResponseState_->TransitionTo(std::make_shared()); - } else { - LOGE("Device manager auth state error"); } break; case MSG_TYPE_REQ_AUTH_TERMINATE: @@ -468,18 +549,6 @@ void DmAuthManager::ProcessSinkMsg() authResponseState_->TransitionTo(std::make_shared()); } break; - case MSG_TYPE_REQ_SYNC_DELETE: - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { - authResponseState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_REQ_SYNC_DELETE_DONE: - if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_SYNCDELETE) { - timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK)); - isFinishOfLocal_ = false; - authResponseState_->TransitionTo(std::make_shared()); - } - break; default: break; } @@ -540,13 +609,14 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId jsonObj[PIN_TOKEN] = authResponseContext_->token; jsonObj[QR_CODE_KEY] = GenerateGroupName(); jsonObj[NFC_CODE_KEY] = GenerateGroupName(); - authResponseContext_->authToken = jsonObj.dump(); + authResponseContext_->authToken = SafetyDump(jsonObj); LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); authResponseContext_->groupId = groupId; authResponseContext_->code = pinCode; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + authResponseContext_->isFinish = true; authResponseState_->TransitionTo(std::make_shared()); } @@ -559,42 +629,59 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) } LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_); if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { - HandleMemberJoinImportAuthCode(requestId, status); - return; - } - authTimes_++; - timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); - if (status != DM_OK || authResponseContext_->requestId != requestId) { - if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { - authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; - authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; - authRequestState_->TransitionTo(std::make_shared()); - } else { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); - } - } else { - authRequestState_->TransitionTo(std::make_shared()); - timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); - } + MemberJoinAuthRequest(requestId, status); } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { if (status == DM_OK && authResponseContext_->requestId == requestId && authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + } else { + if (++authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->isFinish = false; + } } } else { LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid."); } } +void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status) +{ + authTimes_++; + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); + } + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + HandleMemberJoinImportAuthCode(requestId, status); + return; + } + if (status != DM_OK || authResponseContext_->requestId != requestId) { + if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR; + authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; + authRequestState_->TransitionTo(std::make_shared()); + return; + } + if (timer_ != nullptr) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } else { + authRequestState_->TransitionTo(std::make_shared()); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + } + } +} + void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status) { if (status != DM_OK || authResponseContext_->requestId != requestId) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; authRequestState_->TransitionTo(std::make_shared()); } else { @@ -611,6 +698,7 @@ void DmAuthManager::HandleAuthenticateTimeout(std::string name) } authResponseContext_->state = authRequestState_->GetStateType(); authRequestContext_->reason = ERR_DM_TIME_OUT; + authResponseContext_->reply = ERR_DM_TIME_OUT; authRequestState_->TransitionTo(std::make_shared()); } @@ -625,8 +713,6 @@ void DmAuthManager::HandleAuthenticateTimeout(std::string name) int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) { int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); struct RadarInfo info = { .funcName = "EstablishAuthChannel", .stageRes = (sessionId > 0) ? @@ -637,8 +723,7 @@ int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) .peerSessName = DM_SESSION_NAME, .isTrust = static_cast(TrustStatus::NOT_TRUST), .commServ = static_cast(CommServ::USE_SOFTBUS), - .localUdid = localDeviceId, - .peerUdid = deviceId, + .peerUdid = peerTargetId_.deviceId, .channelId = sessionId, .errCode = sessionId, }; @@ -651,6 +736,10 @@ int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) authResponseContext_ = std::make_shared(); } authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE; + authResponseContext_->reply = sessionId; + if (authRequestContext_ == nullptr) { + authRequestContext_ = std::make_shared(); + } authRequestContext_->reason = sessionId; if (authRequestState_ != nullptr) { authRequestState_->TransitionTo(std::make_shared()); @@ -672,6 +761,7 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authResponseContext_->deviceId = authRequestContext_->deviceId; authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash(); authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; + authResponseContext_->bundleName = authRequestContext_->bundleName; authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel; authResponseContext_->tokenId = authRequestContext_->tokenId; authResponseContext_->bindLevel = authRequestContext_->bindLevel; @@ -682,13 +772,16 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authResponseContext_->localAccountId = authRequestContext_->localAccountId; authResponseContext_->localUserId = authRequestContext_->localUserId; authResponseContext_->isIdenticalAccount = false; + authResponseContext_->edition = DM_VERSION_5_0_2; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), NEGOTIATE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } } void DmAuthManager::AbilityNegotiate() @@ -698,7 +791,7 @@ void DmAuthManager::AbilityNegotiate() bool ret = hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, localDeviceId); if (ret) { LOGE("DmAuthManager::EstablishAuthChannel device is in group"); - if (!DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(authResponseContext_->hostPkgName, + if (!DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(authResponseContext_->hostPkgName, authResponseContext_->localDeviceId)) { CompatiblePutAcl(); } @@ -735,49 +828,86 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) remoteDeviceId_ = authResponseContext_->localDeviceId; authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId(); authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); - if (authResponseContext_->dmVersion == "") { - authResponseContext_->dmVersion = dmVersion_; - } else if (authResponseContext_->dmVersion == DM_VERSION) { + remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); + NegotiateRespMsg(remoteVersion_); + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { + ProcRespNegotiateExt(sessionId); + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { + ProcRespNegotiate(sessionId); + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } else { + ProcIncompatible(sessionId); + } +} + +void DmAuthManager::NegotiateRespMsg(const std::string &version) +{ + if (version == DM_VERSION_5_0_1) { + authResponseContext_->dmVersion = DM_VERSION_5_0_1; + } else if (version < DM_VERSION_5_0_1) { authResponseContext_->dmVersion = ""; authResponseContext_->bindLevel = INVALIED_TYPE; + } else if (version > DM_VERSION_5_0_1) { + authResponseContext_->dmVersion = dmVersion_; } - LOGI("RespNegotiate dmversion %{public}s, level %{public}d", - authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { - ProRespNegotiateExt(sessionId); - } else { - ProRespNegotiate(sessionId); - } - timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); } void DmAuthManager::SendAuthRequest(const int32_t &sessionId) { + LOGI("DmAuthManager::SendAuthRequest sessionId %{public}d.", sessionId); if (authResponseContext_ == nullptr) { LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr"); return; } - LOGI("DmAuthManager::SendAuthRequest session id"); + if (authResponseContext_->reply == ERR_DM_VERSION_INCOMPATIBLE) { + LOGE("The peer device version is not supported"); + authRequestContext_->reason = authResponseContext_->reply; + authRequestState_->TransitionTo(std::make_shared()); + return; + } remoteDeviceId_ = authResponseContext_->localDeviceId; - timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + } if (authResponseContext_->cryptoSupport) { isCryptoSupport_ = true; } LOGI("SendAuthRequest dmversion %{public}s, level %{public}d", authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { ProcessAuthRequestExt(sessionId); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { ProcessAuthRequest(sessionId); + } else { + LOGE("Invalied bind mode."); } } void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) { LOGI("ProcessAuthRequest start."); + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { + if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } + } + if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) { authResponseContext_->isOnline = true; } else { @@ -793,11 +923,11 @@ void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); } - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); - listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); - timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), CONFIRM_TIMEOUT, - [this] (std::string name) { + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); + timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } @@ -829,51 +959,77 @@ void DmAuthManager::GetAuthRequestContext() void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) { LOGI("ProcessAuthRequestExt start."); + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { + if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } + } + GetAuthRequestContext(); std::vector bindType = DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName, authResponseContext_->bindType, authResponseContext_->localDeviceId, authResponseContext_->deviceId); authResponseContext_->authed = !bindType.empty(); + if (authResponseContext_->isOnline && authResponseContext_->authed && + authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + (authResponseContext_->importAuthCode.empty() || importAuthCode_.empty())) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } authResponseContext_->bindType = bindType; + if (IsAuthFinish()) { + return; + } + + std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); + for (auto msg : messageList) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + } + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); + timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); +} + +bool DmAuthManager::IsAuthFinish() +{ if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) { - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); authRequestState_->TransitionTo(std::make_shared()); - return; + return true; } if (authResponseContext_->isOnline && authResponseContext_->authed) { authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); - return; + return true; } if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) || (authResponseContext_->authed && !authResponseContext_->isOnline)) { - softbusConnector_->JoinLnn(authRequestContext_->deviceId); + softbusConnector_->JoinLnn(authRequestContext_->addr); authRequestContext_->reason = DM_OK; + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); - return; + return true; } if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && authResponseContext_->isAuthCodeReady == false)) { authRequestState_->TransitionTo(std::make_shared()); - return; - } - - std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); - for (auto msg : messageList) { - softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + return true; } - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); - listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); - timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), CONFIRM_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + return false; } int32_t DmAuthManager::ConfirmProcess(const int32_t &action) @@ -941,10 +1097,15 @@ int32_t DmAuthManager::StartAuthProcess(const int32_t &action) if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { LOGE("ReportAuthConfirmBox failed"); } - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { return ConfirmProcessExt(action); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { return ConfirmProcess(action); + } else { + LOGE("Invalied bind mode."); } return DM_OK; } @@ -956,30 +1117,32 @@ void DmAuthManager::StartRespAuthProcess() return; } LOGI("DmAuthManager::StartRespAuthProcess sessionId = %{public}d", authResponseContext_->sessionId); - timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + } if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ALWAYS) { action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; } else if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ONCE) { action_ = USER_OPERATION_TYPE_ALLOW_AUTH; } if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); - timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), SESSION_HEARTBEAT_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleSessionHeartbeat(name); }); - listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK); - listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, DM_OK, - STATUS_DM_SHOW_PIN_INPUT_UI, ""); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_PIN_INPUT_UI, ""); authRequestState_->TransitionTo(std::make_shared()); } else { LOGE("do not accept"); authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY; authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT; + authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; authRequestState_->TransitionTo(std::make_shared()); } } @@ -1004,18 +1167,22 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) return ERR_DM_FAILED; } LOGI("DmAuthManager::AddMember start group id %{public}s", GetAnonyString(authResponseContext_->groupId).c_str()); - timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + } nlohmann::json jsonObject; jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId; jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName; jsonObject[PIN_CODE_KEY] = pinCode; jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; - std::string connectInfo = jsonObject.dump(); - timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), ADD_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + std::string connectInfo = SafetyDump(jsonObject); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), + GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } if (authUiStateMgr_ == nullptr) { LOGE("DmAuthManager::AddMember authUiStateMgr is null."); return ERR_DM_FAILED; @@ -1026,7 +1193,7 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) return ERR_DM_FAILED; } isAddingMember_ = true; - int32_t ret = hiChainConnector_->AddMember(authRequestContext_->ip, connectInfo); + int32_t ret = hiChainConnector_->AddMember(authRequestContext_->addr, connectInfo); struct RadarInfo info = { .funcName = "AddMember", .stageRes = (ret == 0) ? @@ -1061,10 +1228,13 @@ int32_t DmAuthManager::JoinNetwork() return ERR_DM_FAILED; } LOGI("DmAuthManager JoinNetwork start"); - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authResponseContext_->isFinish = true; authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); return DM_OK; } @@ -1072,6 +1242,9 @@ int32_t DmAuthManager::JoinNetwork() void DmAuthManager::SinkAuthenticateFinish() { LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); + processInfo_.pkgName = authResponseContext_->hostPkgName; + listener_->OnSinkBindResult(processInfo_, peerTargetId_, authResponseContext_->reply, + authResponseContext_->state, GenerateBindResultContent()); if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && authPtr_ != nullptr) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_CONFIRM_SHOW); @@ -1098,11 +1271,11 @@ void DmAuthManager::SrcAuthenticateFinish() authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) && authPtr_ != nullptr) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); } - listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); - listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, authRequestContext_->reason, + usleep(USLEEP_TIME_US_500000); // 500ms + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + authResponseContext_->state, authRequestContext_->reason); + listener_->OnBindResult(processInfo_, peerTargetId_, authRequestContext_->reason, authResponseContext_->state, GenerateBindResultContent()); - usleep(USLEEP_TIME_MS); // 500ms softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); authRequestContext_ = nullptr; authRequestState_ = nullptr; @@ -1111,6 +1284,7 @@ void DmAuthManager::SrcAuthenticateFinish() void DmAuthManager::AuthenticateFinish() { + authType_ = AUTH_TYPE_UNKNOW; std::lock_guard autoLock(g_authFinishLock); if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) { LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr"); @@ -1119,11 +1293,12 @@ void DmAuthManager::AuthenticateFinish() LOGI("DmAuthManager::AuthenticateFinish start"); isAddingMember_ = false; isAuthenticateDevice_ = false; + isAuthDevice_ = false; if (authResponseContext_->isFinish) { CompatiblePutAcl(); } if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 && - authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel == INVALIED_TYPE && + CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) { softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } @@ -1134,24 +1309,17 @@ void DmAuthManager::AuthenticateFinish() } else if (authRequestState_ != nullptr) { SrcAuthenticateFinish(); } - timer_->DeleteAll(); + if (timer_ != nullptr) { + timer_->DeleteAll(); + } isFinishOfLocal_ = true; authResponseContext_ = nullptr; authMessageProcessor_ = nullptr; authPtr_ = nullptr; + authRequestStateTemp_ = nullptr; LOGI("DmAuthManager::AuthenticateFinish complete"); } -void DmAuthManager::CancelDisplay() -{ - LOGI("DmAuthManager::CancelDisplay start"); - nlohmann::json jsonObj; - jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PIN_CODE_DISPLAY; - std::string paramJson = jsonObj.dump(); - std::string pkgName = "com.ohos.devicemanagerui"; - listener_->OnUiCall(pkgName, paramJson); -} - int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName) { LOGI("DmAuthManager::RegisterUiStateCallback start"); @@ -1225,6 +1393,8 @@ int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr aut LOGE("authRequestState is nullptr."); return ERR_DM_INPUT_PARA_INVALID; } + // Keep current state, avoid deconstructed during state transitions + authRequestStateTemp_ = authRequestState_; authRequestState_ = authRequestState; return DM_OK; } @@ -1243,7 +1413,6 @@ int32_t DmAuthManager::GetPinCode(int32_t &code) { if (authResponseContext_ == nullptr) { LOGE("failed to GetPinCode because authResponseContext_ is nullptr"); - code = ERR_DM_AUTH_NOT_START; return ERR_DM_FAILED; } LOGI("ShowConfigDialog start add member pin code."); @@ -1272,7 +1441,7 @@ void DmAuthManager::ShowConfigDialog() jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; - const std::string params = jsonObj.dump(); + const std::string params = SafetyDump(jsonObj); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); @@ -1309,7 +1478,7 @@ void DmAuthManager::ShowAuthInfoDialog() } nlohmann::json jsonObj; jsonObj[PIN_CODE_KEY] = authResponseContext_->code; - std::string authParam = jsonObj.dump(); + std::string authParam = SafetyDump(jsonObj); DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); } @@ -1326,10 +1495,15 @@ void DmAuthManager::ShowStartAuthDialog() LOGE("failed to get auth code"); return; } - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { AuthDevice(pinCode); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { AddMember(pinCode); + } else { + LOGE("Invalied bind mode."); } return; } @@ -1348,12 +1522,20 @@ int32_t DmAuthManager::ProcessPincode(int32_t pinCode) LOGE("failed to ProcessPincode because authResponseContext_ is nullptr"); return ERR_DM_FAILED; } - timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + } + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { return AuthDevice(pinCode); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { return AddMember(pinCode); + } else { + LOGE("Invalied bind mode."); } + return ERR_DM_FAILED; } int32_t DmAuthManager::AuthDevice(int32_t pinCode) @@ -1366,10 +1548,13 @@ int32_t DmAuthManager::AuthDevice(int32_t pinCode) } isAuthDevice_ = true; int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT, + [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } if (hiChainAuthConnector_->AuthDevice(pinCode, osAccountId, remoteDeviceId_, authResponseContext_->requestId) != DM_OK) { LOGE("DmAuthManager::AuthDevice failed."); @@ -1421,7 +1606,7 @@ int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms } break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: - ProcessPincode(std::stoi(params)); + ProcessPincode(std::atoi(params.c_str())); info.stageRes = static_cast(StageRes::STAGE_SUCC); if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { LOGE("ReportAuthInputPinBox failed"); @@ -1465,7 +1650,7 @@ bool DmAuthManager::IsIdenticalAccount() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1505,7 +1690,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1520,7 +1705,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() for (auto &groupInfo : groupList) { jsonAccountObj.push_back(Crypto::GetGroupIdHash(groupInfo.groupId)); } - return jsonAccountObj.dump(); + return SafetyDump(jsonAccountObj); } int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) @@ -1578,7 +1763,7 @@ int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::strin if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { LOGI("DmAuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); if (!addrType.empty()) { - addr.type = static_cast(std::stoi(addrType)); + addr.type = static_cast(std::atoi(addrType.c_str())); } else { addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; } @@ -1639,7 +1824,7 @@ int32_t DmAuthManager::ParseAuthType(const std::map &b LOGE("DmAuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); return ERR_DM_INPUT_PARA_INVALID; } - authType = std::stoi(authTypeStr); + authType = std::atoi(authTypeStr.c_str()); return DM_OK; } @@ -1684,7 +1869,7 @@ int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, int32_t &pinCode) LOGE("GetAuthCode failed, pkgName not supported."); return ERR_DM_FAILED; } - pinCode = std::stoi(importAuthCode_); + pinCode = std::atoi(importAuthCode_.c_str()); return DM_OK; } @@ -1708,7 +1893,7 @@ std::string DmAuthManager::GenerateBindResultContent() Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); jsonObj[TAG_DEVICE_ID] = deviceIdHash; } - std::string content = jsonObj.dump(); + std::string content = SafetyDump(jsonObj); return content; } @@ -1745,10 +1930,13 @@ void DmAuthManager::RequestCredentialDone() if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) { LOGE("ResponseCredential import credential failed."); } - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); - softbusConnector_->JoinLnn(authRequestContext_->ip); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } + softbusConnector_->JoinLnn(authRequestContext_->addr); authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); } @@ -1759,100 +1947,6 @@ int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publ return hiChainAuthConnector_->ImportCredential(osAccountId, deviceId, publicKey); } -int32_t DmAuthManager::EstablishUnbindChannel(const std::string &deviceIdHash) -{ - LOGI("DmAuthManager::EstablishUnbindChannel"); - std::string netWorkId = softbusConnector_->GetNetworkIdByDeviceId(deviceIdHash); - int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenUnbindSession(netWorkId); - if (sessionId < 0) { - LOGE("OpenAuthSession failed, stop the syncdeleteacl."); - authResponseContext_ = std::make_shared(); - authResponseContext_->state = AuthState::AUTH_REQUEST_SYNCDELETE; - authRequestContext_->reason = sessionId; - if (authRequestState_ != nullptr) { - authRequestState_->TransitionTo(std::make_shared()); - } - } - return DM_OK; -} - -void DmAuthManager::RequestSyncDeleteAcl() -{ - LOGI("RequestSyncDeleteAcl start."); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE); - softbusConnector_->GetSoftbusSession()->SendData(authRequestContext_->sessionId, message); - if (timer_ == nullptr) { - timer_ = std::make_shared(); - } - timer_->StartTimer(std::string(SYNC_DELETE_TIMEOUT_TASK), SYNC_DELETE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleSyncDeleteTimeout(name); - }); -} - -void DmAuthManager::SrcSyncDeleteAclDone() -{ - LOGI("DmAuthManager::SrcSyncDeleteAclDone, isFinishOfLocal: %{public}d", isFinishOfLocal_); - if (isFinishOfLocal_) { - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - usleep(USLEEP_TIME_MS); - } - if (authResponseContext_->reply == DM_OK) { - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) && - DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(authResponseContext_->hostPkgName, - remoteDeviceId_)) { - DeleteGroup(authResponseContext_->hostPkgName, remoteDeviceId_); - } - DeleteAcl(authResponseContext_->hostPkgName, remoteDeviceId_); - } - softbusConnector_->GetSoftbusSession()->CloseUnbindSession(authRequestContext_->sessionId); - timer_->DeleteAll(); - isFinishOfLocal_ = true; - authRequestContext_ = nullptr; - authResponseContext_ = nullptr; - authRequestState_ = nullptr; - authMessageProcessor_ = nullptr; -} - -void DmAuthManager::SinkSyncDeleteAclDone() -{ - LOGI("DmAuthManager::SinkSyncDeleteAclDone, isFinishOfLocal: %{public}d", isFinishOfLocal_); - if (isFinishOfLocal_) { - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - if (authResponseContext_->reply == DM_OK) { - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) && - DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(authResponseContext_->hostPkgName, - remoteDeviceId_)) { - DeleteGroup(authResponseContext_->hostPkgName, remoteDeviceId_); - } - DeleteAcl(authResponseContext_->hostPkgName, remoteDeviceId_); - } - } - timer_->DeleteAll(); - isFinishOfLocal_ = true; - authResponseContext_ = nullptr; - authResponseState_ = nullptr; - authMessageProcessor_ = nullptr; -} - -void DmAuthManager::SyncDeleteAclDone() -{ - LOGI("SyncDeleteAclDone start."); - if (authRequestState_ != nullptr) { - SrcSyncDeleteAclDone(); - } else if (authResponseState_ != nullptr) { - SinkSyncDeleteAclDone(); - } -} - void DmAuthManager::ResponseCredential() { LOGI("DmAuthManager::ResponseCredential start."); @@ -1866,14 +1960,6 @@ void DmAuthManager::ResponseCredential() softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } -void DmAuthManager::ResponseSyncDeleteAcl() -{ - LOGI("ResponseSyncDeleteAcl start."); - timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK)); - remoteDeviceId_ = authResponseContext_->localDeviceId; - authResponseState_->TransitionTo(std::make_shared()); -} - bool DmAuthManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) { LOGI("DmAuthManager::onTransmit start."); @@ -1902,12 +1988,15 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH || (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && authResponseContext_->haveCredential)) { - if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return; @@ -1915,8 +2004,8 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && !authResponseContext_->haveCredential) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -1924,9 +2013,10 @@ void DmAuthManager::SrcAuthDeviceFinish() } } if (!authResponseContext_->isOnline && authResponseContext_->haveCredential) { - softbusConnector_->JoinLnn(authRequestContext_->ip); + softbusConnector_->JoinLnn(authRequestContext_->addr); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return; @@ -1945,9 +2035,7 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); - } + SetProcessInfo(); softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -1960,7 +2048,10 @@ void DmAuthManager::AuthDeviceFinish(int64_t requestId) return; } isAuthDevice_ = false; - timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + } + if (authRequestState_ != nullptr && authResponseState_ == nullptr) { PutAccessControlList(); SrcAuthDeviceFinish(); @@ -1979,23 +2070,34 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) return; } if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + if (requestId != authResponseContext_->requestId) { + LOGE("DmAuthManager::AuthDeviceError requestId %{public}" PRId64 "is error.", requestId); + return; + } authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; + authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; authRequestState_->TransitionTo(std::make_shared()); return; } authTimes_++; - timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + } + if (errorCode != DM_OK || requestId != authResponseContext_->requestId) { if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID; + authResponseContext_->reply = ERR_DM_INPUT_PARA_INVALID; authRequestState_->TransitionTo(std::make_shared()); } else { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); } } @@ -2043,7 +2145,7 @@ void DmAuthManager::CompatiblePutAcl() accesser.requestBundleName = authResponseContext_->hostPkgName; if (authRequestState_ != nullptr && authResponseState_ == nullptr) { accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId(); + accesser.requestAccountId = MultipleUserConnector::GetAccountInfoByUserId(accesser.requestUserId).accountId; accesser.requestDeviceId = localUdid; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { accesser.requestDeviceId = authResponseContext_->localDeviceId; @@ -2056,130 +2158,19 @@ void DmAuthManager::CompatiblePutAcl() accessee.trustDeviceId = remoteDeviceId_; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { accessee.trustUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accessee.trustAccountId = MultipleUserConnector::GetOhosAccountId(); + accessee.trustAccountId = MultipleUserConnector::GetAccountInfoByUserId(accessee.trustUserId).accountId; accessee.trustDeviceId = localUdid; } DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee); } -void DmAuthManager::CommonEventCallback(int32_t userId, std::string commonEventType) -{ - LOGI("DmAuthManager::CommonEventCallback"); - if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - AccountIdLogoutEventCallback(userId); - } else if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - LOGI("user_switched event accountId: %{public}s, userId: %{public}s", - GetAnonyString(accountId).c_str(), GetAnonyInt32(userId).c_str()); - if (userId > 0) { - MultipleUserConnector::SetSwitchOldUserId(userId); - MultipleUserConnector::SetSwitchOldAccountId(accountId); - } - } -} - -void DmAuthManager::AccountIdLogoutEventCallback(int32_t userId) -{ - LOGI("DmAuthManager::AccountIdLogoutEventCallback"); - std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId(); - std::string currentAccountId = MultipleUserConnector::GetOhosAccountId(); - MultipleUserConnector::SetSwitchOldAccountId(currentAccountId); - if (oldAccountId == currentAccountId) { - LOGE("The account logout is error."); - return; - } - if (currentAccountId == "ohosAnonymousUid" && - DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, oldAccountId)) { - DeviceProfileConnector::GetInstance().DeleteAccessControlList(userId, oldAccountId); - hiChainConnector_->DeleteAllGroup(userId); - } -} - -void DmAuthManager::UserSwitchEventCallback(int32_t userId) +void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) { - LOGI("UserSwitchEventCallback start."); - std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId(); - int32_t oldUserId = MultipleUserConnector::GetSwitchOldUserId(); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(oldUserId, oldAccountId); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, oldAccountId); - hiChainConnector_->DeleteP2PGroup(userId); -} - -void DmAuthManager::UserChangeEventCallback(int32_t userId) -{ - LOGI("DmAuthManager::UserChangeEventCallback"); - std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId(); - int32_t oldUseId = MultipleUserConnector::GetSwitchOldUserId(); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(oldUseId, oldAccountId); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, oldAccountId); - hiChainConnector_->DeleteP2PGroup(userId); -} - -void DmAuthManager::HandleSyncDeleteTimeout(std::string name) -{ - LOGI("DmAuthManager::HandleSyncDeleteTimeout start timer name %{public}s", name.c_str()); - if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_SYNCDELETE_DONE) { - if (authResponseContext_ == nullptr) { - authResponseContext_ = std::make_shared(); - } - authResponseContext_->state = authRequestState_->GetStateType(); - authResponseContext_->reply = ERR_DM_TIME_OUT; - authRequestState_->TransitionTo(std::make_shared()); - } - - if (authResponseState_ != nullptr && - authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_SYNCDELETE_DONE) { - authResponseContext_->state = authResponseState_->GetStateType(); - authResponseContext_->reply = ERR_DM_TIME_OUT; - authResponseState_->TransitionTo(std::make_shared()); - } - LOGI("DmAuthManager::HandleSyncDeleteTimeout start complete"); -} - -int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &deviceId) -{ - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string localDeviceId = static_cast(localUdid); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, deviceId); - if (offlineParam.bindType == INVALIED_TYPE) { - LOGE("Acl not contain the pkgName bind data."); - return ERR_DM_FAILED; - } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber != 0) { - LOGI("The pkgName unbind app-level type leftAclNumber not zero."); - softbusConnector_->SetPkgName(pkgName); - softbusConnector_->HandleDeviceOffline(deviceId); - } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber == 0) { - LOGI("The pkgName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetPkgName(pkgName); - hiChainAuthConnector_->DeleteCredential(deviceId, MultipleUserConnector::GetCurrentAccountUserID()); - } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber != 0) { - LOGI("Unbind deivce-level, retain identical account bind type."); - } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber == 0) { - LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(deviceId, MultipleUserConnector::GetCurrentAccountUserID()); - } - return DM_OK; -} - -void DmAuthManager::ProRespNegotiateExt(const int32_t &sessionId) -{ - LOGI("DmAuthManager::ProRespNegotiateExt start."); + LOGI("DmAuthManager::ProcRespNegotiateExt start."); remoteDeviceId_ = authResponseContext_->localDeviceId; - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - MultipleUserConnector::SetSwitchOldAccountId(accountId); - MultipleUserConnector::SetSwitchOldUserId(userId); - authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") { - authResponseContext_->isIdenticalAccount = true; - } authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; - authResponseContext_->localAccountId = accountId; authResponseContext_->remoteUserId = authResponseContext_->localUserId; - authResponseContext_->localUserId = userId; + GetBinderInfo(); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); authResponseContext_->deviceId = authResponseContext_->localDeviceId; @@ -2188,6 +2179,17 @@ void DmAuthManager::ProRespNegotiateExt(const int32_t &sessionId) DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(authResponseContext_->hostPkgName, authResponseContext_->localDeviceId, authResponseContext_->deviceId); authResponseContext_->authed = !authResponseContext_->bindType.empty(); + if (authResponseContext_->authed && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !importAuthCode_.empty()) { + authResponseContext_->importAuthCode = Crypto::Sha256(importAuthCode_); + } + + authResponseContext_->isIdenticalAccount = false; + if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && + authResponseContext_->localAccountId != "ohosAnonymousUid" && authResponseContext_->authed) { + authResponseContext_->isIdenticalAccount = true; + } + authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); authResponseContext_->haveCredential = hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, authResponseContext_->localUserId); @@ -2206,9 +2208,9 @@ void DmAuthManager::ProRespNegotiateExt(const int32_t &sessionId) softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } -void DmAuthManager::ProRespNegotiate(const int32_t &sessionId) +void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) { - LOGI("DmAuthManager::ProRespNegotiate session id"); + LOGI("DmAuthManager::ProcRespNegotiate session id"); AbilityNegotiate(); authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); @@ -2241,12 +2243,27 @@ void DmAuthManager::ProRespNegotiate(const int32_t &sessionId) } } jsonObject[TAG_CRYPTO_SUPPORT] = false; - message = jsonObject.dump(); + message = SafetyDump(jsonObject); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); +} + +void DmAuthManager::ProcIncompatible(const int32_t &sessionId) +{ + LOGI("DmAuthManager::ProcIncompatible sessionId %{public}d.", sessionId); + nlohmann::json respNegotiateMsg; + respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; + respNegotiateMsg[TAG_VER] = DM_ITF_VER; + respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; + std::string message = SafetyDump(respNegotiateMsg); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message) { + if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || hiChainAuthConnector_ == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } authResponseContext_->sessionId = sessionId; authMessageProcessor_->SetResponseContext(authResponseContext_); nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); @@ -2264,61 +2281,24 @@ void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std: hiChainAuthConnector_->ProcessAuthData(authResponseContext_->requestId, authData, osAccountId); } -void DmAuthManager::BindSocketFail() -{ - LOGE("BindSocketFail"); - authResponseContext_->reply = DM_OK; - isFinishOfLocal_ = false; - authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; -} - -void DmAuthManager::BindSocketSuccess(int32_t socket) +int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) { - LOGI("BindSocketSuccess"); - if (authResponseState_ == nullptr && authRequestState_ != nullptr && - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_DELETE_INIT) { - authRequestContext_->sessionId = socket; - authRequestState_->SetAuthContext(authRequestContext_); - authMessageProcessor_->SetRequestContext(authRequestContext_); - authResponseContext_->localDeviceId = authRequestContext_->localDeviceId; - authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; - authMessageProcessor_->SetResponseContext(authResponseContext_); - authRequestState_->TransitionTo(std::make_shared()); - } else { - softbusConnector_->GetSoftbusSession()->CloseUnbindSession(socket); - LOGE("DmAuthManager::BindSocketSuccess but request state is wrong"); + LOGI("DmAuthManager::DeleteGroup"); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; } -} - -void DmAuthManager::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) -{ - LOGI("DmAuthManager::OnUnbindSessionOpened socket: %{public}d, peerSocketName: %{public}s, peerNetworkId:" - "%{public}s, peerPkgName: %{public}s", socket, info.name, GetAnonyString(info.networkId).c_str(), info.pkgName); - if (authResponseState_ == nullptr && authRequestState_ == nullptr) { - authMessageProcessor_ = std::make_shared(shared_from_this()); - authResponseState_ = std::make_shared(); - authResponseState_->SetAuthManager(shared_from_this()); - authResponseState_->Enter(); - authResponseContext_ = std::make_shared(); - if (timer_ == nullptr) { - timer_ = std::make_shared(); - } - timer_->StartTimer(std::string(SYNC_DELETE_TIMEOUT_TASK), SYNC_DELETE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleSyncDeleteTimeout(name); - }); - } else { - std::shared_ptr authMessageProcessor = - std::make_shared(shared_from_this()); - std::shared_ptr authResponseContext = std::make_shared(); - authResponseContext->reply = ERR_DM_SYNC_DELETE_DEVICE_REPEATED; - authMessageProcessor->SetResponseContext(authResponseContext); - std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE); - softbusConnector_->GetSoftbusSession()->SendData(socket, message); + std::vector groupList; + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->GetRelatedGroups(deviceId, groupList); + for (const auto &item : groupList) { + std::string groupId = item.groupId; + hiChainConnector_->DeleteGroup(groupId); } + return DM_OK; } -int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId) { LOGI("DmAuthManager::DeleteGroup"); if (pkgName.empty()) { @@ -2326,11 +2306,11 @@ int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string return ERR_DM_FAILED; } std::vector groupList; - hiChainConnector_->GetRelatedGroups(deviceId, groupList); + hiChainConnector_->GetRelatedGroups(userId, deviceId, groupList); if (groupList.size() > 0) { std::string groupId = ""; groupId = groupList.front().groupId; - hiChainConnector_->DeleteGroup(groupId); + hiChainConnector_->DeleteGroup(userId, groupId); } else { LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0"); return ERR_DM_FAILED; @@ -2367,25 +2347,24 @@ void DmAuthManager::PutAccessControlList() } aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestTokenId = static_cast(authResponseContext_->tokenId); accesser.requestBundleName = authResponseContext_->hostPkgName; + DmAccessee accessee; + accessee.trustBundleName = authResponseContext_->hostPkgName; if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + accesser.requestTokenId = static_cast(authResponseContext_->tokenId); accesser.requestUserId = authRequestContext_->localUserId; accesser.requestAccountId = authRequestContext_->localAccountId; accesser.requestDeviceId = authRequestContext_->localDeviceId; - } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { - accesser.requestUserId = authResponseContext_->remoteUserId; - accesser.requestAccountId = authResponseContext_->remoteAccountId; - accesser.requestDeviceId = authResponseContext_->localDeviceId; - } - DmAccessee accessee; - accessee.trustTokenId = static_cast(authResponseContext_->tokenId); - accessee.trustBundleName = authResponseContext_->hostPkgName; - if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + accessee.trustTokenId = static_cast(authResponseContext_->remoteTokenId); accessee.trustUserId = authRequestContext_->remoteUserId; accessee.trustAccountId = authRequestContext_->remoteAccountId; accessee.trustDeviceId = authResponseContext_->deviceId; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); + accesser.requestUserId = authResponseContext_->remoteUserId; + accesser.requestAccountId = authResponseContext_->remoteAccountId; + accesser.requestDeviceId = authResponseContext_->localDeviceId; + accessee.trustTokenId = static_cast(authResponseContext_->tokenId); accessee.trustUserId = authResponseContext_->localUserId; accessee.trustAccountId = authResponseContext_->localAccountId; accessee.trustDeviceId = localUdid; @@ -2395,31 +2374,37 @@ void DmAuthManager::PutAccessControlList() void DmAuthManager::HandleSessionHeartbeat(std::string name) { - timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + } LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); nlohmann::json jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { - timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), SESSION_HEARTBEAT_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleSessionHeartbeat(name); - }); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleSessionHeartbeat(name); + }); + } } LOGI("DmAuthManager::HandleSessionHeartbeat complete"); } int32_t DmAuthManager::CheckTrustState() { - if (authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && - !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { - if (authResponseContext_->importAuthCode == Crypto::Sha256(importAuthCode_)) { - SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH); - } else { - SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); - } + bool isSameGroup = false; + if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT && + hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, + authRequestContext_->localDeviceId)) { + isSameGroup = true; + } + if (isSameGroup && authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + authResponseContext_->isFinish = true; + SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH); return ALREADY_BIND; } if (authResponseContext_->isIdenticalAccount) { @@ -2427,21 +2412,20 @@ int32_t DmAuthManager::CheckTrustState() softbusConnector_->JoinLnn(authResponseContext_->deviceId); authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); return ALREADY_BIND; } } - if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT) { - if (hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, - authRequestContext_->localDeviceId)) { - if (!DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(authResponseContext_->hostPkgName, - authResponseContext_->localDeviceId)) { - CompatiblePutAcl(); - } - softbusConnector_->JoinLnn(authResponseContext_->deviceId); - authRequestState_->TransitionTo(std::make_shared()); - return ALREADY_BIND; + if (isSameGroup) { + if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName, + authResponseContext_->localDeviceId)) { + CompatiblePutAcl(); } + softbusConnector_->JoinLnn(authResponseContext_->deviceId); + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authRequestState_->TransitionTo(std::make_shared()); + return ALREADY_BIND; } if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && @@ -2502,6 +2486,10 @@ bool DmAuthManager::IsScreenLocked() void DmAuthManager::OnScreenLocked() { + if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType); + return; + } if (authRequestState_ == nullptr) { LOGE("OnScreenLocked authRequestState_ is nullptr."); return; @@ -2537,5 +2525,129 @@ void DmAuthManager::HandleDeviceNotTrust(const std::string &udid) CHECK_NULL_VOID(hiChainConnector_); hiChainConnector_->DeleteAllGroupByUdid(udid); } + +std::string DmAuthManager::ConvertSrcVersion(const std::string &version, const std::string &edition) +{ + std::string srcVersion = ""; + if (version == "" && edition != "") { + srcVersion = edition; + } else if (version == "" && edition == "") { + srcVersion = DM_VERSION_5_0_1; + } else if (version != "" && edition == "") { + srcVersion = version; + } + LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", + version.c_str(), edition.c_str(), srcVersion.c_str()); + return srcVersion; +} + +std::string DmAuthManager::ConvertSinkVersion(const std::string &version) +{ + std::string sinkVersion = ""; + if (version == "") { + sinkVersion = DM_VERSION_4_1_5_1; + } else { + sinkVersion = version; + } + LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str()); + return sinkVersion; +} + +void DmAuthManager::SetAuthType(int32_t authType) +{ + authType_ = authType; +} + +int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType_.load()); + if (AUTH_TYPE_IMPORT_AUTH_CODE == authType_) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} + +bool DmAuthManager::IsAllowDeviceBind() +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) +{ + if (IsAllowDeviceBind()) { + if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || + static_cast(bindLevel) < DEVICE) { + return DEVICE; + } + return bindLevel; + } + if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && + static_cast(bindLevel) != SERVICE)) { + return APP; + } + return bindLevel; +} + +std::string DmAuthManager::GetBundleName(nlohmann::json &jsonObject) +{ + if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { + return jsonObject[BUNDLE_NAME_KEY].get(); + } + bool isSystemSA = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +int32_t DmAuthManager::GetBinderInfo() +{ + CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); + if (authResponseContext_->bundleName.empty()) { + LOGI("bundleName is empty"); + authResponseContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); + authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); + authResponseContext_->tokenId = authResponseContext_->remoteTokenId; + return DM_OK; + } + authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); + authResponseContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); + int32_t ret = AppManager::GetInstance(). + GetNativeTokenIdByName(authResponseContext_->bundleName, authResponseContext_->tokenId); + if (ret == DM_OK) { + LOGI("bundleName is sa"); + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, + authResponseContext_->bundleName, 0, authResponseContext_->tokenId); + if (ret != DM_OK) { + LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str()); + authResponseContext_->tokenId = authResponseContext_->remoteTokenId; + } + return ret; +} + +void DmAuthManager::SetProcessInfo() +{ + CHECK_NULL_VOID(authResponseContext_); + ProcessInfo processInfo; + if (authResponseContext_->bindLevel == APP) { + processInfo.pkgName = authResponseContext_->hostPkgName; + processInfo.userId = authResponseContext_->localUserId; + } else if (authResponseContext_->bindLevel == DEVICE || authResponseContext_->bindLevel == INVALIED_TYPE) { + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = authResponseContext_->localUserId; + } else { + LOGE("bindlevel error %{public}d.", authResponseContext_->bindLevel); + return; + } + softbusConnector_->SetProcessInfo(processInfo); +} } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/implementation/src/config/dm_config_manager.cpp b/services/implementation/src/config/dm_config_manager.cpp index 578cb7d444d95d583d2fb46ad3e52a6208f8f5d1..ddfea4bf49069574a96919a1d6e66bafe28347d1 100644 --- a/services/implementation/src/config/dm_config_manager.cpp +++ b/services/implementation/src/config/dm_config_manager.cpp @@ -139,28 +139,24 @@ DmConfigManager::~DmConfigManager() { void *so_handle = nullptr; for (auto iter = soAdapterLoadInfo_.begin(); iter != soAdapterLoadInfo_.end(); iter++) { - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = (iter->second).soPath + (iter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (iter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); continue; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("DmConfigManager so_handle is not nullptr first."); dlclose(so_handle); } } for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) { - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = (iter->second).soPath + (iter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (iter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); continue; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("DmConfigManager so_handle is not nullptr second."); dlclose(so_handle); @@ -189,16 +185,17 @@ std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::str } void *so_handle = nullptr; - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (soInfoIter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); return nullptr; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); if (so_handle == nullptr) { - LOGE("load crypto so %{public}s failed", soName.c_str()); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE); + } + if (so_handle == nullptr) { + LOGE("load crypto so failed."); return nullptr; } @@ -224,14 +221,15 @@ void DmConfigManager::GetAuthAdapter(std::mapsecond).soPath + (iter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (iter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); continue; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE); + } if (so_handle == nullptr) { LOGE("load auth so %{public}s failed", (iter->second).soName.c_str()); continue; diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 043d2dd322ae530417d730ebed4101d95c186e6b..ec374658e41108e66ae8f0a5b67173d71c64f956 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -20,7 +20,9 @@ #include "dm_log.h" #include "dm_random.h" #include "parameter.h" - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { const int32_t LOCAL_CREDENTIAL_DEAL_TYPE = 1; @@ -111,7 +113,7 @@ int32_t DmCredentialManager::RequestCredential(const std::string &reqJsonStr, st jsonObj[FIELD_CREDENTIAL_VERSION] = credentialVersion; jsonObj[FIELD_USER_ID] = userId; jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string tmpStr = jsonObj.dump(); + std::string tmpStr = SafetyDump(jsonObj); return hiChainConnector_->getRegisterInfo(tmpStr.c_str(), returnJsonStr); } @@ -123,7 +125,6 @@ int32_t DmCredentialManager::ImportCredential(const std::string &pkgName, const LOGE("credentialInfo not found by pkgName %{public}s", GetAnonyString(pkgName).c_str()); return ERR_DM_FAILED; } - pkgName_ = pkgName; nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); if (jsonObject.is_discarded()) { LOGE("credentialInfo string not a json type."); @@ -213,7 +214,12 @@ int32_t DmCredentialManager::DeleteCredential(const std::string &pkgName, const LOGE("credentialInfo not found by pkgName %{public}s", GetAnonyString(pkgName).c_str()); return ERR_DM_FAILED; } - pkgName_ = pkgName; + int32_t callerUserId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(callerUserId); +#endif + processInfo_.pkgName = pkgName; + processInfo_.userId = callerUserId; nlohmann::json jsonObject = nlohmann::json::parse(deleteInfo, nullptr, false); if (jsonObject.is_discarded()) { LOGE("deleteInfo string not a json type."); @@ -247,7 +253,8 @@ int32_t DmCredentialManager::DeleteCredential(const std::string &pkgName, const void DmCredentialManager::OnGroupResultExt(int32_t action, const std::string &resultInfo) { LOGI("DmCredentialManager::OnGroupResultExt action %{public}d, resultInfo %{public}s.", action, resultInfo.c_str()); - listener_->OnCredentialResult(pkgName_, action, resultInfo); + CHECK_NULL_VOID(listener_); + listener_->OnCredentialResult(processInfo_, action, resultInfo); } void DmCredentialManager::OnGroupResult(int64_t requestId, int32_t action, @@ -257,7 +264,8 @@ void DmCredentialManager::OnGroupResult(int64_t requestId, int32_t action, if (requestId_ != requestId) { return; } - listener_->OnCredentialResult(pkgName_, action, resultInfo); + CHECK_NULL_VOID(listener_); + listener_->OnCredentialResult(processInfo_, action, resultInfo); } int32_t DmCredentialManager::RegisterCredentialCallback(const std::string &pkgName) @@ -266,9 +274,15 @@ int32_t DmCredentialManager::RegisterCredentialCallback(const std::string &pkgNa LOGE("DmCredentialManager::RegisterCredentialCallback input param is empty"); return ERR_DM_FAILED; } + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif LOGI("DmCredentialManager::RegisterCredentialCallback pkgName = %{public}s", GetAnonyString(pkgName).c_str()); { std::lock_guard autoLock(locks_); + processInfo_.pkgName = pkgName; + processInfo_.userId = userId; credentialVec_.push_back(pkgName); } return hiChainConnector_->RegisterHiChainGroupCallback(std::shared_ptr(shared_from_this())); @@ -350,7 +364,7 @@ void from_json(const nlohmann::json &jsonObject, CredentialDataInfo &credentialD } if (IsString(jsonObject, FIELD_PKINFO)) { nlohmann::json jsonPkInfo = jsonObject[FIELD_PKINFO]; - credentialDataInfo.pkInfo = jsonPkInfo.dump(); + credentialDataInfo.pkInfo = SafetyDump(jsonPkInfo); } } else if (credentialDataInfo.credentialType == SYMMETRY_CREDENTIAL_TYPE) { if (IsString(jsonObject, FIELD_AUTH_CODE)) { @@ -383,7 +397,7 @@ void to_json(nlohmann::json &jsonObject, const CredentialDataInfo &credentialDat int32_t DmCredentialManager::GetAddDeviceList(const nlohmann::json &jsonObject, nlohmann::json &jsonDeviceList) { - if (!jsonObject.contains(FIELD_CREDENTIAL_DATA) || !jsonObject[FIELD_CREDENTIAL_DATA].is_object() || + if (!jsonObject.contains(FIELD_CREDENTIAL_DATA) || !jsonObject[FIELD_CREDENTIAL_DATA].is_array() || !IsInt32(jsonObject, FIELD_AUTH_TYPE)) { LOGE("credentaildata or authType string key not exist!"); return ERR_DM_FAILED; @@ -519,5 +533,12 @@ int32_t DmCredentialManager::DeleteRemoteCredential(const std::string &deleteInf } return DM_OK; } + +void DmCredentialManager::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) +{ + CHECK_NULL_VOID(listener_); + listener_->OnCredentialAuthStatus(processInfo_, deviceList, deviceTypeId, errcode); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp b/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp index 964033d456b1a43ed919da8489dc8769f81906eb..db426f532aaee7b157927b128d01e8d88a96f08d 100644 --- a/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp +++ b/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp @@ -66,7 +66,8 @@ bool DmCommonEventManager::SubscribeServiceEvent(const std::vector subscriber_ = nullptr; return false; } - statusChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener(subscriber_); + statusChangeListener_ = sptr( + new SystemAbilityStatusChangeListener(subscriber_)); if (statusChangeListener_ == nullptr) { LOGE("statusChangeListener_ is nullptr"); subscriber_ = nullptr; diff --git a/services/implementation/src/dependency/deviceprofile/dp_inited_callback.cpp b/services/implementation/src/dependency/deviceprofile/dp_inited_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f56b15d9487b58391b01bea41e72bfd2cd253483 --- /dev/null +++ b/services/implementation/src/dependency/deviceprofile/dp_inited_callback.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dp_inited_callback.h" + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +#include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif + +#include "deviceprofile_connector.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const std::string PUT_ALL_TRUSTED_DEVICES_TASK = "PutAllTrustedDevicesTask"; +} + +DpInitedCallback::DpInitedCallback() +{} + +DpInitedCallback::~DpInitedCallback() +{} + +int32_t DpInitedCallback::OnDpInited() +{ + LOGE("In."); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { PutAllTrustedDevices(); }); +#else + std::thread putAllTrustedDevicesTask([=]() { PutAllTrustedDevices(); }); + if (pthread_setname_np(putAllTrustedDevicesTask.native_handle().c_str(), PUT_ALL_TRUSTED_DEVICES_TASK) != DM_OK) { + LOGE("putAllTrustedDevicesTask setname failed."); + } + putAllTrustedDevicesTask.detach(); +#endif + return DM_OK; +} + +void DpInitedCallback::PutAllTrustedDevices() +{ + LOGE("In."); + std::vector dmDeviceInfos; + int32_t ret = SoftbusCache::GetInstance().GetDeviceInfoFromCache(dmDeviceInfos); + if (ret != DM_OK) { + LOGE("GetDeviceInfoFromCache fail:%{public}d", ret); + return; + } + if (dmDeviceInfos.empty()) { + LOGW("dmDeviceInfos is empty"); + return; + } + char localUdidTemp[DEVICE_UUID_LENGTH]; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = reinterpret_cast(localUdidTemp); + if (localUdid.empty()) { + LOGE("localUdid is empty"); + return; + } + std::vector deviceInfos; + std::unordered_map authFormMap = + DeviceProfileConnector::GetInstance().GetAppTrustDeviceList("", localUdid); + for (const auto& item : dmDeviceInfos) { + DistributedDeviceProfile::TrustedDeviceInfo trustedDeviceInfo; + if (ConvertToTrustedDeviceInfo(authFormMap, item, trustedDeviceInfo)) { + deviceInfos.push_back(trustedDeviceInfo); + } + } + if (deviceInfos.empty()) { + LOGW("deviceInfos is empty"); + return; + } + ret = DeviceProfileConnector::GetInstance().PutAllTrustedDevices(deviceInfos); + LOGI("ret:%{public}d", ret); +} + +bool DpInitedCallback::ConvertToTrustedDeviceInfo(const std::unordered_map &authFormMap, + const DmDeviceInfo &deviceInfo, DistributedDeviceProfile::TrustedDeviceInfo &trustedDeviceInfo) +{ + trustedDeviceInfo.SetNetworkId(deviceInfo.networkId); + trustedDeviceInfo.SetDeviceTypeId(deviceInfo.deviceTypeId); + + if (deviceInfo.extraData.empty()) { + LOGE("extraData is empty, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + nlohmann::json extraJson = nlohmann::json::parse(deviceInfo.extraData, nullptr, false); + if (extraJson.is_discarded()) { + LOGE("extraData parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + if (IsString(extraJson, PARAM_KEY_OS_VERSION)) { + trustedDeviceInfo.SetOsVersion(extraJson[PARAM_KEY_OS_VERSION].get()); + } else { + LOGE("osVersion parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + if (IsInt32(extraJson, PARAM_KEY_OS_TYPE)) { + trustedDeviceInfo.SetOsType(extraJson[PARAM_KEY_OS_TYPE].get()); + } else { + LOGE("osType parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + + std::string udid = ""; + if (SoftbusCache::GetInstance().GetUdidFromCache(deviceInfo.networkId, udid) != DM_OK) { + LOGE("udid parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + trustedDeviceInfo.SetUdid(udid); + + std::string uuid = ""; + if (SoftbusCache::GetInstance().GetUuidFromCache(deviceInfo.networkId, uuid) != DM_OK) { + LOGE("uuid parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + trustedDeviceInfo.SetUuid(uuid); + + auto it = authFormMap.find(udid); + if (it == authFormMap.end()) { + LOGE("authForm not exist, udid:%{public}s", GetAnonyString(udid).c_str()); + return false; + } + trustedDeviceInfo.SetAuthForm(static_cast(it->second)); + return true; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index c7887c985c4816c75e238df57f1c920e6b17852b..f0614dcf2d274501fd37080746032c47b51c4206 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -56,7 +56,7 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s authParamJson["osAccountId"] = osAccountId; authParamJson["pinCode"] = std::to_string(pinCode); authParamJson["acquireType"] = AcquireType::P2P_BIND; - std::string authParam = authParamJson.dump(); + std::string authParam = SafetyDump(authParamJson); LOGI("StartAuthDevice authParam %{public}s ,requestId %{public}" PRId64, GetAnonyString(authParam).c_str(), requestId); int32_t ret = StartAuthDevice(requestId, authParam.c_str(), &deviceAuthCallback_); @@ -73,7 +73,7 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut nlohmann::json jsonAuthParam; jsonAuthParam["osAccountId"] = osAccountId; jsonAuthParam["data"] = authData; - int32_t ret = ProcessAuthDevice(requestId, jsonAuthParam.dump().c_str(), &deviceAuthCallback_); + int32_t ret = ProcessAuthDevice(requestId, SafetyDump(jsonAuthParam).c_str(), &deviceAuthCallback_); if (ret != HC_SUCCESS) { LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; @@ -101,17 +101,17 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons return nullptr; } nlohmann::json jsonObj; - int32_t pinCode = 0; - if (dmDeviceAuthCallback_->GetPinCode(pinCode) == ERR_DM_FAILED) { + int32_t pinCode = -1; + if (dmDeviceAuthCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == -1) { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); } std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -159,7 +159,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_CREATE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain generate credential failed."); @@ -192,7 +192,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -223,7 +223,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -255,7 +255,7 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_IMPORT, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -286,7 +286,7 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 4721bd730430b6f6dc11c1d0dfe3d439029e65c0..c1b4f837b384cf583a772ce52ddea0cf05c3bb72 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -40,6 +40,7 @@ const int32_t CREDENTIAL_NETWORK = 1; const int32_t DELAY_TIME_MS = 10000; // 10ms const int32_t FIELD_EXPIRE_TIME_VALUE = 7; const int32_t SAME_ACCOUNT = 1; +const int32_t DEVICE_ID_HALF = 2; constexpr const char* DEVICE_ID = "DEVICE_ID"; constexpr const char* FIELD_CREDENTIAL = "credential"; @@ -153,8 +154,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - - int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); + int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, SafetyDump(jsonObj).c_str()); struct RadarInfo info = { .funcName = "CreateGroup", .toCallPkg = HICHAINNAME, @@ -162,7 +162,6 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou static_cast(StageRes::STAGE_FAIL) : static_cast(StageRes::STAGE_IDLE), .bizState = (ret != 0) ? static_cast(BizState::BIZ_STATE_END) : static_cast(BizState::BIZ_STATE_START), - .localUdid = std::string(localDeviceId), .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_CREATE_GROUP_FAILED), }; if (!DmRadarHelper::GetInstance().ReportAuthCreateGroup(info)) { @@ -179,7 +178,7 @@ bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInf { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); std::vector groupList; if (GetGroupInfo(queryParams, groupList)) { groupInfo = groupList[0]; @@ -192,7 +191,7 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -212,53 +211,36 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth bool HiChainConnector::GetGroupInfo(const std::string &queryParams, std::vector &groupList) { - char *groupVec = nullptr; - uint32_t num = 0; int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); return false; } - int32_t ret = deviceGroupManager_->getGroupInfo(userId, DM_PKG_NAME, queryParams.c_str(), &groupVec, &num); - if (ret != 0) { - LOGE("[HICHAIN]fail to get group info with ret:%{public}d.", ret); - return false; - } - if (groupVec == nullptr) { - LOGE("[HICHAIN]return groups info point is nullptr"); - return false; - } - if (num == 0) { - LOGE("[HICHAIN]return groups info number is zero."); - return false; - } - LOGI("HiChainConnector::GetGroupInfo groupNum(%{public}u)", num); - std::string relatedGroups = std::string(groupVec); - deviceGroupManager_->destroyInfo(&groupVec); - nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups, nullptr, false); - if (jsonObject.is_discarded()) { - LOGE("returnGroups parse error"); - return false; - } - if (!jsonObject.is_array()) { - LOGE("json string is not array."); - return false; - } - std::vector groupInfos = jsonObject.get>(); - if (groupInfos.size() == 0) { - LOGE("HiChainConnector::GetGroupInfo group failed, groupInfos is empty."); - return false; - } - groupList = groupInfos; - return true; + return GetGroupInfo(userId, queryParams, groupList); +} + +bool HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &queryParams, + std::vector &groupList) +{ + return GetGroupInfoCommon(userId, queryParams, DM_PKG_NAME, groupList); } -int32_t HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &queryParams, +bool HiChainConnector::GetGroupInfoExt(const int32_t userId, const std::string &queryParams, + std::vector &groupList) +{ + return GetGroupInfoCommon(userId, queryParams, DM_PKG_NAME_EXT, groupList); +} + +bool HiChainConnector::GetGroupInfoCommon(const int32_t userId, const std::string &queryParams, const char* pkgName, std::vector &groupList) { char *groupVec = nullptr; uint32_t num = 0; - int32_t ret = deviceGroupManager_->getGroupInfo(userId, DM_PKG_NAME, queryParams.c_str(), &groupVec, &num); + if (deviceGroupManager_ == nullptr) { + LOGE("deviceGroupManager_ is null"); + return false; + } + int32_t ret = deviceGroupManager_->getGroupInfo(userId, pkgName, queryParams.c_str(), &groupVec, &num); if (ret != 0) { LOGE("[HICHAIN]fail to get group info with ret:%{public}d.", ret); return false; @@ -361,7 +343,7 @@ int32_t HiChainConnector::AddMember(const std::string &deviceId, const std::stri jsonObj[FIELD_DEVICE_ID] = localDeviceId; jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME].get(); jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str(); - std::string tmpStr = jsonObj.dump(); + std::string tmpStr = SafetyDump(jsonObj); int64_t requestId = jsonObject[TAG_REQUEST_ID].get(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { @@ -493,18 +475,18 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch return nullptr; } nlohmann::json jsonObj; - int32_t pinCode = 0; - if (hiChainConnectorCallback_->GetPinCode(pinCode) == ERR_DM_FAILED) { + int32_t pinCode = -1; + if (hiChainConnectorCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == -1) { jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); } - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str(); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -529,7 +511,7 @@ std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string r } jsonObject[DEVICE_ID] = reqDeviceId; - return jsonObject.dump(); + return SafetyDump(jsonObject); } int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vector &groupList) @@ -537,6 +519,12 @@ int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vec return GetRelatedGroupsCommon(deviceId, DM_PKG_NAME, groupList); } +int32_t HiChainConnector::GetRelatedGroups(int32_t userId, const std::string &deviceId, + std::vector &groupList) +{ + return GetRelatedGroupsCommon(userId, deviceId, DM_PKG_NAME, groupList); +} + int32_t HiChainConnector::GetRelatedGroupsExt(const std::string &deviceId, std::vector &groupList) { return GetRelatedGroupsCommon(deviceId, DM_PKG_NAME_EXT, groupList); @@ -614,7 +602,7 @@ int32_t HiChainConnector::DelMemberFromGroup(const std::string &groupId, const s nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_DELETE_ID] = deviceId; - std::string deleteParams = jsonObj.dump(); + std::string deleteParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -633,7 +621,7 @@ int32_t HiChainConnector::DeleteGroup(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -653,7 +641,7 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -668,26 +656,12 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) return DM_OK; } -int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId) -{ - int64_t requestId = GenRequestId(); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); - int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); - if (ret != 0) { - LOGE("[HICHAIN]fail to delete group failed, ret: %{public}d.", ret); - return ERR_DM_FAILED; - } - return DM_OK; -} - int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &userId, const int32_t authType) { networkStyle_ = CREDENTIAL_NETWORK; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); std::vector groupList; if (!GetGroupInfo(queryParams, groupList)) { LOGE("failed to get device join groups"); @@ -708,7 +682,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use return ERR_DM_FAILED; } jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = SafetyDump(jsonObj); g_deleteGroupFlag = false; int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -817,8 +791,8 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - - int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); + int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, + SafetyDump(jsonObj).c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); return ERR_DM_CREATE_GROUP_FAILED; @@ -868,7 +842,7 @@ int32_t HiChainConnector::GetGroupId(const std::string &userId, const int32_t gr { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(); + std::string queryParams = SafetyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -901,7 +875,7 @@ int32_t HiChainConnector::ParseRemoteCredential(const int32_t groupType, const s jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = groupType; jsonObj[FIELD_DEVICE_LIST] = jsonDeviceList[FIELD_DEVICE_LIST]; - params = jsonObj.dump(); + params = SafetyDump(jsonObj); osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { LOGE("get current process account user id failed"); @@ -955,7 +929,7 @@ int32_t HiChainConnector::GetGroupIdExt(const std::string &userId, const int32_t { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(); + std::string queryParams = SafetyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -1009,7 +983,7 @@ int32_t HiChainConnector::ParseRemoteCredentialExt(const std::string &credential return ERR_DM_FAILED; } jsonObj[FIELD_DEVICE_LIST] = jsonObject[FIELD_DEVICE_LIST]; - params = jsonObj.dump(); + params = SafetyDump(jsonObj); return DM_OK; } @@ -1131,54 +1105,84 @@ void HiChainConnector::DeleteAllGroup(int32_t userId) } } -void HiChainConnector::DeleteP2PGroup(int32_t userId) +int32_t HiChainConnector::GetRelatedGroupsCommon(const std::string &deviceId, const char* pkgName, + std::vector &groupList) { - LOGI("switch user event happen and this user groups will be deleted with userId: %{public}d", userId); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - std::string queryParams = jsonObj.dump(); - std::vector groupList; - - int32_t oldUserId = MultipleUserConnector::GetSwitchOldUserId(); - MultipleUserConnector::SetSwitchOldUserId(userId); - if (!GetGroupInfo(oldUserId, queryParams, groupList)) { - LOGE("failed to get the old user id groups"); - return; + LOGI("HiChainConnector::GetRelatedGroupsCommon Start to get local related groups."); + uint32_t groupNum = 0; + char *returnGroups = nullptr; + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + if (userId < 0) { + LOGE("get current process account user id failed"); + return ERR_DM_FAILED; } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - int32_t ret = DeleteGroup(oldUserId, iter->groupId); - if (ret != DM_OK) { - LOGE("failed to delete the old user id group"); - } + int32_t ret = + deviceGroupManager_->getRelatedGroups(userId, pkgName, deviceId.c_str(), &returnGroups, &groupNum); + if (ret != 0) { + LOGE("[HICHAIN] fail to get related groups with ret:%{public}d.", ret); + return ERR_DM_FAILED; + } + if (returnGroups == nullptr) { + LOGE("[HICHAIN] return related goups point is nullptr"); + return ERR_DM_FAILED; + } + if (groupNum == 0) { + LOGE("[HICHAIN]return related goups number is zero."); + return ERR_DM_FAILED; + } + std::string relatedGroups = std::string(returnGroups); + nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("returnGroups parse error"); + return ERR_DM_FAILED; + } + if (!jsonObject.is_array()) { + LOGE("jsonObject is not an array."); + return ERR_DM_FAILED; + } + std::vector groupInfos = jsonObject.get>(); + if (groupInfos.empty()) { + LOGE("HiChainConnector::GetRelatedGroups group failed, groupInfos is empty."); + return ERR_DM_FAILED; } + groupList = groupInfos; + return DM_OK; +} - if (!GetGroupInfo(userId, queryParams, groupList)) { - LOGE("failed to get the user id groups"); - return; +int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId) +{ + if (userId < 0) { + LOGE("user id failed"); + return ERR_DM_FAILED; } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - int32_t ret = DeleteGroup(userId, iter->groupId); - if (ret != DM_OK) { - LOGE("failed to delete the user id group"); - } + int64_t requestId = GenRequestId(); + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = groupId; + std::string disbandParams = SafetyDump(jsonObj); + int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); + if (ret != 0) { + LOGE("[HICHAIN]fail to delete group with ret:%{public}d.", ret); + return ERR_DM_FAILED; } + return DM_OK; } -int32_t HiChainConnector::GetRelatedGroupsCommon(const std::string &deviceId, const char* pkgName, +int32_t HiChainConnector::GetRelatedGroupsCommon(int32_t userId, const std::string &deviceId, const char* pkgName, std::vector &groupList) { - LOGI("HiChainConnector::GetRelatedGroupsCommon Start to get local related groups."); - uint32_t groupNum = 0; - char *returnGroups = nullptr; - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + LOGI("Start to get related groups."); if (userId < 0) { - LOGE("get current process account user id failed"); + LOGE("user id failed"); return ERR_DM_FAILED; } + uint32_t groupNum = 0; + char *returnGroups = nullptr; int32_t ret = deviceGroupManager_->getRelatedGroups(userId, pkgName, deviceId.c_str(), &returnGroups, &groupNum); if (ret != 0) { LOGE("[HICHAIN] fail to get related groups with ret:%{public}d.", ret); + delete[] returnGroups; + returnGroups = nullptr; return ERR_DM_FAILED; } if (returnGroups == nullptr) { @@ -1187,9 +1191,13 @@ int32_t HiChainConnector::GetRelatedGroupsCommon(const std::string &deviceId, co } if (groupNum == 0) { LOGE("[HICHAIN]return related goups number is zero."); + delete[] returnGroups; + returnGroups = nullptr; return ERR_DM_FAILED; } std::string relatedGroups = std::string(returnGroups); + delete[] returnGroups; + returnGroups = nullptr; nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups, nullptr, false); if (jsonObject.is_discarded()) { LOGE("returnGroups parse error"); @@ -1226,5 +1234,53 @@ void HiChainConnector::DeleteAllGroupByUdid(const std::string &udid) } } } + +int32_t HiChainConnector::DeleteGroupByACL(std::vector> &delACLInfoVec, + std::vector &userIdVec) +{ + if (delACLInfoVec.size() == 0) { + LOGI("delACLInfoVec is empty"); + return DM_OK; + } + if (userIdVec.size() == 0) { + LOGI("userIdVec is empty"); + return DM_OK; + } + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + std::string queryParams = SafetyDump(jsonObj); + for (int32_t userId : userIdVec) { + std::vector groupList; + if (!GetGroupInfo(userId, queryParams, groupList)) { + continue; + } + for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { + if (!IsNeedDelete(iter->groupName, userId, delACLInfoVec)) { + continue; + } + if (DeleteGroup(userId, iter->groupId) != DM_OK) { + LOGE("failed to delete group %{public}s", GetAnonyString(iter->groupId).c_str()); + } + } + } + return DM_OK; +} + +bool HiChainConnector::IsNeedDelete(std::string &groupName, int32_t userId, + std::vector> &delACLInfoVec) +{ + if (delACLInfoVec.size() == 0 || groupName.empty()) { + LOGI("delACLInfoVec or groupName is empty"); + return false; + } + for (auto item : delACLInfoVec) { + uint32_t interceptLength = item.second.size() / DEVICE_ID_HALF; + std::string interceptUdid = item.second.substr(0, interceptLength); + if (groupName.find(interceptUdid) != std::string::npos && userId == item.first) { + return true; + } + } + return false; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index 44e54a941f1cb018521bcd7d9f056bc4bab765e0..a4df42a1aca384ac9be3dc4d739c4c6a5282ea4d 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -22,6 +22,7 @@ #include "device_auth.h" #include "device_auth_defines.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "nlohmann/json.hpp" @@ -135,7 +136,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) { nlohmann::json jsonObj; jsonObj[FIELD_IS_DELETE_ALL] = true; - std::string params = jsonObj.dump(); + std::string params = SafetyDump(jsonObj); #if (defined(MINE_HARMONY)) char *returnInfo = nullptr; int32_t retValue = g_deviceGroupManager->processCredential(DELETE_SELF_CREDENTIAL, params.c_str(), &returnInfo); @@ -143,6 +144,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) LOGE("failed to delete hichain credential and group with ret:%{public}d.", retValue); return ERR_DM_FAILED; } + g_deviceGroupManager->destroyInfo(&returnInfo); #endif return DM_OK; } @@ -172,7 +174,7 @@ int32_t MineHiChainConnector::CreateGroup(const std::string &reqJsonStr) jsonObj[FIELD_GROUP_NAME] = DEVICE_MANAGER_GROUPNAME; jsonObj[FIELD_DEVICE_ID] = std::string(deviceUdid); jsonObj[FIELD_GROUP_TYPE] = IDENTICAL_ACCOUNT_GROUP; - std::string createParams = jsonObj.dump(); + std::string createParams = SafetyDump(jsonObj); retValue = g_deviceGroupManager->createGroup(DEFAULT_OS_ACCOUNT, requestId, DM_PKG_NAME, createParams.c_str()); if (retValue != HC_SUCCESS) { LOGE("failed to create group with ret:%{public}d.", retValue); @@ -263,9 +265,11 @@ int MineHiChainConnector::ImportCredential(std::string reqJsonStr, std::string & } if (CreateGroup(reqJsonStr) != DM_OK) { DeleteCredentialAndGroup(); + g_deviceGroupManager->destroyInfo(&returnInfo); LOGE("fail to import hichain credential bacause create group unsuccessfully."); return ERR_DM_HICHAIN_GROUP_CREATE_FAILED; } + g_deviceGroupManager->destroyInfo(&returnInfo); #endif LOGI("import device credential info successfully."); return DM_OK; diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 57ad2c710139a732955111af32bd6626272d28ac..9e5770cf4c9e88919964e11db62f1ce23627c3a5 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -42,17 +42,18 @@ constexpr const char* BLE_MAC = "BLE_MAC"; constexpr const char* ETH_IP = "ETH_IP"; constexpr const char* ETH_PORT = "ETH_PORT"; +std::string SoftbusConnector::remoteUdidHash_ = ""; SoftbusConnector::PulishStatus SoftbusConnector::publishStatus = SoftbusConnector::STATUS_UNKNOWN; std::map> SoftbusConnector::discoveryDeviceInfoMap_ = {}; std::map> SoftbusConnector::discoveryCallbackMap_ = {}; std::map> SoftbusConnector::publishCallbackMap_ = {}; std::queue SoftbusConnector::discoveryDeviceIdQueue_ = {}; std::unordered_map SoftbusConnector::deviceUdidMap_ = {}; -std::vector SoftbusConnector::pkgNameVec_ = {}; +std::vector SoftbusConnector::processInfoVec_ = {}; std::mutex SoftbusConnector::discoveryCallbackMutex_; std::mutex SoftbusConnector::discoveryDeviceInfoMutex_; std::mutex SoftbusConnector::deviceUdidLocks_; -std::mutex SoftbusConnector::pkgNameVecMutex_; +std::mutex SoftbusConnector::processInfoVecMutex_; IPublishCb SoftbusConnector::softbusPublishCallback_ = { .OnPublishResult = SoftbusConnector::OnSoftbusPublishResult, @@ -127,7 +128,10 @@ int32_t SoftbusConnector::UnRegisterSoftbusPublishCallback(const std::string &pk int32_t SoftbusConnector::PublishDiscovery(const DmPublishInfo &dmPublishInfo) { PublishInfo publishInfo; - (void)memset_s(&publishInfo, sizeof(PublishInfo), 0, sizeof(PublishInfo)); + if (memset_s(&publishInfo, sizeof(PublishInfo), 0, sizeof(PublishInfo)) != EOK) { + LOGE("PublishDiscovery memset_s failed."); + return ERR_DM_FAILED; + } publishInfo.publishId = dmPublishInfo.publishId; publishInfo.mode = static_cast(dmPublishInfo.mode); publishInfo.medium = ExchangeMedium::AUTO; @@ -158,7 +162,10 @@ int32_t SoftbusConnector::UnPublishDiscovery(int32_t publishId) int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) { SubscribeInfo subscribeInfo; - (void)memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + if (memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)) != EOK) { + LOGE("StartDiscovery memset_s failed."); + return ERR_DM_FAILED; + } subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; subscribeInfo.mode = static_cast(dmSubscribeInfo.mode); subscribeInfo.medium = static_cast(dmSubscribeInfo.medium); @@ -192,7 +199,10 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) int32_t SoftbusConnector::StartDiscovery(const uint16_t subscribeId) { SubscribeInfo subscribeInfo; - (void)memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + if (memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)) != EOK) { + LOGE("StartDiscovery memset_s failed."); + return ERR_DM_FAILED; + } subscribeInfo.subscribeId = subscribeId; subscribeInfo.mode = static_cast(DmDiscoverMode::DM_DISCOVER_MODE_ACTIVE); subscribeInfo.medium = static_cast(DmExchangeMedium::DM_AUTO); @@ -255,6 +265,11 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId) LOGE("addrInfo is nullptr."); return; } + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + remoteUdidHash_.c_str(), remoteUdidHash_.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); + return; + } int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult); if (ret != DM_OK) { LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); @@ -327,7 +342,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); @@ -335,20 +350,20 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); @@ -357,32 +372,46 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo) { - (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed."); + return; + } + if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != DM_OK) { + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); + return; } if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + return; } + dmDeviceInfo.deviceTypeId = deviceInfo.devType; dmDeviceInfo.range = deviceInfo.range; } void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceBasicInfo &dmDeviceBasicInfo) { - (void)memset_s(&dmDeviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (memset_s(&dmDeviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed."); + return; + } + if (memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))) != DM_OK) { + std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); + return; } if (memcpy_s(dmDeviceBasicInfo.deviceName, sizeof(dmDeviceBasicInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { + std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + return; } + dmDeviceBasicInfo.deviceTypeId = deviceInfo.devType; } @@ -639,38 +668,40 @@ std::string SoftbusConnector::GetNetworkIdByDeviceId(const std::string &deviceId LOGE("[SOFTBUS]GetNodeKeyInfo failed."); } if (reinterpret_cast(mUdid) == deviceId) { + FreeNodeInfo(nodeInfo); return static_cast(nodeBasicInfo->networkId); } } + FreeNodeInfo(nodeInfo); return ""; } -void SoftbusConnector::SetPkgName(std::string pkgName) +void SoftbusConnector::SetProcessInfo(ProcessInfo processInfo) { - LOGI("SoftbusConnector::SetPkgName"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_.push_back(pkgName); + LOGI("SoftbusConnector::SetProcessInfo"); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_.push_back(processInfo); } -void SoftbusConnector::SetPkgNameVec(std::vector pkgNameVec) +void SoftbusConnector::SetProcessInfoVec(std::vector processInfoVec) { - LOGI("SoftbusConnector::SetPkgNameVec"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_ = pkgNameVec; + LOGI("SoftbusConnector::SetProcessInfoVec"); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_ = processInfoVec; } -std::vector SoftbusConnector::GetPkgName() +std::vector SoftbusConnector::GetProcessInfo() { - LOGI("SoftbusConnector::GetPkgName"); - std::lock_guard lock(pkgNameVecMutex_); - return pkgNameVec_; + LOGI("In"); + std::lock_guard lock(processInfoVecMutex_); + return processInfoVec_; } -void SoftbusConnector::ClearPkgName() +void SoftbusConnector::ClearProcessInfo() { - LOGI("SoftbusConnector::SetPkgName vec"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_.clear(); + LOGI("In"); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_.clear(); } void SoftbusConnector::HandleDeviceOnline(std::string deviceId, int32_t authForm) @@ -687,6 +718,15 @@ void SoftbusConnector::HandleDeviceOffline(std::string deviceId) return; } +void SoftbusConnector::DeleteOffLineTimer(std::string &udidHash) +{ + LOGI("SoftbusConnector::DeleteOffLineTimer"); + remoteUdidHash_ = udidHash; + if (deviceStateManagerCallback_ != nullptr) { + deviceStateManagerCallback_->DeleteOffLineTimer(udidHash); + } +} + bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) { LOGI("Check the device is online."); @@ -694,7 +734,7 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) NodeBasicInfo *nodeInfo = nullptr; if (GetAllNodeDeviceInfo(DM_PKG_NAME, &nodeInfo, &deviceCount) != DM_OK) { LOGE("[SOFTBUS]GetAllNodeDeviceInfo failed."); - return ERR_DM_FAILED; + return false; } for (int32_t i = 0; i < deviceCount; ++i) { NodeBasicInfo *nodeBasicInfo = nodeInfo + i; @@ -706,10 +746,12 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) std::string udid = reinterpret_cast(mUdid); if (udid == targetDeviceId) { LOGI("The device is online."); + FreeNodeInfo(nodeInfo); return true; } } LOGI("The device is not online."); + FreeNodeInfo(nodeInfo); return false; } @@ -726,6 +768,7 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(deviceId, reinterpret_cast(deviceIdHash)) != DM_OK) { LOGE("get deviceIdHash by deviceId: %{public}s failed.", GetAnonyString(deviceId).c_str()); + FreeNodeInfo(nodeInfo); return info; } for (int32_t i = 0; i < deviceCount; ++i) { @@ -734,6 +777,7 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device if (GetNodeKeyInfo(DM_PKG_NAME, nodeBasicInfo->networkId, NodeDeviceInfoKey::NODE_KEY_UDID, mUdid, sizeof(mUdid)) != DM_OK) { LOGE("[SOFTBUS]GetNodeKeyInfo failed."); + FreeNodeInfo(nodeInfo); return info; } std::string udid = reinterpret_cast(mUdid); @@ -753,16 +797,23 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo) { - (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); + return; + } + if (memcpy_s(dmDeviceInfo.networkId, sizeof(dmDeviceInfo.networkId), nodeBasicInfo.networkId, - std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))) != DM_OK) { + std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); + return; } if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DM_OK) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + return; } + dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId; std::string extraData = dmDeviceInfo.extraData; nlohmann::json extraJson; diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index ba32951e47aa0c211c9b2d48e749ee86e5f09da4..9730b6861196211ea30bef4d220c3218e37bd57d 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -25,18 +25,9 @@ namespace OHOS { namespace DistributedHardware { -namespace { -static QosTV g_qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, -}; -static uint32_t g_qosTVParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); -} - std::shared_ptr SoftbusSession::sessionCallback_ = nullptr; constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; -constexpr int32_t INTERCEPT_STRING_LENGTH = 20; +constexpr int32_t MAX_DATA_LEN = 65535; static void OnShutdown(int32_t socket, ShutdownReason reason) { @@ -54,6 +45,10 @@ static void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t q { LOGI("[SOFTBUS]OnQos, socket: %{public}d, QoSEvent: %{public}d, qosCount: %{public}u", socket, (int32_t)eventId, qosCount); + if (qosCount > QOS_TYPE_BUTT) { + LOGE("OnQos invalid qosCount"); + return; + } for (uint32_t idx = 0; idx < qosCount; idx++) { LOGI("QosTV: type: %{public}d, value: %{public}d", (int32_t)qos[idx].qos, qos[idx].value); } @@ -62,7 +57,10 @@ static void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t q SoftbusSession::SoftbusSession() { LOGD("SoftbusSession constructor."); - (void)memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)); + if (memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)) != DM_OK) { + LOGE("SoftbusSession::SoftbusSession memset_s failed."); + } + iSocketListener_.OnShutdown = OnShutdown; iSocketListener_.OnBytes = OnBytes; iSocketListener_.OnQos = OnQos; @@ -118,13 +116,6 @@ int32_t SoftbusSession::CloseAuthSession(int32_t sessionId) return DM_OK; } -int32_t SoftbusSession::CloseUnbindSession(int32_t socket) -{ - LOGI("CloseUnbindSession."); - Shutdown(socket); - return DM_OK; -} - int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) { char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; @@ -189,7 +180,7 @@ void SoftbusSession::OnSessionClosed(int sessionId) void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - if (sessionId < 0 || data == nullptr || dataLen <= 0) { + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { LOGI("[SOFTBUS]fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); return; @@ -216,41 +207,5 @@ void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned i } LOGI("completed."); } - -void SoftbusSession::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) -{ - sessionCallback_->OnUnbindSessionOpened(socket, info); - LOGI("SoftbusSession::OnUnbindSessionOpened success, socket: %{public}d.", socket); -} - -int32_t SoftbusSession::OpenUnbindSession(const std::string &netWorkId) -{ - std::string localSessionName = DM_UNBIND_SESSION_NAME + netWorkId.substr(0, INTERCEPT_STRING_LENGTH); - SocketInfo info = { - .name = const_cast(localSessionName.c_str()), - .peerName = const_cast(DM_UNBIND_SESSION_NAME), - .peerNetworkId = const_cast(netWorkId.c_str()), - .pkgName = const_cast(DM_PKG_NAME), - .dataType = DATA_TYPE_BYTES - }; - - int32_t socket = Socket(info); - if (socket <= 0) { - LOGE("[SOFTBUS]create socket failed, socket: %{public}d", socket); - return socket; - } - - int32_t ret = Bind(socket, g_qosInfo, g_qosTVParamIndex, &iSocketListener_); - if (ret < DM_OK) { - LOGE("[SOFTBUS]OpenUnbindSession failed, netWorkId: %{public}s, socket: %{public}d", - GetAnonyString(netWorkId).c_str(), socket); - sessionCallback_->BindSocketFail(); - Shutdown(socket); - return ret; - } - LOGI("OpenUnbindSession success. socket: %{public}d.", socket); - sessionCallback_->BindSocketSuccess(socket); - return socket; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index b27b42df7b4d7462726913320d0a17a042cd2433..ef62fddad0f1669fef39306a0cd994835f5cd86f 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -17,13 +17,15 @@ #include +#include "app_manager.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_distributed_hardware_load.h" #include "dm_log.h" +#include "dm_radar_helper.h" +#include "dm_softbus_cache.h" #include "multiple_user_connector.h" -#include "app_manager.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_common_event_manager.h" #include "parameter.h" @@ -79,6 +81,11 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr(hiChainConnector_, listener); } + if (dpInitedCallback_ == nullptr) { + dpInitedCallback_ = sptr(new DpInitedCallback()); + DeviceProfileConnector::GetInstance().SubscribeDeviceProfileInited(dpInitedCallback_); + } + listener_ = listener; LOGI("Init success, singleton initialized"); return DM_OK; } @@ -98,6 +105,8 @@ void DeviceManagerServiceImpl::Release() softbusConnector_ = nullptr; abilityMgr_ = nullptr; hiChainConnector_ = nullptr; + DeviceProfileConnector::GetInstance().UnSubscribeDeviceProfileInited(); + dpInitedCallback_ = nullptr; } int32_t DeviceManagerServiceImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, @@ -147,47 +156,35 @@ int32_t DeviceManagerServiceImpl::UnPublishDeviceDiscovery(const std::string &pk return publishMgr_->UnPublishDeviceDiscovery(pkgName, publishId); } -int32_t DeviceManagerServiceImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - if (pkgName.empty() || deviceId.empty()) { - LOGE("DeviceManagerServiceImpl::AuthenticateDevice failed, pkgName is %{public}s, deviceId is %{public}s," - "extra is %{public}s", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); -} - -int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) +int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { - if (pkgName.empty() || networkId.empty()) { - LOGE("DeviceManagerServiceImpl::UnAuthenticateDevice failed, pkgName is %{public}s, networkId is %{public}s", - pkgName.c_str(), GetAnonyString(networkId).c_str()); + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerServiceImpl::UnAuthenticateDevice failed, pkgName is %{public}s, udid is %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnAuthenticateDevice(pkgName, networkId); + return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); } -int32_t DeviceManagerServiceImpl::BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam) +int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) { - if (pkgName.empty() || udidHash.empty()) { - LOGE("DeviceManagerServiceImpl::BindDevice failed, pkgName is %{public}s, udidHash is %{public}s, bindParam is" - "%{public}s", pkgName.c_str(), GetAnonyString(udidHash).c_str(), bindParam.c_str()); + if (pkgName.empty()) { + LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed"); return ERR_DM_INPUT_PARA_INVALID; } - - return authMgr_->AuthenticateDevice(pkgName, authType, udidHash, bindParam); + return authMgr_->StopAuthenticateDevice(pkgName); } -int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udidHash) +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { - if (pkgName.empty() || udidHash.empty()) { - LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udidHash is %{public}s", - pkgName.c_str(), GetAnonyString(udidHash).c_str()); + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnBindDevice(pkgName, udidHash); + return authMgr_->UnBindDevice(pkgName, udid, bindLevel); } int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action, @@ -220,27 +217,35 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf } char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string requestDeviceId = static_cast(localUdid); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - LOGI("The offline device bind type is %{public}d.", offlineParam.bindType); - if (offlineParam.leftAclNumber == 0 && offlineParam.bindType == INVALIED_TYPE) { - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == IDENTICAL_ACCOUNT_TYPE) { - LOGI("The offline device is identical account bind type."); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE) { - LOGI("The offline device is device-level bind type."); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE) { - LOGI("The offline device is app-level bind type."); - softbusConnector_->SetPkgNameVec(offlineParam.pkgNameVec); + std::string requestDeviceId = std::string(localUdid); + std::map userIdAndBindLevel = + DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(requestDeviceId, trustDeviceId); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (userIdAndBindLevel.empty() || userIdAndBindLevel.find(processInfo.userId) == userIdAndBindLevel.end()) { + userIdAndBindLevel[processInfo.userId] = INVALIED_TYPE; + } + for (const auto &item : userIdAndBindLevel) { + if (item.second == INVALIED_TYPE) { + LOGI("The offline device is identical account bind type."); + devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + processInfo.userId = item.first; + softbusConnector_->SetProcessInfo(processInfo); + } else if (item.second == DEVICE) { + LOGI("The offline device is device bind type."); + devInfo.authForm = DmAuthForm::PEER_TO_PEER; + processInfo.userId = item.first; + softbusConnector_->SetProcessInfo(processInfo); + } else if (item.second == SERVICE || item.second == APP) { + LOGI("The offline device is APP_PEER_TO_PEER_TYPE bind type."); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + item.first); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } - if (offlineParam.leftAclNumber == 0) { - LOGI("Delete credential in HandleDeviceOffline."); - hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetCurrentAccountUserID()); - } } void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -248,7 +253,7 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo LOGI("DeviceManagerServiceImpl::HandleOnline"); std::string trustDeviceId = ""; if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { - LOGE("HandleDeviceOffline get udid failed."); + LOGE("HandleOnline get udid failed."); return; } std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); @@ -258,35 +263,37 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo } char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string requestDeviceId = static_cast(localUdid); + std::string requestDeviceId = std::string(localUdid); uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); LOGI("The online device bind type is %{public}d.", bindType); - if (bindType == INVALIED_TYPE) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (bindType == INVALIED_TYPE && isCredentialType_.load()) { PutIdenticalAccountToAcl(requestDeviceId, trustDeviceId); devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + isCredentialType_.store(false); + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == IDENTICAL_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == DEVICE_PEER_TO_PEER_TYPE) { devInfo.authForm = DmAuthForm::PEER_TO_PEER; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == APP_PEER_TO_PEER_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::PEER_TO_PEER; } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } LOGI("DeviceManagerServiceImpl::HandleOnline success devInfo auform %{public}d.", devInfo.authForm); @@ -309,6 +316,10 @@ void DeviceManagerServiceImpl::HandleDeviceStatusChange(DmDeviceState devState, LOGE("get deviceId: %{public}s failed", GetAnonyString(udiddHash).c_str()); return; } + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } } @@ -330,6 +341,18 @@ std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string & int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) { + std::string peerUdid = ""; + softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); + struct RadarInfo info = { + .funcName = "OnSessionOpened", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .isTrust = static_cast(TrustStatus::NOT_TRUST), + .peerUdid = peerUdid, + .channelId = sessionId, + }; + if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) { + LOGE("ReportAuthSessionOpenCb failed"); + } return SoftbusSession::OnSessionOpened(sessionId, result); } @@ -367,6 +390,7 @@ int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, c LOGE("credentialMgr_ is nullptr"); return ERR_DM_POINT_NULL; } + isCredentialType_.store(true); return credentialMgr_->ImportCredential(pkgName, credentialInfo); } @@ -381,6 +405,7 @@ int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, c LOGE("credentialMgr_ is nullptr"); return ERR_DM_POINT_NULL; } + isCredentialType_.store(false); return credentialMgr_->DeleteCredential(pkgName, deleteInfo); } @@ -421,6 +446,7 @@ int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, c LOGE("failed to import devices credential"); return ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED; } + isCredentialType_.store(true); return DM_OK; } @@ -436,6 +462,7 @@ int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, c LOGE("failed to delete devices credential"); return ERR_DM_HICHAIN_CREDENTIAL_DELETE_FAILED; } + isCredentialType_.store(false); return DM_OK; } @@ -481,7 +508,7 @@ int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkg int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { - LOGE("RegisterUiStateCallback failed, pkgName is empty"); + LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } if (authMgr_ == nullptr) { @@ -610,15 +637,15 @@ void DeviceManagerServiceImpl::PutIdenticalAccountToAcl(std::string requestDevic LOGI("DeviceManagerServiceImpl::PutIdenticalAccountAcl start."); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; Crypto::GetUdidHash(requestDeviceId, reinterpret_cast(localDeviceId)); - std::string localUdidHash = static_cast(localDeviceId); + std::string localUdidHash = std::string(localDeviceId); DmAclInfo aclInfo; aclInfo.bindType = IDENTICAL_ACCOUNT; aclInfo.trustDeviceId = trustDeviceId; aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId(); + accesser.requestUserId = MultipleUserConnector::GetFirstForegroundUserId(); + accesser.requestAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldAccountId(accesser.requestAccountId); accesser.requestDeviceId = requestDeviceId; @@ -634,6 +661,10 @@ int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); if (deviceStateMgr_->CheckIsOnline(udid)) { LOGI("DeviceManagerServiceImpl DpAclAdd identical account and online"); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); deviceStateMgr_->OnDeviceOnline(udid, DmAuthForm::IDENTICAL_ACCOUNT); } LOGI("DeviceManagerServiceImpl::DpAclAdd completed"); @@ -659,36 +690,57 @@ std::unordered_map DeviceManagerServiceImpl::GetAppTrus return DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgname, deviceId); } -void DeviceManagerServiceImpl::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) +void DeviceManagerServiceImpl::LoadHardwareFwkService() { - SoftbusSession::OnUnbindSessionOpened(socket, info); + DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); } -void DeviceManagerServiceImpl::OnUnbindSessionCloseed(int32_t socket) +void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) { - SoftbusSession::OnSessionClosed(socket); + LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", + GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); + if (notifyOffline) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = localUserId; + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(deviceStateMgr_); + deviceStateMgr_->OnDeviceOffline(peerUdid); + } } -void DeviceManagerServiceImpl::OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen) +void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) { - SoftbusSession::OnBytesReceived(socket, data, dataLen); + LOGI("PreUserId %{public}d.", preUserId); + char localDeviceId[DEVICE_UUID_LENGTH]; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = reinterpret_cast(localDeviceId); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(preUserId); } -void DeviceManagerServiceImpl::LoadHardwareFwkService() +void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) { - DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); + LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(remoteUdid, userId); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(userId); } -void DeviceManagerServiceImpl::AccountCommonEventCallback(int32_t userId, std::string commonEventType) +void DeviceManagerServiceImpl::HandleUserSwitched(const std::map &deviceMap, + int32_t currentUserId, int32_t beforeUserId) { - if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED || - commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - authMgr_->CommonEventCallback(userId, commonEventType); - LOGI("DeviceManagerServiceImpl::account event: %{public}s, userId: %{public}s", - commonEventType.c_str(), GetAnonyInt32(userId).c_str()); - return; - } - LOGI("DeviceManagerServiceImpl::AccountCommonEventCallback error."); + LOGI("currentUserId: %{public}s, beforeUserId: %{public}s", GetAnonyInt32(currentUserId).c_str(), + GetAnonyInt32(beforeUserId).c_str()); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -724,6 +776,230 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) authMgr_->HandleDeviceNotTrust(udid); } +int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + return DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); +} + +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::vector userIds; + userIds.push_back(userId); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); +} + +void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::multimap devIdAndUserMap = + DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, + remoteUserId, remoteAccountHash); + CHECK_NULL_VOID(listener_); + std::string uuid = ""; + SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); + listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT); + for (const auto &item : devIdAndUserMap) { + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(item.first, item.second, + remoteUdid, remoteUserId); + if (notifyOffline) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = item.second; + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(deviceStateMgr_); + deviceStateMgr_->OnDeviceOffline(remoteUdid); + } + } +} + +DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) +{ + LOGI("BindType %{public}d.", bindType); + DmAuthForm authForm = DmAuthForm::INVALID_TYPE; + if (bindType == DM_IDENTICAL_ACCOUNT) { + authForm = IDENTICAL_ACCOUNT; + } else if (bindType == DM_POINT_TO_POINT) { + authForm = PEER_TO_PEER; + } else if (bindType == DM_ACROSS_ACCOUNT) { + authForm = ACROSS_ACCOUNT; + } else { + LOGE("Invalied bindType."); + } + return authForm; +} + +void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + if (bindType == DM_INVALIED_BINDTYPE) { + LOGE("Invalied bindtype."); + return; + } + CHECK_NULL_VOID(authMgr_); + authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); +} + +void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + ProcessInfo processInfo = + DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + if (processInfo.pkgName.empty()) { + LOGE("Pkgname is empty."); + return; + } + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfo(processInfo); + softbusConnector_->HandleDeviceOffline(remoteUdid); +} + +void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid) +{ + LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s", + GetAnonyString(remoteUdid).c_str(), GetIntegerList(foregroundUserIds).c_str(), + GetIntegerList(backgroundUserIds).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::vector rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end()); + std::vector rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end()); + std::vector localUserIds; + int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds); + if (ret != DM_OK || localUserIds.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + return; + } + DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, + rmtFrontUserIdsTemp, rmtBackUserIdsTemp); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, + localUserIds, localUdid); + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, + localUserIds, localUdid); +} + +void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) +{ + LOGI("In"); + CHECK_NULL_VOID(deviceStateMgr_); + CHECK_NULL_VOID(softbusConnector_); + std::string trustDeviceId = ""; + if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { + LOGE("get udid failed."); + return; + } + std::string udidHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); + if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHash.c_str(), udidHash.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHash).c_str()); + return; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); + std::string requestDeviceId = static_cast(localUdid); + uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); + LOGI("bind type is %{public}d.", bindType); + if (bindType == INVALIED_TYPE) { + return; + } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || + bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); + } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } + deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); +} + +void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) +{ + CHECK_NULL_VOID(credentialMgr_); + credentialMgr_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); +} + +int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) +{ + CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + LOGI("delete ACL size is %{public}zu, appId %{public}s", profiles.size(), GetAnonyString(appId).c_str()); + if (profiles.size() == 0) { + return DM_OK; + } + std::vector> delACLInfoVec; + std::vector userIdVec; + for (auto &item : profiles) { + int64_t tokenId = item.GetAccesser().GetAccesserTokenId(); + if (accessTokenId != static_cast(tokenId)) { + continue; + } + DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); + listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); + if (item.GetBindLevel() == DEVICE) { + userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); + delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), + item.GetAccessee().GetAccesseeDeviceId())); + } + } + if (delACLInfoVec.size() == 0) { + LOGI("delACLInfoVec is empty"); + return DM_OK; + } + if (userIdVec.size() == 0) { + LOGI("userIdVec is empty"); + return DM_OK; + } + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->DeleteGroupByACL(delACLInfoVec, userIdVec); + return DM_OK; +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId) +{ + LOGI("localUserId %{public}d.", localUserId); + char localdeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localdeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localdeviceId); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); +} + +int32_t DeviceManagerServiceImpl::SaveOnlineDeviceInfo(const std::vector &deviceList) +{ + CHECK_NULL_RETURN(deviceStateMgr_, ERR_DM_POINT_NULL); + for (auto item : deviceList) { + deviceStateMgr_->SaveOnlineDeviceInfo(item); + } + return DM_OK; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 2864f44b7d08e5baa66654ddcf733b67314af080..d08c6c5d831ecf4572cb226067adfc4d6f642d28 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -24,6 +24,7 @@ namespace OHOS { namespace DistributedHardware { +constexpr uint32_t DEVICE_BIUND_LEVEL = 1; DeviceManagerServiceImpl::DeviceManagerServiceImpl() { LOGI("DeviceManagerServiceImpl constructor"); @@ -109,37 +110,21 @@ int32_t DeviceManagerServiceImpl::UnPublishDeviceDiscovery(const std::string &pk return DM_OK; } -int32_t DeviceManagerServiceImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) +int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { (void)pkgName; - (void)authType; - (void)deviceId; - (void)extra; - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) -{ - (void)pkgName; - (void)networkId; - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam) -{ - (void)pkgName; - (void)authType; - (void)udidHash; - (void)bindParam; + (void)udid; + (void)bindLevel; return DM_OK; } -int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udidHash) +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { (void)pkgName; - (void)udidHash; + (void)udid; + (void)bindLevel; return DM_OK; } @@ -416,24 +401,6 @@ std::unordered_map DeviceManagerServiceImpl::GetAppTrus return tmp; } -void DeviceManagerServiceImpl::OnUnbindSessionOpened(int32_t sessionId, PeerSocketInfo info) -{ - (void)sessionId; - (void)info; -} - -void DeviceManagerServiceImpl::OnUnbindSessionCloseed(int32_t sessionId) -{ - (void)sessionId; -} - -void DeviceManagerServiceImpl::OnUnbindBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) -{ - (void)sessionId; - (void)data; - (void)dataLen; -} - void DeviceManagerServiceImpl::LoadHardwareFwkService() { } @@ -450,12 +417,6 @@ int32_t DeviceManagerServiceImpl::IsSameAccount(const std::string &udid) return DM_OK; } -void DeviceManagerServiceImpl::AccountCommonEventCallback(int32_t userId, std::string commonEventType) -{ - (void)userId; - (void)commonEventType; -} - void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) { (void)commonEventType; @@ -487,6 +448,133 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) return; } +int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + (void)pkgName; + (void)udid; + (void)tokenId; + (void)localUdid; + return DEVICE_BIUND_LEVEL; +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId) +{ + (void)userId; + (void)accountId; + return std::multimap {}; +} + +void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid) +{ + (void)remoteUserId; + (void)remoteAccountHash; + (void)remoteUdid; + return; +} + +void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) +{ + (void)remoteUserId; + (void)remoteUdid; + return; +} + +void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId) +{ + (void)remoteUserId; + (void)remoteUdid; + (void)tokenId; + return; +} + +void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) +{ + (void)localUdid; + (void)localUserId; + (void)peerUdid; + (void)peerUserId; + return; +} + +void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) +{ + (void)preUserId; + return; +} + +void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) +{ + (void)devInfo; + return; +} + +void DeviceManagerServiceImpl::HandleUserSwitched(const std::map &deviceMap, + int32_t currentUserId, int32_t beforeUserId) +{ + (void)deviceMap; + (void)currentUserId; + (void)beforeUserId; + return; +} + +int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + (void)pkgName; + return 0; +} + +void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) +{ + (void)deviceList; + (void)deviceTypeId; + (void)errcode; + return; +} + +int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) +{ + (void)appId; + (void)accessTokenId; + return 0; +} + +void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid) +{ + (void)foregroundUserIds; + (void)backgroundUserIds; + (void)remoteUdid; +} + +void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid) +{ + (void)preUserId; + (void)remoteUdid; +} + +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId) +{ + (void)userId; +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId) +{ + (void)localUserId; + return {}; +} + +int32_t DeviceManagerServiceImpl::SaveOnlineDeviceInfo(const std::vector &deviceList) +{ + (void)deviceList; + return DM_OK; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 71932f11dd86cbd34f3fb19ff954dca0768fd81c..bce366f5156c7e61fb52e22a361d3bf8f569118e 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -20,6 +20,8 @@ #include "dm_adapter_manager.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_device_info.h" #include "dm_distributed_hardware_load.h" #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -109,7 +111,7 @@ void DmDeviceStateManager::OnDeviceOnline(std::string deviceId, int32_t authForm } } ProcessDeviceStateChange(DEVICE_STATE_ONLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) @@ -125,7 +127,7 @@ void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) devInfo = stateDeviceInfos_[deviceId]; } ProcessDeviceStateChange(DEVICE_STATE_OFFLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -138,7 +140,7 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe SaveOnlineDeviceInfo(devInfo); DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_STATE_OFFLINE: StartOffLineTimer(devInfo); @@ -149,12 +151,12 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe softbusConnector_->EraseUdidFromMap(udid); } ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_INFO_CHANGED: ChangeDeviceInfo(devInfo); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; default: LOGE("HandleDeviceStatusChange error, unknown device state = %{public}d", devState); @@ -164,15 +166,11 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe void DmDeviceStateManager::ProcessDeviceStateChange(const DmDeviceState devState, const DmDeviceInfo &devInfo) { - if (softbusConnector_ == nullptr || listener_ == nullptr) { - LOGE("ProcessDeviceStateChange failed, callback_ptr is null."); - return; - } - std::vector pkgName = softbusConnector_->GetPkgName(); - if (pkgName.size() == 0) { - listener_->OnDeviceStateChange(std::string(DM_PKG_NAME), devState, devInfo); - } else { - for (auto item : pkgName) { + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); + std::vector processInfoVec = softbusConnector_->GetProcessInfo(); + for (const auto &item : processInfoVec) { + if (!item.pkgName.empty()) { listener_->OnDeviceStateChange(item, devState, devInfo); } } @@ -200,7 +198,10 @@ void DmDeviceStateManager::OnDbReady(const std::string &pkgName, const std::stri } if (listener_ != nullptr) { DmDeviceState state = DEVICE_INFO_READY; - listener_->OnDeviceStateChange(pkgName, state, saveInfo); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + listener_->OnDeviceStateChange(processInfo, state, saveInfo); } } @@ -212,23 +213,35 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) LOGE("fail to get udid by networkId"); return; } - LOGI("Register offline timer for deviceUdid: %{public}s", GetAnonyString(deviceUdid).c_str()); + char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(deviceUdid, reinterpret_cast(udidHash)) != DM_OK) { + LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(deviceUdid).c_str()); + return; + } + LOGI("Register offline timer for udidHash: %{public}s", GetAnonyString(std::string(udidHash)).c_str()); std::lock_guard mutexLock(timerMapMutex_); for (auto &iter : stateTimerInfoMap_) { - if ((iter.first == deviceUdid) && (timer_ != nullptr)) { + if ((iter.first == std::string(udidHash)) && (timer_ != nullptr)) { timer_->DeleteTimer(iter.second.timerName); stateTimerInfoMap_.erase(iter.first); + auto idIter = udidhash2udidMap_.find(udidHash); + if (idIter != udidhash2udidMap_.end()) { + udidhash2udidMap_.erase(idIter->first); + } break; } } - if (stateTimerInfoMap_.find(deviceUdid) == stateTimerInfoMap_.end()) { - std::string timerName = std::string(STATE_TIMER_PREFIX) + GetAnonyString(deviceUdid); + if (stateTimerInfoMap_.find(std::string(udidHash)) == stateTimerInfoMap_.end()) { + std::string timerName = std::string(STATE_TIMER_PREFIX) + GetAnonyString(std::string(udidHash)); StateTimerInfo stateTimer = { .timerName = timerName, .networkId = deviceInfo.networkId, .isStart = false, }; - stateTimerInfoMap_[deviceUdid] = stateTimer; + stateTimerInfoMap_[std::string(udidHash)] = stateTimer; + } + if (udidhash2udidMap_.find(std::string(udidHash)) == udidhash2udidMap_.end()) { + udidhash2udidMap_[std::string(udidHash)] = deviceUdid; } } @@ -251,18 +264,43 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) } } +void DmDeviceStateManager::DeleteOffLineTimer(std::string udidHash) +{ + std::lock_guard mutexLock(timerMapMutex_); + LOGI("DELETE offline timer for networkId: %{public}s", GetAnonyString(udidHash).c_str()); + if (timer_ == nullptr || udidHash.empty()) { + return; + } + auto iter = stateTimerInfoMap_.find(udidHash); + if (iter != stateTimerInfoMap_.end()) { + timer_->DeleteTimer(iter->second.timerName); + iter->second.isStart = false; + stateTimerInfoMap_.erase(iter->first); + auto idIter = udidhash2udidMap_.find(udidHash); + if (idIter != udidhash2udidMap_.end()) { + udidhash2udidMap_.erase(idIter->first); + } + } + return; +} + void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) { std::lock_guard mutexLock(timerMapMutex_); for (auto iter = stateTimerInfoMap_.begin(); iter != stateTimerInfoMap_.end(); iter++) { if (((iter->second).timerName == name) && (hiChainConnector_ != nullptr)) { - LOGI("remove hichain group with deviceId: %{public}s", GetAnonyString(iter->first).c_str()); - hiChainConnector_->DeleteTimeOutGroup((iter->first).c_str()); + auto idIter = udidhash2udidMap_.find(iter->first); + if (idIter == udidhash2udidMap_.end()) { + LOGE("remove hichain group find deviceId: %{public}s failed.", GetAnonyString(iter->first).c_str()); + break; + } + LOGI("remove hichain group with deviceId: %{public}s", GetAnonyString(idIter->second).c_str()); + hiChainConnector_->DeleteTimeOutGroup((idIter->second).c_str()); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - DeleteGroupByDP(iter->first); - uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(iter->first); + DeleteGroupByDP(idIter->second); + uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(idIter->second); if (res == 0) { - hiChainAuthConnector_->DeleteCredential(iter->first, + hiChainAuthConnector_->DeleteCredential(idIter->second, MultipleUserConnector::GetCurrentAccountUserID()); } #endif @@ -470,5 +508,17 @@ bool DmDeviceStateManager::CheckIsOnline(const std::string &udid) } return false; } + +void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) +{ + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); + std::vector processInfos = softbusConnector_->GetProcessInfo(); + softbusConnector_->ClearProcessInfo(); + LOGI("pkgName size: %{public}zu", processInfos.size()); + for (const auto &item : processInfos) { + listener_->OnDeviceScreenStateChange(item, devInfo); + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/discovery/dm_discovery_manager.cpp b/services/implementation/src/discovery/dm_discovery_manager.cpp index 594b949f1f0f8dc8a50fdf9ea753bf279a57f613..a872d4f02bc77e16c05380074e8c53888753e6b6 100644 --- a/services/implementation/src/discovery/dm_discovery_manager.cpp +++ b/services/implementation/src/discovery/dm_discovery_manager.cpp @@ -130,7 +130,9 @@ int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint } if (!discoveryContextMap_.empty()) { discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + } } } softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); @@ -160,9 +162,6 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, DmDeviceInfo info.authForm = DmAuthForm::INVALID_TYPE; GetAuthForm(localDeviceId, info.deviceId, filterPara.isTrusted, info.authForm); filterPara.authForm = info.authForm; - if (filter.IsValidDevice(discoveryContext.filterOp, discoveryContext.filters, filterPara)) { - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); - } return; } @@ -223,9 +222,6 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, DmAuthForm authForm = DmAuthForm::INVALID_TYPE; GetAuthForm(localDeviceId, info.deviceId, filterPara.isTrusted, authForm); filterPara.authForm = authForm; - if (filter.IsValidDevice(discoveryContext.filterOp, discoveryContext.filters, filterPara)) { - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); - } return; } @@ -244,11 +240,12 @@ void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t s } if (!discoveryContextMap_.empty()) { discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + } } } softbusConnector_->StopDiscovery(subscribeId); - listener_->OnDiscoveryFailed(pkgName, (uint32_t)subscribeId, failedReason); } void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) @@ -258,7 +255,6 @@ void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t std::lock_guard autoLock(locks_); discoveryContextMap_[pkgName].subscribeId = (uint32_t)subscribeId; } - listener_->OnDiscoverySuccess(pkgName, subscribeId); } void DmDiscoveryManager::HandleDiscoveryTimeout(std::string name) diff --git a/services/implementation/src/publish/dm_publish_manager.cpp b/services/implementation/src/publish/dm_publish_manager.cpp index 81fef1b9ffabb954434a027cfa04cc239d7961d2..b093981612ff778c6d9277ddcbe0df2bc013fe2a 100644 --- a/services/implementation/src/publish/dm_publish_manager.cpp +++ b/services/implementation/src/publish/dm_publish_manager.cpp @@ -93,7 +93,9 @@ int32_t DmPublishManager::UnPublishDeviceDiscovery(const std::string &pkgName, i if (!publishContextMap_.empty()) { publishContextMap_.erase(pkgName); softbusConnector_->UnRegisterSoftbusPublishCallback(pkgName); - timer_->DeleteTimer(std::string(PUBLISH_DISCOVERY_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(PUBLISH_DISCOVERY_TIMEOUT_TASK)); + } } return softbusConnector_->UnPublishDiscovery(publishId); } diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index f05823c4c2559c1b2d21678f63d5fe42d5db2df9..00ee00fc1ee2e8741a983ee3d0798047ec80a9aa 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -26,6 +26,7 @@ if (defined(ohos_lite)) { "include", "include/advertise", "include/discovery", + "include/notify", "include/softbus", "include/ipc/lite", "include/permission/lite", @@ -40,6 +41,7 @@ if (defined(ohos_lite)) { "${utils_path}/include/appInfo/lite", "${utils_path}/include/crypto", "${utils_path}/include/fwkload/lite", + "${utils_path}/include/kvadapter", "${utils_path}/include/timer/lite", "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/ipc", @@ -67,6 +69,7 @@ if (defined(ohos_lite)) { "src/ipc/lite/ipc_server_listenermgr.cpp", "src/ipc/lite/ipc_server_main.cpp", "src/ipc/lite/ipc_server_stub.cpp", + "src/notify/device_manager_service_notify.cpp", "src/permission/lite/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", @@ -116,12 +119,15 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "include/advertise", + "include/devicenamemgr", "include/discovery", "include/ipc", "include/ipc/standard", + "include/notify", "include/permission/standard", "include/pinholder", "include/publishcommonevent", + "include/relationshipsyncmgr", "include/softbus", "${common_path}/include", "${common_path}/include/dfx", @@ -135,6 +141,7 @@ if (defined(ohos_lite)) { "${softbuscache_parh}/include", "${utils_path}/include/appInfo/standard", "${utils_path}/include/crypto", + "${utils_path}/include/kvadapter", "${utils_path}/include/timer", ] } @@ -158,17 +165,27 @@ if (defined(ohos_lite)) { "src/advertise/advertise_manager.cpp", "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", + "src/devicenamemgr/account_boot_listener.cpp", + "src/devicenamemgr/local_device_name_mgr.cpp", + "src/devicenamemgr/settings_data_event_monitor.cpp", "src/discovery/discovery_filter.cpp", "src/discovery/discovery_manager.cpp", "src/ipc/standard/ipc_cmd_parser.cpp", "src/ipc/standard/ipc_server_client_proxy.cpp", "src/ipc/standard/ipc_server_listener.cpp", "src/ipc/standard/ipc_server_stub.cpp", + "src/notify/device_manager_service_notify.cpp", "src/permission/standard/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", "src/publishcommonevent/dm_account_common_event.cpp", + "src/publishcommonevent/dm_data_share_common_event.cpp", + "src/publishcommonevent/dm_package_common_event.cpp", "src/publishcommonevent/dm_screen_common_event.cpp", + "src/relationshipsyncmgr/dm_comm_tool.cpp", + "src/relationshipsyncmgr/dm_transport.cpp", + "src/relationshipsyncmgr/dm_transport_msg.cpp", + "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", ] @@ -192,22 +209,27 @@ if (defined(ohos_lite)) { "ability_base:want", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "eventhandler:libeventhandler", + "ffrt:libffrt", "hicollie:libhicollie", "hilog:libhilog", "init:libbeget_proxy", "init:libbegetutil", "ipc:ipc_core", "ipc:ipc_single", - "memmgr:memmgrclient", "openssl:libcrypto_shared", "os_account:libaccountkits", + "os_account:os_account_innerkits", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -234,6 +256,15 @@ if (defined(ohos_lite)) { external_deps += [ "power_manager:powermgr_client" ] } + if (support_memmgr) { + defines += [ "SUPPORT_MEMMGR" ] + external_deps += [ "memmgr:memmgrclient" ] + } + + if (device_manager_common) { + defines += [ "DEVICE_MANAGER_COMMON_FLAG" ] + } + public_external_deps = [ "json:nlohmann_json_static" ] subsystem_name = "distributedhardware" diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 6e2e243568e041aa644219983c3ef8caed012565..469f2486cdb938068def69ea30749188c225ca17 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -33,7 +33,9 @@ #include "dm_single_instance.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_account_common_event.h" +#include "dm_package_common_event.h" #include "dm_screen_common_event.h" +#include "relationship_sync_mgr.h" #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) #include "dm_publish_common_event.h" #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI @@ -52,9 +54,9 @@ public: int32_t InitSoftbusListener(); - void RegisterDeviceManagerListener(const std::string &pkgName); + void RegisterCallerAppId(const std::string &pkgName); - void UnRegisterDeviceManagerListener(const std::string &pkgName); + void UnRegisterCallerAppId(const std::string &pkgName); void UninitSoftbusListener(); @@ -75,14 +77,6 @@ public: int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid); - int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, - const std::string &extra); - - int32_t StartDeviceDiscovery(const std::string &pkgName, const uint16_t subscribeInfo, - const std::string &filterOptions); - - int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId); - int32_t PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo); int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId); @@ -92,10 +86,12 @@ public: int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); + int32_t StopAuthenticateDevice(const std::string &pkgName); + int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &bindParam); - int32_t UnBindDevice(const std::string &pkgName, const std::string &deviceId); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); @@ -180,10 +176,6 @@ public: int32_t UnbindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &unbindParam); - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); - void OnUnbindSessionCloseed(int32_t socket); - void OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen); - int32_t DpAclAdd(const std::string &udid); int32_t GetDeviceSecurityLevel(const std::string &pkgName, const std::string &networkId, int32_t &networkType); @@ -193,6 +185,24 @@ public: bool CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee); bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); void HandleDeviceNotTrust(const std::string &msg); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + void HandleDeviceTrustedChange(const std::string &msg); + void HandleUserIdCheckSumChange(const std::string &msg); +#endif + int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); + void ClearDiscoveryCache(const ProcessInfo &processInfo); + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus); + void SubscribePackageCommonEvent(); + int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + void ProcessSyncUserIds(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid); + int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); + void RemoveNotifyRecord(const ProcessInfo &processInfo); + int32_t RegDevStateCallbackToService(const std::string &pkgName); + int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList); private: bool IsDMServiceImplReady(); @@ -200,11 +210,57 @@ private: bool IsDMImplSoLoaded(); void UnloadDMServiceImplSo(); void UnloadDMServiceAdapter(); + void SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, + int32_t bindLevel); + void SendDeviceUnBindBroadCast(const std::vector &peerUdids, int32_t userId); + void SendAppUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId); + void SendServiceUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId); + void SendAccountLogoutBroadCast(const std::vector &peerUdids, const std::string &accountId, + const std::string &accountName, int32_t userId); + /** + * @brief send local foreground or background userids by broadcast + * + * @param peerUdids the broadcast target device udid list + * @param foregroundUserIds local foreground userids + * @param backgroundUserIds local background userids + */ + void SendUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, + bool isNeedResponse); + void SendUserRemovedBroadCast(const std::vector &peerUdids, int32_t userId); + /** + * @brief parse dsoftbus checksum msg + * + * @param msg checksum msg + * @param networkId remote device networkid + * @param discoveryType remote device link type, wifi or ble/br + * @return int32_t 0 for success + */ + int32_t ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType, bool &isChange); + void ProcessCheckSumByWifi(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds); + void ProcessCheckSumByBT(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds); + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void SubscribeAccountCommonEvent(); - void AccountCommonEventCallback(int32_t userId, std::string commonEventType); + void AccountCommonEventCallback(const std::string commonEventType, int32_t currentUserId, int32_t beforeUserId); void SubscribeScreenLockEvent(); void ScreenCommonEventCallback(std::string commonEventType); + void ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInfo); + int32_t ConvertUdidHashToAnoyDeviceId(const std::string &udidHash, std::string &anoyDeviceId); + int32_t GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash); + void HandleAccountLogout(int32_t userId, const std::string &accountId, const std::string &accountName); + void HandleUserRemoved(int32_t removedUserId); + /** + * @brief process the user switch + * + * @param currentUserId the user id which switched to foreground. + * @param beforeUserId the user id which switched to backend. + */ + void HandleUserSwitched(int32_t curUserId, int32_t preUserId); + void HandleUserIdsBroadCast(const std::vector &remoteUserIdInfos, + const std::string &remoteUdid, bool isNeedResponse); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); @@ -226,11 +282,13 @@ private: std::shared_ptr pinHolder_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::shared_ptr accountCommonEventManager_; + std::shared_ptr packageCommonEventManager_; std::shared_ptr screenCommonEventManager_; #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) std::shared_ptr publshCommonEventManager_; #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI #endif + std::string localNetWorkId_ = ""; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 3d9d2611856fc43c755d7151265cacdb6a49f1a6..bd17e5de1533baf83caec3954f77dd16290b703e 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -17,12 +17,16 @@ #define OHOS_DM_SERVICE_LISTENER_H #include +#include #include +#include #include -#include #include "dm_device_info.h" #include "idevice_manager_service_listener.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "kv_adapter_manager.h" +#endif #if !defined(__LITEOS_M__) #include "ipc_notify_dmfa_result_req.h" #include "ipc_server_listener.h" @@ -36,66 +40,84 @@ public: DeviceManagerServiceListener() {}; virtual ~DeviceManagerServiceListener() {}; - void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) override; + void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info) override; - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) override; + void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) override; - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) override; + void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) override; - void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) override; - - void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) override; + void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) override; void OnPublishResult(const std::string &pkgName, int32_t publishId, int32_t publishResult) override; - void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, - int32_t reason) override; + void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) override; - void OnUiCall(std::string &pkgName, std::string ¶mJson) override; + void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) override; - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override; + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override; - void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; - void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) override; - void DeleteDeviceIdFromMap(const std::string &deviceId, const std::string &pkgName); - void RegisterDmListener(const std::string &pkgName, const std::string &appId); - void UnRegisterDmListener(const std::string &pkgName); - std::string GetAppId(const std::string &pkgName); - std::string CalcDeviceId(const std::string &udidHash, const std::string &appId); - void SetUdidHashMap(const std::string &udidHash, const std::string &deviceId, const std::string &pkgName); - std::string GetDeviceId(const std::string &udidHash, const std::string &pkgName); - std::string GetUdidHash(const std::string &deviceId, const std::string &pkgName); - void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) override; - void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) override; - void OnCreateResult(const std::string &pkgName, int32_t result) override; - void OnDestroyResult(const std::string &pkgName, int32_t result) override; - void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) override; + void OnCreateResult(const ProcessInfo &processInfo, int32_t result) override; + void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) override; + void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) override; + void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; + void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override; + void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) override; + void OnAppUnintall(const std::string &pkgName) override; + void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, + int32_t status, std::string content) override; + void OnProcessRemove(const ProcessInfo &processInfo) override; + void OnDevStateCallbackAdd(const ProcessInfo &processInfo, const std::vector &deviceList) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); - void SetDeviceInfo(std::shared_ptr pReq, const std::string &pkgName, + void SetDeviceInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, + int32_t FillUdidAndUuidToDeviceInfo(const std::string &pkgName, DmDeviceInfo &dmDeviceInfo); + void ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, + void ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - std::string ComposeOnlineKey(const std::string &pkgName, const std::string &devId); + void SetDeviceScreenInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, + const DmDeviceInfo &deviceInfo); + void RemoveOnlinePkgName(const DmDeviceInfo &info); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + int32_t ConvertUdidHashToAnoyAndSave(const std::string &pkgName, DmDeviceInfo &deviceInfo); + int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, + std::string &anoyDeviceId); +#endif + std::vector GetWhiteListSAProcessInfo(DmCommonNotifyEvent dmCommonNotifyEvent); + std::vector GetNotifyProcessInfoByUserId(int32_t userId, DmCommonNotifyEvent dmCommonNotifyEvent); + ProcessInfo DealBindProcessInfo(const ProcessInfo &processInfo); + void ProcessDeviceOnline(const std::vector &procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessDeviceOffline(const std::vector &procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessDeviceInfoChange(const std::vector &procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessAppOnline(const std::vector &procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessAppOffline(const std::vector &procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; - static std::mutex dmListenerMapLock_; - static std::map dmListenerMap_; - static std::mutex udidHashMapLock_; - static std::map> udidHashMap_; - static std::mutex alreadyOnlineSetLock_; - static std::unordered_set alreadyOnlineSet_; + static std::mutex alreadyNotifyPkgNameLock_; + static std::map alreadyOnlinePkgName_; + static std::unordered_set highPriorityPkgNameSet_; #endif }; } // namespace DistributedHardware diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..c964054b3adac1b5b0b0dd70f3699f511d33367d --- /dev/null +++ b/services/service/include/devicenamemgr/account_boot_listener.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_ACCOUNT_BOOT_LISTENER_H +#define OHOS_ACCOUNT_BOOT_LISTENER_H +#include + +#include "dm_data_share_common_event.h" +#include "local_device_name_mgr.h" +namespace OHOS { +namespace DistributedHardware { +enum class SaTriggerFlag : int32_t { + DM_SA_READY = 0, + DATA_SHARE_SA_REDDY = 1 +}; + +class AccountBootListener { +public: + AccountBootListener(); + ~AccountBootListener(); + void RegisterAccountBootCb(); + void DoAccountBootProc(); + void SetSaTriggerFlag(SaTriggerFlag triggerFlag); + void InitDataShareEvent(); + void DataShareCallback(); + std::string GetLocalDisplayName() const; + std::string GetLocalDeviceName() const; + +private: + /** + * @brief flag for is registered callback for account boot event + * true: has register the callback + * false: NOT register the callback + */ + std::atomic isRegAccountBootCb_; + std::shared_ptr localDeviceMgr_; + std::atomic isDmSaReady_; + std::atomic isDataShareReady_; + static std::mutex depSaStatelock_; + std::shared_ptr dataShareCommonEventManager_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_ACCOUNT_BOOT_LISTENER_H \ No newline at end of file diff --git a/services/service/include/devicenamemgr/local_device_name_mgr.h b/services/service/include/devicenamemgr/local_device_name_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..bd12387fccbe20144faabf13a75c2d3157505903 --- /dev/null +++ b/services/service/include/devicenamemgr/local_device_name_mgr.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_NAME_MGR_H +#define OHOS_DEVICE_NAME_MGR_H + +#include +#include +#include + +#include "datashare_helper.h" + +namespace OHOS { +namespace DistributedHardware { +class LocalDeviceNameMgr : public std::enable_shared_from_this { +public: + LocalDeviceNameMgr(); + virtual ~LocalDeviceNameMgr(); + int32_t QueryLocalDeviceName(); + void RegisterDeviceNameChangeCb(); + int32_t QueryLocalDisplayName(); + void RegisterDisplayNameChangeCb(); + std::string GetLocalDisplayName() const; + std::string GetLocalDeviceName() const; + +private: + std::shared_ptr GetDataShareHelper(); + int32_t GetDeviceNameFromDataShareHelper(std::shared_ptr dataShareHelper, + std::shared_ptr uri, const char *key, std::string &deviceName); + int32_t GetDefaultDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName); + int32_t GetUserDefinedDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName); + int32_t GetDisplayDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName); + int32_t GetActiveOsAccountIds(); +private: + static std::mutex devNameMtx_; + std::string localDeviceName_; + std::string localDisplayName_; +}; +} // DistributedHardware +} // OHOS + +#endif // OHOS_DEVICE_NAME_MGR_H \ No newline at end of file diff --git a/services/service/include/devicenamemgr/settings_data_event_monitor.h b/services/service/include/devicenamemgr/settings_data_event_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..1ba6591bbd87663e64579ee024b36caa9f9d7f61 --- /dev/null +++ b/services/service/include/devicenamemgr/settings_data_event_monitor.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_SETTINGS_DATA_EVENT_MONITOR_H +#define OHOS_SETTINGS_DATA_EVENT_MONITOR_H + +#include + +#include "data_ability_observer_stub.h" +#include "local_device_name_mgr.h" + +namespace OHOS { +namespace DistributedHardware { +class LocalDeviceNameMgr; +enum class SettingsDataMonitorType : int32_t { + USER_DEFINED_DEVICE_NAME_MONITOR = 0, + DISPLAY_DEVICE_NAME_MONITOR = 1 +}; + +class SettingsDataEventMonitor : public AAFwk::DataAbilityObserverStub { +public: + SettingsDataEventMonitor(std::shared_ptr localDeviceNameMgr, + SettingsDataMonitorType monitorType); + void OnChange() override; +private: + std::weak_ptr localDeviceNameMgrWPtr_; + SettingsDataMonitorType monitorType_; +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_SETTINGS_DATA_EVENT_MONITOR_H \ No newline at end of file diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index 07a725ff68195c1f8f906b0971edb515c9a9fb7b..ca122d021baad0ea76db4194faac545b393871d8 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -36,6 +36,11 @@ typedef struct DiscoveryContext { std::vector filters; } DiscoveryContext; +typedef struct MultiUserDiscovery { + std::string pkgName; + int32_t userId; +} MultiUserDiscovery; + typedef enum { PROXY_TRANSMISION = 0, PROXY_HEARTBEAT = 1, @@ -71,6 +76,8 @@ public: static bool IsCommonDependencyReady(); static bool CloseCommonDependencyObj(); #endif + void ClearDiscoveryCache(const ProcessInfo &processInfo); + std::set ClearDiscoveryPkgName(const std::string &pkgName); private: void StartDiscoveryTimer(const std::string &pkgName); @@ -83,11 +90,17 @@ private: const std::string &searchJson); int32_t HandleDiscoveryQueue(const std::string &pkgName, uint16_t subscribeId, const std::map &filterOps); - int32_t GetDeviceAclParam(const std::string &pkgName, std::string deviceId, bool &isOnline, int32_t &authForm); + int32_t GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, + int32_t &authForm); void ConfigDiscParam(const std::map &discoverParam, DmSubscribeInfo *dmSubInfo); bool CompareCapability(uint32_t capabilityType, const std::string &capabilityStr); void OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara); + void UpdateInfoFreq(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); + void UpdateInfoMedium(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); + std::string AddMultiUserIdentify(const std::string &pkgName); + std::string RemoveMultiUserIdentify(const std::string &pkgName); + void GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, int32_t &userId); private: std::mutex locks_; @@ -102,6 +115,8 @@ private: std::set pkgNameSet_; std::map capabilityMap_; std::mutex capabilityMapLocks_; + std::mutex multiUserDiscLocks_; + std::map multiUserDiscMap_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) static bool isSoLoaded_; diff --git a/services/service/include/i_dm_service_impl_ext.h b/services/service/include/i_dm_service_impl_ext.h index cb30d1deafae20f5f01d2f27da9e8d37ca963457..fe5da7e43d2e0ae82d8d03191557b9189c52c1cd 100644 --- a/services/service/include/i_dm_service_impl_ext.h +++ b/services/service/include/i_dm_service_impl_ext.h @@ -85,6 +85,20 @@ public: * @tc.type: FUNC */ virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + + /** + * @tc.name: IDMServiceImplExt::SetDnPolicy + * @tc.desc: SetDnPolicy + * @tc.type: FUNC + */ + virtual int32_t SetDnPolicy(int32_t policy, int32_t timeOut) = 0; + + /** + * @tc.name: IDMServiceImplExt::AccountUserSwitched + * @tc.desc: AccountUserSwitched + * @tc.type: FUNC + */ + virtual int32_t AccountUserSwitched(int32_t userId, const std::string &accountId) = 0; }; using CreateDMServiceImplExtFuncPtr = IDMServiceImplExt *(*)(void); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index d0d06323a8ee2568a71b6d3d74a3939f201d90f5..bfa0f92beb7b4d65d15a6115cb3a19dacdb8592f 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -83,35 +83,18 @@ public: */ virtual int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId) = 0; - /** - * @tc.name: IDeviceManagerServiceImpl::AuthenticateDevice - * @tc.desc: Authenticate Device of the device manager service impl - * @tc.type: FUNC - */ - virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra) = 0; - /** * @tc.name: IDeviceManagerServiceImpl::UnAuthenticateDevice * @tc.desc: UnAuthenticate Device of the device manager service impl * @tc.type: FUNC */ - virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) = 0; - - /** - * @tc.name: IDeviceManagerServiceImpl::BindDevice - * @tc.desc: Bind Device of the device manager service impl - * @tc.type: FUNC - */ - virtual int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &bindParam) = 0; - + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; /** * @tc.name: IDeviceManagerServiceImpl::UnBindDevice * @tc.desc: UnBindDevice Device of the device manager service impl * @tc.type: FUNC */ - virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &deviceId) = 0; + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; /** * @tc.name: IDeviceManagerServiceImpl::SetUserOperation @@ -270,18 +253,38 @@ public: virtual int32_t UnRegisterUiStateCallback(const std::string &pkgName) = 0; virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname) = 0; - virtual void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) = 0; - virtual void OnUnbindSessionCloseed(int32_t socket) = 0; - virtual void OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen) = 0; virtual int32_t DpAclAdd(const std::string &udid) = 0; virtual int32_t IsSameAccount(const std::string &udid) = 0; - virtual void AccountCommonEventCallback(int32_t userId, std::string commonEventType) = 0; virtual void ScreenCommonEventCallback(std::string commonEventType) = 0; virtual int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId) = 0; + virtual void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid) = 0; + virtual void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) = 0; + virtual void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId) = 0; + virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) = 0; + virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) = 0; + virtual void HandleUserRemoved(int32_t preUserId) = 0; + virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; + virtual void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId) = 0; + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; + virtual void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) = 0; + virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; + virtual void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid) = 0; + virtual void HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) = 0; + virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; + virtual int32_t SaveOnlineDeviceInfo(const std::vector &deviceList) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 5253a5e6d8261c8d20212fde2170b8233791846d..48f7c0fe52e7eb61de6cf769b5ed43057daaa9c7 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -32,7 +32,7 @@ public: * @tc.desc: Device State Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, + virtual void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info) = 0; /** @@ -40,28 +40,21 @@ public: * @tc.desc: Device Found of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) = 0; - - /** - * @tc.name: IDeviceManagerServiceListener::OnDeviceFound - * @tc.desc: Device Found of the DeviceManager Service Listener - * @tc.type: FUNC - */ - virtual void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) = 0; + virtual void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDiscoveryFailed * @tc.desc: Discovery Failed of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) = 0; + virtual void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDiscoverySuccess * @tc.desc: Discovery Success of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) = 0; + virtual void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnPublishResult @@ -75,7 +68,7 @@ public: * @tc.desc: Auth Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, + virtual void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) = 0; /** @@ -83,21 +76,21 @@ public: * @tc.desc: Fa Call of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnUiCall(std::string &pkgName, std::string ¶mJson) = 0; + virtual void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCredentialResult * @tc.desc: Credential Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) = 0; + virtual void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnBindResult * @tc.desc: Bind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) = 0; /** @@ -105,7 +98,7 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) = 0; /** @@ -113,7 +106,7 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + virtual void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) = 0; /** @@ -121,29 +114,57 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) = 0; + virtual void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCreateResult * @tc.desc: Create Pin Holder Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCreateResult(const std::string &pkgName, int32_t result) = 0; + virtual void OnCreateResult(const ProcessInfo &processInfo, int32_t result) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDestroyResult * @tc.desc: Destroy Pin Holder Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDestroyResult(const std::string &pkgName, int32_t result) = 0; + virtual void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnPinHolderEvent * @tc.desc: Pin Holder Event of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + virtual void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) = 0; + + /** + * @tc.name: IDeviceManagerServiceListener::SetNotOfflinePkgname + * @tc.desc: Set the pkgname that not offline + * @tc.type: FUNC + */ + virtual void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) = 0; + + /** + * @tc.name: IDeviceManagerServiceListener::OnDeviceScreenStateChange + * @tc.desc: Device Screen State Change of the DeviceManager Service Listener + * @tc.type: FUNC + */ + virtual void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) = 0; + + /** + * @tc.name: IDeviceManagerServiceListener::OnCredentialAuthStatus + * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener + * @tc.type: FUNC + */ + virtual void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, + uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void OnAppUnintall(const std::string &pkgName) = 0; + virtual void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, + int32_t status, std::string content) = 0; + virtual void OnProcessRemove(const ProcessInfo &processInfo) = 0; + virtual void OnDevStateCallbackAdd(const ProcessInfo &processInfo, + const std::vector &deviceList) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/ipc/lite/ipc_server_listener.h b/services/service/include/ipc/lite/ipc_server_listener.h index f6dfcb6af53d1c6df0583ef85c6885cac9faedeb..294cbe2265b002277c7e345c6e904fa49df9600a 100644 --- a/services/service/include/ipc/lite/ipc_server_listener.h +++ b/services/service/include/ipc/lite/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,9 @@ #define OHOS_DM_IPC_SERVER_LISTENER_H #include +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" #include "ipc_server_listenermgr.h" @@ -38,18 +40,12 @@ public: int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Send All of the Ipc Server Listener - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); + std::set GetSystemSA(); private: void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity); diff --git a/services/service/include/ipc/standard/ipc_server_listener.h b/services/service/include/ipc/standard/ipc_server_listener.h index 4a19b1e57ed5fc5d3abdcdd5f53205345607bd4d..af97616104ad978621bcf9c40865e4708af5aa28 100644 --- a/services/service/include/ipc/standard/ipc_server_listener.h +++ b/services/service/include/ipc/standard/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,8 @@ #define OHOS_DM_IPC_SERVER_LISTENER_H #include - +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -37,18 +38,12 @@ public: int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Send All of the Ipc Server Listener - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); + std::set GetSystemSA(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/ipc/standard/ipc_server_stub.h b/services/service/include/ipc/standard/ipc_server_stub.h index d5390706f20719223d7b7596f605fa31b482161d..ff6055c45a34e54977043a66324bdfc5d797d936 100644 --- a/services/service/include/ipc/standard/ipc_server_stub.h +++ b/services/service/include/ipc/standard/ipc_server_stub.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -27,9 +28,12 @@ #include "ipc_req.h" #include "ipc_rsp.h" #include "iremote_stub.h" -#include "dm_single_instance.h" #include "system_ability.h" +#include "account_boot_listener.h" +#include "dm_device_info.h" +#include "dm_single_instance.h" + namespace OHOS { namespace DistributedHardware { enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; @@ -84,14 +88,14 @@ public: * @tc.desc: Register DeviceManager Listener of the IpcServerStub * @tc.type: FUNC */ - int32_t RegisterDeviceManagerListener(std::string &pkgName, sptr listener); + int32_t RegisterDeviceManagerListener(const ProcessInfo &processInfo, sptr listener); /** * @tc.name: IpcServerStub::UnRegisterDeviceManagerListener * @tc.desc: UnRegister DeviceManager Listener of the IpcServerStub * @tc.type: FUNC */ - int32_t UnRegisterDeviceManagerListener(std::string &pkgName); + int32_t UnRegisterDeviceManagerListener(const ProcessInfo &processInfo); /** * @tc.name: IpcServerStub::QueryServiceState @@ -101,32 +105,25 @@ public: ServiceRunningState QueryServiceState() const; /** - * @tc.name: IpcServerStub::SendALL - * @tc.desc: SendALL of the IpcServerStub - * @tc.type: FUNC - */ - int32_t SendALL(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerStub::GetAllPkgName + * @tc.name: IpcServerStub::GetAllProcessInfo * @tc.desc: Get All PkgName from dmListener_ * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); /** * @tc.name: IpcServerStub::GetDmListener * @tc.desc: Get DmListener of the IpcServerStub * @tc.type: FUNC */ - const sptr GetDmListener(std::string pkgName) const; + const sptr GetDmListener(ProcessInfo processInfo) const; /** * @tc.name: IpcServerStub::GetDmListenerPkgName * @tc.desc: Get DmListener PkgName of the IpcServerStub * @tc.type: FUNC */ - const std::string GetDmListenerPkgName(const wptr &remote) const; + const ProcessInfo GetDmListenerPkgName(const wptr &remote) const; /** * @tc.name: IpcServerStub::Dump @@ -148,20 +145,23 @@ public: * @tc.type: FUNC */ void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + std::set GetSystemSA(); private: IpcServerStub(); ~IpcServerStub() override = default; bool Init(); + void AddSystemSA(const std::string &pkgName); + void RemoveSystemSA(const std::string &pkgName); private: bool registerToService_; ServiceRunningState state_; mutable std::mutex listenerLock_; - std::map> appRecipient_; - std::map> dmListener_; - std::mutex dependsSASetLock_; - std::unordered_set dependsSASet_; + std::map> appRecipient_; + std::map> dmListener_; + std::shared_ptr accountBootListener_; + std::set systemSA_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/softbus/softbus_adapter.h b/services/service/include/notify/device_manager_service_notify.h similarity index 41% rename from services/service/include/softbus/softbus_adapter.h rename to services/service/include/notify/device_manager_service_notify.h index 24d6aacfe9a3c227edaa033599bce107a90ec234..9dcb28ebed6510755d73178c34327941a8260e30 100644 --- a/services/service/include/softbus/softbus_adapter.h +++ b/services/service/include/notify/device_manager_service_notify.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,37 +13,29 @@ * limitations under the License. */ -#ifndef OHOS_SOFTBUS_ADAPTER -#define OHOS_SOFTBUS_ADAPTER +#ifndef OHOS_DM_SERVICE_NOTIFY_H +#define OHOS_DM_SERVICE_NOTIFY_H #include -#include #include -#include "session.h" -#include "socket.h" +#include "dm_device_info.h" #include "dm_single_instance.h" + namespace OHOS { namespace DistributedHardware { -class SoftbusAdapter { - DM_DECLARE_SINGLE_INSTANCE_BASE(SoftbusAdapter); -public: - SoftbusAdapter(); - ~SoftbusAdapter(); - int32_t CreateSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName); - int32_t RemoveSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName); +class DeviceManagerServiceNotify { + DM_DECLARE_SINGLE_INSTANCE(DeviceManagerServiceNotify); - void OnSoftbusSessionOpened(int32_t socket, PeerSocketInfo info); - void OnSoftbusSessionClosed(int32_t socket, ShutdownReason reason); - void OnBytesReceived(int32_t socket, const void *data, uint32_t dataLen); - void OnStreamReceived(int32_t socket, const StreamData *data, const StreamData *ext, - const StreamFrameInfo *frameInfo); - void OnMessageReceived(int32_t socket, const void *data, unsigned int dataLen) const; - void OnQosEvent(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) const; +public: + int32_t RegisterCallBack(int32_t dmCommonNotifyEvent, const ProcessInfo &processInfo); + void GetCallBack(int32_t dmCommonNotifyEvent, std::set &processInfos); + void ClearDiedProcessCallback(const ProcessInfo &processInfo); private: - ISocketListener iSocketListener_; + std::mutex callbackLock_; + std::map> callbackMap_; }; } // namespace DistributedHardware } // namespace OHOS -#endif \ No newline at end of file +#endif // OHOS_DM_SERVICE_NOTIFY_H diff --git a/services/service/include/permission/lite/permission_manager.h b/services/service/include/permission/lite/permission_manager.h index 9d8d2cce511e10f3a26a28ee98e4cb7462983ae3..85b6bd48e40f8c8be777da026549473ac672e97c 100644 --- a/services/service/include/permission/lite/permission_manager.h +++ b/services/service/include/permission/lite/permission_manager.h @@ -32,8 +32,10 @@ public: int32_t GetCallerProcessName(std::string &processName); bool CheckProcessNameValidOnAuthCode(const std::string &processName); bool CheckProcessNameValidOnPinHolder(const std::string &processName); + bool CheckWhiteListSystemSA(const std::string &pkgName); + std::unordered_set GetWhiteListSystemSA(); bool CheckSystemSA(const std::string &pkgName); - std::unordered_set GetSystemSA(); + bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index b62f81ea58989ec7e4e7f6a0fcbe8757edab47da..ddf790bf0ac202bd41b355de7ac7ccdc27f3c4b8 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -33,8 +33,10 @@ public: int32_t GetCallerProcessName(std::string &processName); bool CheckProcessNameValidOnAuthCode(const std::string &processName); bool CheckProcessNameValidOnPinHolder(const std::string &processName); + bool CheckWhiteListSystemSA(const std::string &pkgName); + std::unordered_set GetWhiteListSystemSA(); bool CheckSystemSA(const std::string &pkgName); - std::unordered_set GetSystemSA(); + bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index b1aa7c149cc5275651793b9e56aec88aed63aa0e..f5d8a3fae4b251c02aa27b45cf00921b6d0b09a8 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -21,6 +21,7 @@ #include "pin_holder_session.h" #include "pinholder_session_callback.h" +#include #include #include @@ -35,6 +36,12 @@ typedef enum PinHolderState { SINK_DESTROY, } PinHolderState; +typedef enum DestroyState { + STATE_UNKNOW = 0x0, + STATE_REMOTE_WRONG = 0x1, + STATE_TIME_OUT = 0x2, +} DestroyState; + class PinHolder final : public IPinholderSessionCallback, public std::enable_shared_from_this { public: @@ -54,6 +61,7 @@ public: private: int32_t CreateGeneratePinHolderMsg(); int32_t ParseMsgType(const std::string &message); + void ProcessCloseSessionMsg(const std::string &message); void ProcessCreateMsg(const std::string &message); void ProcessCreateRespMsg(const std::string &message); void ProcessDestroyMsg(const std::string &message); @@ -68,7 +76,6 @@ private: std::shared_ptr session_ = nullptr; std::shared_ptr timer_ = nullptr; - std::string registerPkgName_ = ""; std::string remoteDeviceId_ = ""; std::string payload_ = ""; DmPinType pinType_ = NUMBER_PIN_CODE; @@ -76,6 +83,9 @@ private: PinHolderState sourceState_; int32_t sessionId_ = -1; bool isRemoteSupported_ = false; + std::atomic isDestroy_ {false}; + DestroyState destroyState_ = STATE_UNKNOW; + ProcessInfo processInfo_; }; } } diff --git a/services/service/include/publishcommonevent/dm_account_common_event.h b/services/service/include/publishcommonevent/dm_account_common_event.h index b0a9e68785b3d242173f433f02b663eb1a88a874..640bf206fbfe1a46397b40662700966244747b77 100644 --- a/services/service/include/publishcommonevent/dm_account_common_event.h +++ b/services/service/include/publishcommonevent/dm_account_common_event.h @@ -33,7 +33,19 @@ namespace DistributedHardware { using OHOS::EventFwk::CommonEventData; using OHOS::EventFwk::CommonEventSubscriber; using OHOS::EventFwk::CommonEventSubscribeInfo; -using AccountEventCallback = std::function; +/** + * @brief account event callback define, fun(event_type, current userid, before userid) + * first param, accont event + * second param, the current userid + * third param, the userid before. + * first param | second param | third param + * ------------------------------------------ + * COMMON_EVENT_USER_SWITCHED | switch target user id | the user id before switch + * COMMON_EVENT_USER_REMOVED | -1 | the user id removed + * COMMON_EVENT_HWID_LOGOUT | logout in witch user id | logout in witch user id + * COMMON_EVENT_HWID_LOGIN | login in witch user id | login in witch user id + */ +using AccountEventCallback = std::function; class DmAccountEventSubscriber : public CommonEventSubscriber { public: diff --git a/services/service/include/publishcommonevent/dm_data_share_common_event.h b/services/service/include/publishcommonevent/dm_data_share_common_event.h new file mode 100644 index 0000000000000000000000000000000000000000..f861486a9c0863839249a5381ade4ac5e2b90ba9 --- /dev/null +++ b/services/service/include/publishcommonevent/dm_data_share_common_event.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DATA_SHARE_COMMON_EVENT_H +#define OHOS_DATA_SHARE_COMMON_EVENT_H + +#include +#include +#include +#include + +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "matching_skills.h" +#include "system_ability_status_change_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::CommonEventData; +using OHOS::EventFwk::CommonEventSubscriber; +using OHOS::EventFwk::CommonEventSubscribeInfo; +using DataShareEventCallback = std::function; + +class DmDataShareEventSubscriber : public CommonEventSubscriber { +public: + DmDataShareEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, const DataShareEventCallback &callback, + const std::vector &eventNameVec) : CommonEventSubscriber(subscribeInfo), + eventNameVec_(eventNameVec), callback_(callback) {} + ~DmDataShareEventSubscriber() override = default; + std::vector GetSubscriberEventNameVec() const; + void OnReceiveEvent(const CommonEventData &data) override; + +private: + std::vector eventNameVec_; + DataShareEventCallback callback_; +}; + +class DmDataShareCommonEventManager { +public: + DmDataShareCommonEventManager() = default; + ~DmDataShareCommonEventManager(); + bool SubscribeDataShareCommonEvent(const std::vector &eventNameVec, + const DataShareEventCallback &callback); + bool UnsubscribeDataShareCommonEvent(); + +private: + std::vector eventNameVec_; + bool eventValidFlag_ = false; + std::mutex evenSubscriberMutex_; + std::shared_ptr subscriber_ = nullptr; + sptr statusChangeListener_ = nullptr; + int32_t counter_ = 0; + +private: + class SystemAbilityStatusChangeListener : public SystemAbilityStatusChangeStub { + public: + explicit SystemAbilityStatusChangeListener(std::shared_ptr DataShareSubscriber) + : changeSubscriber_(DataShareSubscriber) {} + ~SystemAbilityStatusChangeListener() = default; + void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + + private: + std::shared_ptr changeSubscriber_; + }; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DATA_SHARE_COMMON_EVENT_H diff --git a/services/service/include/publishcommonevent/dm_package_common_event.h b/services/service/include/publishcommonevent/dm_package_common_event.h new file mode 100644 index 0000000000000000000000000000000000000000..f0964d173e19744402e24b61933ebecea8c05106 --- /dev/null +++ b/services/service/include/publishcommonevent/dm_package_common_event.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_PACKAGE_COMMON_EVENT_H +#define OHOS_PACKAGE_COMMON_EVENT_H + +#include +#include +#include +#include + +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "matching_skills.h" +#include "system_ability_status_change_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::CommonEventData; +using OHOS::EventFwk::CommonEventSubscriber; +using OHOS::EventFwk::CommonEventSubscribeInfo; +using PackageEventCallback = std::function; + +class DmPackageEventSubscriber : public CommonEventSubscriber { +public: + DmPackageEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, const PackageEventCallback &callback, + const std::vector &eventNameVec) : CommonEventSubscriber(subscribeInfo), + eventNameVec_(eventNameVec), callback_(callback) {} + ~DmPackageEventSubscriber() override = default; + std::vector GetSubscriberEventNameVec() const; + void OnReceiveEvent(const CommonEventData &data) override; + +private: + std::vector eventNameVec_; + PackageEventCallback callback_; +}; + +class DmPackageCommonEventManager { +public: + DmPackageCommonEventManager() = default; + ~DmPackageCommonEventManager(); + bool SubscribePackageCommonEvent(const std::vector &eventNameVec, + const PackageEventCallback &callback); + bool UnsubscribePackageCommonEvent(); + +private: + std::vector eventNameVec_; + bool eventValidFlag_ = false; + std::mutex evenSubscriberMutex_; + std::shared_ptr subscriber_ = nullptr; + sptr statusChangeListener_ = nullptr; + int32_t counter_ = 0; + +private: + class SystemAbilityStatusChangeListener : public SystemAbilityStatusChangeStub { + public: + explicit SystemAbilityStatusChangeListener(std::shared_ptr PackageSubscriber) + : changeSubscriber_(PackageSubscriber) {} + ~SystemAbilityStatusChangeListener() = default; + void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + + private: + std::shared_ptr changeSubscriber_; + }; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_PACKAGE_COMMON_EVENT_H diff --git a/services/service/include/relationshipsyncmgr/dm_comm_tool.h b/services/service/include/relationshipsyncmgr/dm_comm_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..8eba6a77a5e7e68d16784cdcee481ba85907a364 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_comm_tool.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_COMM_TOOL_H +#define OHOS_DM_COMM_TOOL_H + +#include +#include +#include +#include + +#include "dm_transport.h" +#include "dm_transport_msg.h" +#include "event_handler.h" + +namespace OHOS { +namespace DistributedHardware { +// send local foreground userids msg +constexpr int32_t DM_COMM_SEND_LOCAL_USERIDS = 1; +// if receive remote device send foreground userids, response local foreground uerids +// This msg no need response +constexpr int32_t DM_COMM_RSP_LOCAL_USERIDS = 2; + +class DMCommTool : public std::enable_shared_from_this { +public: + DMCommTool(); + virtual ~DMCommTool() = default; + static std::shared_ptr GetInstance(); + void Init(); + void UnInit(); + + void SendUserIds(const std::string rmtNetworkId, const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds); + void RspLocalFrontOrBackUserIds(const std::string rmtNetworkId, const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds); + + class DMCommToolEventHandler : public AppExecFwk::EventHandler { + public: + DMCommToolEventHandler(const std::shared_ptr runner, + std::shared_ptr dmCommToolPtr); + ~DMCommToolEventHandler() override = default; + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; + private: + std::weak_ptr dmCommToolWPtr_; + }; + std::shared_ptr GetEventHandler(); + const std::shared_ptr GetDMTransportPtr(); + + void ProcessReceiveUserIdsEvent(const std::shared_ptr commMsg); + void ProcessResponseUserIdsEvent(const std::shared_ptr commMsg); +private: + std::shared_ptr dmTransportPtr_; + std::shared_ptr eventHandler_; +}; +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/dm_transport.h b/services/service/include/relationshipsyncmgr/dm_transport.h new file mode 100644 index 0000000000000000000000000000000000000000..cf8eb0890673f1c8b612f3a1b323facb1fd16564 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_transport.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_TRANSPORT_H +#define OHOS_DM_TRANSPORT_H + +#include +#include +#include +#include +#include +#include + +#include "event_handler.h" +#include "socket.h" +#include "softbus_bus_center.h" + +namespace OHOS { +namespace DistributedHardware { +class DMCommTool; +class DMTransport { +public: + explicit DMTransport(std::shared_ptr dmCommToolPtr); + int32_t Init(); + int32_t UnInit(); + virtual ~DMTransport() = default; + // open softbus channel with remote device by networkid. + int32_t StartSocket(const std::string &rmtNetworkId); + // stop softbus channel with remote device by networkid. + int32_t StopSocket(const std::string &rmtNetworkId); + int32_t Send(const std::string &rmtNetworkId, const std::string &payload); + int32_t OnSocketOpened(int32_t socketId, const PeerSocketInfo &info); + void OnSocketClosed(int32_t socketId, ShutdownReason reason); + void OnBytesReceived(int32_t socketId, const void *data, uint32_t dataLen); + +private: + int32_t CreateServerSocket(); + int32_t CreateClientSocket(const std::string &remoteDevId); + bool IsDeviceSessionOpened(const std::string &remoteDevId, int32_t &socketId); + std::string GetRemoteNetworkIdBySocketId(int32_t socketId); + void ClearDeviceSocketOpened(const std::string &remoteDevId); + void HandleReceiveMessage(const int32_t socketId, const std::string &payload); + +private: + std::mutex rmtSocketIdMtx_; + // record the socket id for the connection with remote devices, + std::map remoteDevSocketIds_; + std::atomic localServerSocket_; + std::string localSocketName_; + std::atomic isSocketSvrCreateFlag_; + std::weak_ptr dmCommToolWPtr_; +}; +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/dm_transport_msg.h b/services/service/include/relationshipsyncmgr/dm_transport_msg.h new file mode 100644 index 0000000000000000000000000000000000000000..bdca9e7916ca23f0771e707882a45e9f8e70ab73 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_transport_msg.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_TRANSPORT_MSG_H +#define OHOS_DM_TRANSPORT_MSG_H + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +const char* const FOREGROUND_USERIDS_MSG_USERIDS_KEY = "foregroundUserIds"; +const char* const BACKGROUND_USERIDS_MSG_USERIDS_KEY = "backgroundUserIds"; +const char* const COMM_MSG_CODE_KEY = "code"; +const char* const COMM_MSG_MSG_KEY = "msg"; + +const char* const DSOFTBUS_NOTIFY_USERIDS_UDIDKEY = "remoteUdid"; +const char* const DSOFTBUS_NOTIFY_USERIDS_USERIDKEY = "foregroundUserIds"; + +struct UserIdsMsg { + std::vector foregroundUserIds; + std::vector backgroundUserIds; + UserIdsMsg() : foregroundUserIds({}), backgroundUserIds({}) {} + UserIdsMsg(std::vector foregroundUserIds, std::vector backgroundUserIds) + : foregroundUserIds(foregroundUserIds), backgroundUserIds(backgroundUserIds) {} +}; + +void ToJson(cJSON *jsonObject, const UserIdsMsg &userIdsMsg); +void FromJson(const cJSON *jsonObject, UserIdsMsg &userIdsMsg); + +struct CommMsg { + int32_t code; + std::string msg; + CommMsg() : code(-1), msg("") {} + CommMsg(int32_t code, std::string msg) : code(code), msg(msg) {} +}; + +void ToJson(cJSON *jsonObject, const CommMsg &commMsg); +void FromJson(const cJSON *jsonObject, CommMsg &commMsg); + +std::string GetCommMsgString(const CommMsg &commMsg); + +struct InnerCommMsg { + std::string remoteNetworkId; + std::shared_ptr commMsg; + InnerCommMsg(std::string remoteNetworkId, std::shared_ptr commMsg) + : remoteNetworkId(remoteNetworkId), commMsg(commMsg) {} +}; + +struct NotifyUserIds { + std::string remoteUdid; + std::vector userIds; + NotifyUserIds() : remoteUdid(""), userIds({}) {} + NotifyUserIds(std::string remoteUdid, std::vector userIds) + : remoteUdid(remoteUdid), userIds(userIds) {} + + std::string ToString(); +}; + +void ToJson(cJSON *jsonObject, const NotifyUserIds &userIds); +void FromJson(const cJSON *jsonObject, NotifyUserIds &userIds); +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..f64c1af30c15db5c06c449fcce749501282ff65f --- /dev/null +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_RELATIONSHIP_SYNC_MGR_H +#define OHOS_RELATIONSHIP_SYNC_MGR_H + +#include +#include +#include "cJSON.h" +#include "dm_single_instance.h" +namespace OHOS { +namespace DistributedHardware { +const uint32_t MAX_USER_ID_NUM = 5; +enum class RelationShipChangeType : uint32_t { + ACCOUNT_LOGOUT = 0, + DEVICE_UNBIND = 1, + APP_UNBIND = 2, + SERVICE_UNBIND = 3, + DEL_USER = 4, + APP_UNINSTALL = 5, + SYNC_USERID = 6, + TYPE_MAX = 7 +}; + +struct UserIdInfo { + /** + * @brief true for foreground userid, false for background + */ + bool isForeground; + std::uint16_t userId; + UserIdInfo(bool isForeground, std::uint16_t userId) : isForeground(isForeground), userId(userId) {} + const std::string ToString() const; +}; + +struct RelationShipChangeMsg { + RelationShipChangeType type; + uint32_t userId; + std::string accountId; + uint64_t tokenId; + // The broadcast need send to these devices with the udids + std::vector peerUdids; + // The broadcast from which device with the udid. + std::string peerUdid; + std::string accountName; + // true: request, false: response + bool syncUserIdFlag; + // The foreground and background user id infos + std::vector userIdInfos; + + explicit RelationShipChangeMsg(); + bool ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) const; + bool FromBroadcastPayLoad(const cJSON *payloadJson, RelationShipChangeType type); + bool IsValid() const; + bool IsChangeTypeValid(); + bool IsChangeTypeValid(uint32_t type); + void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + bool ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const; + cJSON *ToPayLoadJson() const; + + bool FromAccountLogoutPayLoad(const cJSON *payloadJson); + bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); + bool FromAppUnbindPayLoad(const cJSON *payloadJson); + bool FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson); + bool FromDelUserPayLoad(const cJSON *payloadJson); + + std::string ToJson() const; + bool FromJson(const std::string &msgJson); + + const std::string ToString() const; +}; + +class ReleationShipSyncMgr { +DM_DECLARE_SINGLE_INSTANCE(ReleationShipSyncMgr); +public: + std::string SyncTrustRelationShip(const RelationShipChangeMsg &msg); + RelationShipChangeMsg ParseTrustRelationShipChange(const std::string &msgJson); +}; + +const std::string GetUserIdInfoList(const std::vector &list); +void GetFrontAndBackUserIdInfos(const std::vector &remoteUserIdInfos, + std::vector &foregroundUserIdInfos, std::vector &backgroundUserIdInfos); +} // DistributedHardware +} // OHOS +#endif // OHOS_RELATIONSHIP_SYNC_MGR_H \ No newline at end of file diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 362e132ce50b1ca1afb27df1b682d6d3ff3509e3..7a916e4350f557eb5b7dcec8b5259505eda5cbf5 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -34,6 +34,7 @@ #include "inner_session.h" #include "session.h" #include "socket.h" +#include "dm_anonymous.h" namespace OHOS { namespace DistributedHardware { @@ -53,8 +54,15 @@ public: static void DeviceOffLine(DmDeviceInfo deviceInfo); static void DeviceNameChange(DmDeviceInfo deviceInfo); static void OnLocalDevInfoChange(); - static void OnDeviceNotTrusted(const char *msg); + static void OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen); static void DeviceNotTrust(const std::string &msg); + static void DeviceTrustedChange(const std::string &msg); + static void DeviceUserIdCheckSumChange(const std::string &msg); + static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); + static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); + static void OnCredentialAuthStatus(const char *deviceList, uint32_t deviceListLen, uint16_t deviceTypeId, + int32_t errcode); + static void CredentialAuthStatusProcess(std::string deviceList, uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); @@ -65,12 +73,14 @@ public: static int32_t ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo); static int32_t ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceBasicInfo &devInfo); static std::string ConvertBytesToUpperCaseHexString(const uint8_t arr[], const size_t size); + static int32_t ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, + DmDeviceInfo &devInfo); int32_t InitSoftbusListener(); int32_t GetTrustedDeviceList(std::vector &deviceInfoList); int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo); int32_t GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info); - int32_t ShiftLNNGear(bool isWakeUp); + int32_t ShiftLNNGear(bool isWakeUp, const std::string &callerId); static int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); int32_t GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel); int32_t GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType); @@ -91,7 +101,15 @@ public: static IRefreshCallback &GetSoftbusRefreshCb(); static void SetHostPkgName(const std::string hostName); static std::string GetHostPkgName(); + void SendAclChangedBroadcast(const std::string &msg); + int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); + static int32_t GetNetworkIdByUdid(const std::string &udid, std::string &networkId); + int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); + int32_t SetForegroundUserIdsToDSoftBus(const std::string &remoteUserId, const std::vector &userIds); + void DeleteCacheDeviceInfo(); private: + static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); + static void ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj); int32_t InitSoftPublishLNN(); private: diff --git a/services/service/src/advertise/advertise_manager.cpp b/services/service/src/advertise/advertise_manager.cpp index 3e449028129400c6c2eeb72b8a3ca8f4795182d2..263203e85048c9e7ad3a8862b82f1aa8b483e774 100644 --- a/services/service/src/advertise/advertise_manager.cpp +++ b/services/service/src/advertise/advertise_manager.cpp @@ -48,7 +48,7 @@ int32_t AdvertiseManager::StartAdvertising(const std::string &pkgName, if (advertiseParam.find(PARAM_KEY_DISC_CAPABILITY) != advertiseParam.end()) { capability = advertiseParam.find(PARAM_KEY_DISC_CAPABILITY)->second; } - if (capability == DM_CAPABILITY_APPROACH) { + if (capability == DM_CAPABILITY_APPROACH || capability == DM_CAPABILITY_TOUCH) { dmPubInfo.mode = DmDiscoverMode::DM_DISCOVER_MODE_ACTIVE; } std::string customData = ""; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 6cfec1869f890650ffc6f375ff60e169917884da..82b1b3af9cc1020947fd5c2b6284bb1ef0fbbd7c 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -19,6 +19,7 @@ #include #include "app_manager.h" +#include "nlohmann/json.hpp" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" @@ -29,8 +30,13 @@ #include "permission_manager.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "common_event_support.h" +#include "datetime_ex.h" +#include "dm_comm_tool.h" +#include "dm_transport_msg.h" #include "iservice_registry.h" +#include "kv_adapter_manager.h" #include "multiple_user_connector.h" +#include "relationship_sync_mgr.h" #if defined(SUPPORT_POWER_MANAGER) #include "power_mgr_client.h" #endif // SUPPORT_POWER_MANAGER @@ -57,11 +63,21 @@ constexpr const char* LIB_DM_ADAPTER_NAME = "libdevicemanageradapter.z.so"; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); -const int32_t NORMAL = 0; -const int32_t SYSTEM_BASIC = 1; -const int32_t SYSTEM_CORE = 2; -constexpr const char* ALL_PKGNAME = ""; -constexpr const char* NETWORKID = "NETWORK_ID"; +namespace { + const int32_t NORMAL = 0; + const int32_t SYSTEM_BASIC = 1; + const int32_t SYSTEM_CORE = 2; + constexpr const char *ALL_PKGNAME = ""; + constexpr const char *NETWORKID = "NETWORK_ID"; + constexpr uint32_t INVALIED_BIND_LEVEL = 0; + constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; + const std::string USERID_CHECKSUM_NETWORKID_KEY = "networkId"; + const std::string USERID_CHECKSUM_DISCOVER_TYPE_KEY = "discoverType"; + constexpr uint32_t USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK = 0b0010; + const std::string DHARD_WARE_PKG_NAME = "ohos.dhardware"; + const std::string USERID_CHECKSUM_ISCHANGE_KEY = "ischange"; +} + DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); @@ -83,6 +99,11 @@ int32_t DeviceManagerService::InitSoftbusListener() softbusListener_ = std::make_shared(); } SoftbusCache::GetInstance().UpdateDeviceInfoCache(); + std::vector onlineDeviceList; + SoftbusCache::GetInstance().GetDeviceInfoFromCache(onlineDeviceList); + if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { + dmServiceImpl_->SaveOnlineDeviceInfo(onlineDeviceList); + } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) SubscribePublishCommonEvent(); @@ -128,15 +149,9 @@ void DeviceManagerService::QueryDependsSwitchState() { LOGI("DeviceManagerService::QueryDependsSwitchState start."); std::shared_ptr publishSubScriber = publshCommonEventManager_->GetSubscriber(); - if (publishSubScriber == nullptr) { - LOGE("publishSubScriber is nullptr."); - return; - } + CHECK_NULL_VOID(publishSubScriber); auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr == nullptr) { - LOGE("Get SystemAbilityManager Failed"); - return; - } + CHECK_NULL_VOID(samgr); #ifdef SUPPORT_BLUETOOTH if (samgr->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID) == nullptr) { publishSubScriber->SetBluetoothState(static_cast(Bluetooth::BTStateID::STATE_TURN_OFF)); @@ -154,7 +169,9 @@ void DeviceManagerService::QueryDependsSwitchState() publishSubScriber->SetWifiState(static_cast(OHOS::Wifi::WifiState::DISABLED)); } else { bool isWifiActive = false; - Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID)->IsWifiActive(isWifiActive); + auto wifiMgr = Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); + CHECK_NULL_VOID(wifiMgr); + wifiMgr->IsWifiActive(isWifiActive); if (isWifiActive) { publishSubScriber->SetWifiState(static_cast(OHOS::Wifi::WifiState::ENABLED)); } else { @@ -164,10 +181,14 @@ void DeviceManagerService::QueryDependsSwitchState() #endif // SUPPORT_WIFI #ifdef SUPPORT_POWER_MANAGER - if (OHOS::PowerMgr::PowerMgrClient::GetInstance().IsScreenOn()) { - publishSubScriber->SetScreenState(DM_SCREEN_ON); - } else { + if (samgr->CheckSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr) { publishSubScriber->SetScreenState(DM_SCREEN_OFF); + } else { + if (OHOS::PowerMgr::PowerMgrClient::GetInstance().IsScreenOn()) { + publishSubScriber->SetScreenState(DM_SCREEN_ON); + } else { + publishSubScriber->SetScreenState(DM_SCREEN_OFF); + } } #else publishSubScriber->SetScreenState(DM_SCREEN_ON); @@ -180,6 +201,8 @@ void DeviceManagerService::QueryDependsSwitchState() void DeviceManagerService::UninitSoftbusListener() { + CHECK_NULL_VOID(softbusListener_); + softbusListener_->DeleteCacheDeviceInfo(); softbusListener_ = nullptr; LOGI("SoftbusListener uninit."); } @@ -198,7 +221,10 @@ int32_t DeviceManagerService::InitDMServiceListener() if (pinHolder_ == nullptr) { pinHolder_ = std::make_shared(listener_); } - LOGI("DeviceManagerServiceListener init success."); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + DMCommTool::GetInstance()->Init(); +#endif + LOGI("Init success."); return DM_OK; } @@ -207,29 +233,26 @@ void DeviceManagerService::UninitDMServiceListener() listener_ = nullptr; advertiseMgr_ = nullptr; discoveryMgr_ = nullptr; - LOGI("DeviceManagerServiceListener uninit."); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + KVAdapterManager::GetInstance().UnInit(); +#endif + LOGI("Uninit."); } -void DeviceManagerService::RegisterDeviceManagerListener(const std::string &pkgName) +void DeviceManagerService::RegisterCallerAppId(const std::string &pkgName) { - if (listener_ == nullptr) { - listener_ = std::make_shared(); - } - listener_->RegisterDmListener(pkgName, AppManager::GetInstance().GetAppId()); + AppManager::GetInstance().RegisterCallerAppId(pkgName); } -void DeviceManagerService::UnRegisterDeviceManagerListener(const std::string &pkgName) +void DeviceManagerService::UnRegisterCallerAppId(const std::string &pkgName) { - if (listener_ == nullptr) { - listener_ = std::make_shared(); - } - listener_->UnRegisterDmListener(pkgName); + AppManager::GetInstance().UnRegisterCallerAppId(pkgName); } int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - LOGI("DMSrc::GetTrustedDeviceList begin for pkgName = %{public}s.", pkgName.c_str()); + LOGI("Begin for pkgName = %{public}s.", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -251,19 +274,23 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c DmDeviceInfo tempInfo; if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, item.networkId, sizeof(item.networkId)) != 0) { LOGE("get networkId: %{public}s failed", GetAnonyString(item.networkId).c_str()); + continue; } deviceList.push_back(tempInfo); } return DM_OK; } - if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { + if (!onlineDeviceList.empty() && IsDMServiceImplReady()) { std::unordered_map udidMap; - if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) { + if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) { udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME)); } else { udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName); } for (auto item : onlineDeviceList) { +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ConvertUdidHashToAnoyDeviceId(item); +#endif std::string udid = ""; SoftbusListener::GetUdidByNetworkId(item.networkId, udid); if (udidMap.find(udid) != udidMap.end()) { @@ -278,7 +305,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std::string &callerId, bool isRefresh, bool isWakeUp) { - LOGI("DeviceManagerService::ShiftLNNGear begin for pkgName = %{public}s, callerId = %{public}s, isRefresh =" + LOGD("Begin for pkgName = %{public}s, callerId = %{public}s, isRefresh =" "%{public}d, isWakeUp = %{public}d", pkgName.c_str(), GetAnonyString(callerId).c_str(), isRefresh, isWakeUp); if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call ShiftLNNGear, pkgName = %{public}s", pkgName.c_str()); @@ -290,7 +317,7 @@ int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std } if (isRefresh) { CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); - int32_t ret = softbusListener_->ShiftLNNGear(isWakeUp); + int32_t ret = softbusListener_->ShiftLNNGear(isWakeUp, callerId); if (ret != DM_OK) { LOGE("ShiftLNNGear error, failed ret: %{public}d", ret); return ret; @@ -301,7 +328,7 @@ int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std int32_t DeviceManagerService::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info) { - LOGI("DeviceManagerService::GetDeviceInfo begin networkId %{public}s.", GetAnonyString(networkId).c_str()); + LOGI("Begin networkId %{public}s.", GetAnonyString(networkId).c_str()); if (!PermissionManager::GetInstance().CheckPermission() && !PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call GetDeviceInfo."); @@ -321,7 +348,7 @@ int32_t DeviceManagerService::GetDeviceInfo(const std::string &networkId, DmDevi int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - LOGI("DeviceManagerService::GetLocalDeviceInfo begin."); + LOGD("Begin."); bool isOnlyShowNetworkId = false; if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call GetLocalDeviceInfo."); @@ -337,6 +364,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) DmDeviceInfo tempInfo; if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, info.networkId, sizeof(info.networkId)) != 0) { LOGE("get networkId: %{public}s failed", GetAnonyString(info.networkId).c_str()); + return ERR_DM_FAILED; } info = tempInfo; return DM_OK; @@ -349,9 +377,23 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) localDeviceId_ = udidHash; } } - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHashTemp = ""; + if (ConvertUdidHashToAnoyDeviceId(localDeviceId_, udidHashTemp) == DM_OK) { + if (memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { + LOGE("GetLocalDeviceInfo memset_s failed."); + return ERR_DM_FAILED; + } + if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); + return ERR_DM_FAILED; + } + return DM_OK; + } +#endif if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, localDeviceId_.c_str(), localDeviceId_.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(localDeviceId_).c_str()); + return ERR_DM_FAILED; } return DM_OK; } @@ -386,79 +428,13 @@ int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, con return SoftbusListener::GetUuidByNetworkId(netWorkId.c_str(), uuid); } -int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, - const std::string &extra) -{ - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("DeviceManagerService::StartDeviceDiscovery begin for pkgName = %{public}s, extra = %{public}s", - pkgName.c_str(), extra.c_str()); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - - SoftbusListener::SetHostPkgName(pkgName); - std::map discParam; - discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, - std::to_string(subscribeInfo.subscribeId))); - discParam.insert(std::pair(PARAM_KEY_DISC_MEDIUM, std::to_string(subscribeInfo.medium))); - - std::map filterOps; - filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, extra)); - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StartDiscovering(pkgName, discParam, filterOps); -} - -int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const uint16_t subscribeId, - const std::string &filterOptions) -{ - if (!PermissionManager::GetInstance().CheckNewPermission()) { - LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("StartDeviceDiscovery begin for pkgName = %{public}s, filterOptions = %{public}s, subscribeId = %{public}d", - pkgName.c_str(), filterOptions.c_str(), subscribeId); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - - SoftbusListener::SetHostPkgName(pkgName); - std::map discParam; - discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId))); - - std::map filterOps; - filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, filterOptions)); - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StartDiscovering(pkgName, discParam, filterOps); -} - -int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) -{ - if (!PermissionManager::GetInstance().CheckPermission() && - !PermissionManager::GetInstance().CheckNewPermission()) { - LOGE("The caller: %{public}s does not have permission to call StopDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("DeviceManagerService::StopDeviceDiscovery begin for pkgName = %{public}s", pkgName.c_str()); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StopDiscovering(pkgName, subscribeId); -} - int32_t DeviceManagerService::PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo) { if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller: %{public}s does not have permission to call PublishDeviceDiscovery.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::PublishDeviceDiscovery begin for pkgName = %{public}s", pkgName.c_str()); + LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -500,10 +476,16 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int LOGE("AuthenticateDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - + std::string queryDeviceId = deviceId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHash = ""; + if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) { + queryDeviceId = udidHash; + } +#endif PeerTargetId targetId; ConnectionAddrType addrType; - int32_t ret = SoftbusListener::GetTargetInfoFromCache(deviceId, targetId, addrType); + int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType); if (ret != DM_OK) { LOGE("AuthenticateDevice failed, cannot get target info from cached discovered device map."); return ERR_DM_BIND_INPUT_PARA_INVALID; @@ -521,18 +503,64 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c LOGE("The caller: %{public}s does not have permission to call UnAuthenticateDevice.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::UnAuthenticateDevice begin for pkgName = %{public}s, networkId = %{public}s", + LOGI("Begin for pkgName = %{public}s, networkId = %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); if (pkgName.empty() || networkId.empty()) { LOGE("DeviceManagerService::UnAuthenticateDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } + std::string udid = ""; + if (SoftbusListener::GetUdidByNetworkId(networkId.c_str(), udid) != DM_OK) { + LOGE("UnAuthenticateDevice GetUdidByNetworkId error: udid: %{public}s", GetAnonyString(udid).c_str()); + return ERR_DM_FAILED; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); if (!IsDMServiceImplReady()) { LOGE("UnAuthenticateDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - return dmServiceImpl_->UnAuthenticateDevice(pkgName, networkId); + uint64_t tokenId = 0; + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); + LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); + if (bindLevel == INVALIED_BIND_LEVEL) { + LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); + return ERR_DM_FAILED; + } + if (dmServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel) != DM_OK) { + LOGE("dmServiceImpl_ UnAuthenticateDevice failed."); + return ERR_DM_FAILED; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::vector peerUdids; + peerUdids.emplace_back(udid); + SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId, bindLevel); +#endif + return DM_OK; +} + +int32_t DeviceManagerService::StopAuthenticateDevice(const std::string &pkgName) +{ + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGE("The caller: %{public}s does not have permission to call StopAuthenticateDevice.", pkgName.c_str()); + return ERR_DM_NO_PERMISSION; + } + if (pkgName.empty()) { + LOGE("DeviceManagerService::StopAuthenticateDevice error: Invalid parameter, pkgName: %{public}s", + pkgName.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); + if (!IsDMServiceImplReady()) { + LOGE("StopAuthenticateDevice failed, instance not init or init failed."); + return ERR_DM_NOT_INIT; + } + if (dmServiceImpl_->StopAuthenticateDevice(pkgName) != DM_OK) { + LOGE("dmServiceImpl_ StopAuthenticateDevice failed."); + return ERR_DM_FAILED; + } + return DM_OK; } int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, @@ -550,10 +578,16 @@ int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t aut LOGE("BindDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - + std::string queryDeviceId = deviceId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHash = ""; + if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) { + queryDeviceId = udidHash; + } +#endif PeerTargetId targetId; ConnectionAddrType addrType; - int32_t ret = SoftbusListener::GetTargetInfoFromCache(deviceId, targetId, addrType); + int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType); if (ret != DM_OK) { LOGE("BindDevice failed, cannot get target info from cached discovered device map."); return ERR_DM_BIND_INPUT_PARA_INVALID; @@ -565,15 +599,14 @@ int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t aut return dmServiceImpl_->BindTarget(pkgName, targetId, bindParamMap); } -int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &deviceId) +int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &udidHash) { if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call UnBindDevice."); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::UnBindDevice begin for pkgName = %{public}s, deviceId = %{public}s", - pkgName.c_str(), GetAnonyString(deviceId).c_str()); - if (pkgName.empty() || deviceId.empty()) { + LOGI("Begin for pkgName = %{public}s, udidHash = %{public}s", pkgName.c_str(), GetAnonyString(udidHash).c_str()); + if (pkgName.empty() || udidHash.empty()) { LOGE("DeviceManagerService::UnBindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } @@ -581,7 +614,37 @@ int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std LOGE("UnBindDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - return dmServiceImpl_->UnBindDevice(pkgName, deviceId); + std::string realDeviceId = udidHash; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHashTemp = ""; + if (GetUdidHashByAnoyDeviceId(udidHash, udidHashTemp) == DM_OK) { + realDeviceId = udidHashTemp; + } +#endif + std::string udid = ""; + if (SoftbusCache::GetInstance().GetUdidByUdidHash(realDeviceId, udid) != DM_OK) { + LOGE("Get udid by udidhash failed."); + return ERR_DM_FAILED; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); + uint64_t tokenId = 0; + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); + LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); + if (bindLevel == INVALIED_BIND_LEVEL) { + LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); + return ERR_DM_FAILED; + } + if (dmServiceImpl_->UnBindDevice(pkgName, udid, bindLevel) != DM_OK) { + LOGE("dmServiceImpl_ UnBindDevice failed."); + return ERR_DM_FAILED; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::vector peerUdids; + peerUdids.emplace_back(udid); + SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId, bindLevel); +#endif + return DM_OK; } int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms) @@ -643,19 +706,19 @@ void DeviceManagerService::OnBytesReceived(int sessionId, const void *data, unsi int DeviceManagerService::OnPinHolderSessionOpened(int sessionId, int result) { - LOGI("DeviceManagerService::OnPinHolderSessionOpened"); + LOGI("In"); return PinHolderSession::OnSessionOpened(sessionId, result); } void DeviceManagerService::OnPinHolderSessionClosed(int sessionId) { - LOGI("DeviceManagerService::OnPinHolderSessionClosed"); + LOGI("In"); PinHolderSession::OnSessionClosed(sessionId); } void DeviceManagerService::OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - LOGI("DeviceManagerService::OnPinHolderBytesReceived"); + LOGI("In"); PinHolderSession::OnBytesReceived(sessionId, data, dataLen); } @@ -829,15 +892,12 @@ bool DeviceManagerService::IsDMServiceImplReady() if (isImplsoLoaded_ && (dmServiceImpl_ != nullptr)) { return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_IMPL_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; + void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE); } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { - LOGE("load libdevicemanagerserviceimpl so %{public}s failed, errMsg: %{public}s.", soName.c_str(), dlerror()); + LOGE("load libdevicemanagerserviceimpl so failed, errMsg: %{public}s.", dlerror()); return false; } dlerror(); @@ -849,8 +909,10 @@ bool DeviceManagerService::IsDMServiceImplReady() } dmServiceImpl_ = std::shared_ptr(func()); + if (listener_ == nullptr) { + listener_ = std::make_shared(); + } if (dmServiceImpl_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImpl_ = nullptr; isImplsoLoaded_ = false; return false; @@ -861,7 +923,7 @@ bool DeviceManagerService::IsDMServiceImplReady() bool DeviceManagerService::IsDMImplSoLoaded() { - LOGI("DeviceManagerService::IsDMImplSoLoaded"); + LOGI("In"); std::lock_guard lock(isImplLoadLock_); return isImplsoLoaded_; } @@ -913,16 +975,22 @@ int32_t DeviceManagerService::NotifyEvent(const std::string &pkgName, const int3 void DeviceManagerService::LoadHardwareFwkService() { - std::string extra; std::vector deviceList; - int32_t ret = GetTrustedDeviceList(DM_PKG_NAME, extra, deviceList); + CHECK_NULL_VOID(softbusListener_); + int32_t ret = GetTrustedDeviceList(DHARD_WARE_PKG_NAME, deviceList); if (ret != DM_OK) { LOGE("LoadHardwareFwkService failed, get trusted devicelist failed."); return; } - if (deviceList.size() > 0) { - dmServiceImpl_->LoadHardwareFwkService(); + if (deviceList.empty()) { + LOGI("no trusted device."); + return; } + if (!IsDMServiceImplReady()) { + LOGE("LoadHardwareFwkService failed, instance not init or init failed."); + return; + } + dmServiceImpl_->LoadHardwareFwkService(); } int32_t DeviceManagerService::GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId, @@ -932,7 +1000,7 @@ int32_t DeviceManagerService::GetEncryptedUuidByNetworkId(const std::string &pkg LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerService::GetEncryptedUuidByNetworkId for pkgName = %{public}s", pkgName.c_str()); + LOGI("PkgName = %{public}s", pkgName.c_str()); CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); int32_t ret = softbusListener_->GetUuidByNetworkId(networkId.c_str(), uuid); if (ret != DM_OK) { @@ -961,7 +1029,7 @@ int32_t DeviceManagerService::GenerateEncryptedUuid(const std::string &pkgName, int32_t DeviceManagerService::CheckApiPermission(int32_t permissionLevel) { - LOGI("DeviceManagerService::CheckApiPermission permissionLevel: %{public}d", permissionLevel); + LOGI("PermissionLevel: %{public}d", permissionLevel); int32_t ret = ERR_DM_NO_PERMISSION; switch (permissionLevel) { case NORMAL: @@ -996,7 +1064,7 @@ int32_t DeviceManagerService::GetNetworkTypeByNetworkId(const std::string &pkgNa LOGE("The caller: %{public}s does not have permission to call GetNetworkTypeByNetworkId.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::GetNetworkTypeByNetworkId begin for pkgName = %{public}s", pkgName.c_str()); + LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty() || netWorkId.empty()) { LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(), GetAnonyString(netWorkId).c_str()); @@ -1058,19 +1126,12 @@ int32_t DeviceManagerService::ExportAuthCode(std::string &authCode) void DeviceManagerService::UnloadDMServiceImplSo() { - LOGI("DeviceManagerService::UnloadDMServiceImplSo start."); + LOGI("Start."); std::lock_guard lock(isImplLoadLock_); if (dmServiceImpl_ != nullptr) { dmServiceImpl_->Release(); } - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_IMPL_NAME); - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { - LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); - return; - } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("DeviceManagerService so_handle is not nullptr."); dlclose(so_handle); @@ -1079,21 +1140,22 @@ void DeviceManagerService::UnloadDMServiceImplSo() bool DeviceManagerService::IsDMServiceAdapterLoad() { - LOGI("DeviceManagerService::IsDMServiceAdapterLoad start."); + LOGI("Start."); + if (listener_ == nullptr) { + LOGE("Dm service is not init."); + return false; + } std::lock_guard lock(isAdapterLoadLock_); if (isAdapterSoLoaded_ && (dmServiceImplExt_ != nullptr)) { return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_DM_ADAPTER_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; + void *so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NODELETE); } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { - LOGE("load dm service adapter so %{public}s failed.", soName.c_str()); + LOGE("load dm service adapter so failed."); return false; } dlerror(); @@ -1106,34 +1168,26 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() dmServiceImplExt_ = std::shared_ptr(func()); if (dmServiceImplExt_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImplExt_ = nullptr; isAdapterSoLoaded_ = false; LOGE("dm service adapter impl ext init failed."); return false; } isAdapterSoLoaded_ = true; - LOGI("DeviceManagerService::IsDMServiceAdapterLoad sucess."); + LOGI("Success."); return true; } void DeviceManagerService::UnloadDMServiceAdapter() { - LOGI("DeviceManagerService::UnloadDMServiceAdapter start."); + LOGI("Start."); std::lock_guard lock(isAdapterLoadLock_); if (dmServiceImplExt_ != nullptr) { dmServiceImplExt_->Release(); } dmServiceImplExt_ = nullptr; - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_DM_ADAPTER_NAME); - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { - LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); - return; - } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + void *so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("dm service adapter so_handle is not nullptr."); dlclose(so_handle); @@ -1143,11 +1197,12 @@ void DeviceManagerService::UnloadDMServiceAdapter() int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName, const std::map &discoverParam, const std::map &filterOptions) { - if (!PermissionManager::GetInstance().CheckNewPermission()) { + if (!PermissionManager::GetInstance().CheckNewPermission() && + !PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StartDiscovering for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1162,11 +1217,12 @@ int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName, int32_t DeviceManagerService::StopDiscovering(const std::string &pkgName, const std::map &discoverParam) { - if (!PermissionManager::GetInstance().CheckNewPermission()) { + if (!PermissionManager::GetInstance().CheckNewPermission() && + !PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StopDiscovering for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1189,7 +1245,7 @@ int32_t DeviceManagerService::EnableDiscoveryListener(const std::string &pkgName LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::EnableDiscoveryListener for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1206,7 +1262,7 @@ int32_t DeviceManagerService::DisableDiscoveryListener(const std::string &pkgNam LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::DisableDiscoveryListener for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1222,7 +1278,7 @@ int32_t DeviceManagerService::StartAdvertising(const std::string &pkgName, LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StartAdvertising for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1238,7 +1294,7 @@ int32_t DeviceManagerService::StopAdvertising(const std::string &pkgName, LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StopAdvertising for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1261,7 +1317,7 @@ int32_t DeviceManagerService::BindTarget(const std::string &pkgName, const PeerT LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::BindTarget for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1301,7 +1357,7 @@ int32_t DeviceManagerService::UnbindTarget(const std::string &pkgName, const Pee LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::UnbindTarget for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1382,7 +1438,7 @@ int32_t DeviceManagerService::DestroyPinHolder(const std::string &pkgName, const LOGE("The caller: %{public}s is not in white list.", processName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerService::DestroyPinHolder begin."); + LOGI("Begin."); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; @@ -1391,40 +1447,13 @@ int32_t DeviceManagerService::DestroyPinHolder(const std::string &pkgName, const return pinHolder_->DestroyPinHolder(pkgName, targetId, pinType, payload); } -void DeviceManagerService::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) -{ - if (!IsDMServiceImplReady()) { - LOGE("OnUnbindSessionOpened failed, instance not init or init failed."); - return; - } - dmServiceImpl_->OnUnbindSessionOpened(socket, info); -} - -void DeviceManagerService::OnUnbindSessionCloseed(int32_t socket) -{ - if (!IsDMServiceImplReady()) { - LOGE("OnUnbindSessionCloseed failed, instance not init or init failed."); - return; - } - dmServiceImpl_->OnUnbindSessionCloseed(socket); -} - -void DeviceManagerService::OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - if (!IsDMServiceImplReady()) { - LOGE("OnUnbindBytesReceived failed, instance not init or init failed."); - return; - } - dmServiceImpl_->OnUnbindBytesReceived(socket, data, dataLen); -} - int32_t DeviceManagerService::DpAclAdd(const std::string &udid) { if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call DpAclAdd."); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService DpAclAdd start."); + LOGI("Start."); if (!IsDMServiceImplReady()) { LOGE("DpAclAdd failed, instance not init or init failed."); return ERR_DM_NOT_INIT; @@ -1437,7 +1466,7 @@ int32_t DeviceManagerService::DpAclAdd(const std::string &udid) int32_t DeviceManagerService::GetDeviceSecurityLevel(const std::string &pkgName, const std::string &networkId, int32_t &securityLevel) { - LOGI("DeviceManagerService::GetDeviceSecurityLevel begin pkgName: %{public}s, networkId: %{public}s", + LOGI("Begin pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller: %{public}s does not have permission to call GetDeviceSecurityLevel.", pkgName.c_str()); @@ -1459,7 +1488,7 @@ int32_t DeviceManagerService::GetDeviceSecurityLevel(const std::string &pkgName, int32_t DeviceManagerService::IsSameAccount(const std::string &networkId) { - LOGI("DeviceManagerService::IsSameAccount networkId %{public}s.", GetAnonyString(networkId).c_str()); + LOGI("NetworkId %{public}s.", GetAnonyString(networkId).c_str()); if (!PermissionManager::GetInstance().CheckPermission()) { return ERR_DM_NO_PERMISSION; } @@ -1479,11 +1508,11 @@ bool DeviceManagerService::CheckAccessControl(const DmAccessCaller &caller, cons { if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller: %{public}s does not have permission to call CheckAccessControl.", caller.pkgName.c_str()); - return ERR_DM_NO_PERMISSION; + return false; } if (!IsDMServiceImplReady()) { LOGE("CheckAccessControl failed, instance not init or init failed."); - return ERR_DM_NOT_INIT; + return false; } std::string srcUdid = ""; SoftbusListener::GetUdidByNetworkId(caller.networkId.c_str(), srcUdid); @@ -1496,11 +1525,11 @@ bool DeviceManagerService::CheckIsSameAccount(const DmAccessCaller &caller, cons { if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller: %{public}s does not have permission to call CheckIsSameAccount.", caller.pkgName.c_str()); - return ERR_DM_NO_PERMISSION; + return false; } if (!IsDMServiceImplReady()) { LOGE("CheckIsSameAccount failed, instance not init or init failed."); - return ERR_DM_NOT_INIT; + return false; } std::string srcUdid = ""; SoftbusListener::GetUdidByNetworkId(caller.networkId.c_str(), srcUdid); @@ -1513,7 +1542,7 @@ int32_t DeviceManagerService::InitAccountInfo() { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) SubscribeAccountCommonEvent(); - LOGI("InitAccountInfo success."); + LOGI("Success."); #endif return DM_OK; } @@ -1522,7 +1551,7 @@ int32_t DeviceManagerService::InitScreenLockEvent() { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) SubscribeScreenLockEvent(); - LOGI("InitScreenLockEvent success."); + LOGI("Success."); #endif return DM_OK; } @@ -1530,26 +1559,27 @@ int32_t DeviceManagerService::InitScreenLockEvent() #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void DeviceManagerService::SubscribeAccountCommonEvent() { - LOGI("DeviceManagerServiceImpl::SubscribeAccountCommonEvent"); + LOGI("Start"); if (accountCommonEventManager_ == nullptr) { accountCommonEventManager_ = std::make_shared(); } - AccountEventCallback callback = [=](const auto &arg1, const auto &arg2) { - this->AccountCommonEventCallback(arg1, arg2); + AccountEventCallback callback = [=](const auto &eventType, const auto ¤tUserId, const auto &beforeUserId) { + this->AccountCommonEventCallback(eventType, currentUserId, beforeUserId); }; std::vector AccountCommonEventVec; AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_REMOVED); AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGIN); if (accountCommonEventManager_->SubscribeAccountCommonEvent(AccountCommonEventVec, callback)) { - LOGI("subscribe account common event success"); + LOGI("Success"); } return; } void DeviceManagerService::SubscribeScreenLockEvent() { - LOGI("DeviceManagerServiceImpl::SubscribeScreenLockEvent"); + LOGI("Start"); if (screenCommonEventManager_ == nullptr) { screenCommonEventManager_ = std::make_shared(); } @@ -1557,44 +1587,255 @@ void DeviceManagerService::SubscribeScreenLockEvent() std::vector screenEventVec; screenEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED); if (screenCommonEventManager_->SubscribeScreenCommonEvent(screenEventVec, callback)) { - LOGI("subscribe screen common event success"); + LOGI("Success"); } return; } -void DeviceManagerService::AccountCommonEventCallback(int32_t userId, std::string commonEventType) +void DeviceManagerService::AccountCommonEventCallback(const std::string commonEventType, int32_t currentUserId, + int32_t beforeUserId) { - LOGI("AccountCommonEventCallback start, commonEventType: %{public}s", commonEventType.c_str()); - if ((commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED || - commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN)) { - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - LOGI("accountId: %{public}s, userId: %{public}s", GetAnonyString(accountId).c_str(), - GetAnonyInt32(userId).c_str()); - if (userId > 0) { - MultipleUserConnector::SetSwitchOldUserId(userId); - MultipleUserConnector::SetSwitchOldAccountId(accountId); + LOGI("CommonEventType: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", commonEventType.c_str(), + currentUserId, beforeUserId); + if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + MultipleUserConnector::SetAccountInfo(currentUserId, dmAccountInfo); + if (beforeUserId == -1 || currentUserId == -1) { + return; + } else if (beforeUserId != -1 && currentUserId != -1) { + HandleUserSwitched(currentUserId, beforeUserId); } - return; + if (IsDMServiceAdapterLoad()) { + dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); + } + } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + MultipleUserConnector::SetAccountInfo(currentUserId, dmAccountInfo); + } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { + DMAccountInfo dmAccountInfo = MultipleUserConnector::GetAccountInfoByUserId(beforeUserId); + if (dmAccountInfo.accountId.empty()) { + return; + } + HandleAccountLogout(currentUserId, dmAccountInfo.accountId, dmAccountInfo.accountName); + MultipleUserConnector::DeleteAccountInfoByUserId(currentUserId); + } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + HandleUserRemoved(beforeUserId); + MultipleUserConnector::DeleteAccountInfoByUserId(beforeUserId); + } else { + LOGE("Invalied account common event."); } + return; +} - if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - std::vector onlineDeviceList; - CHECK_NULL_VOID(softbusListener_); - int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList); - if (ret != DM_OK) { - LOGE("GetTrustedDeviceList failed, ret: %{public}d", ret); +void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string &accountId, + const std::string &accountName) +{ + LOGI("UserId: %{public}d, accountId: %{public}s, accountName: %{public}s", userId, + GetAnonyString(accountId).c_str(), GetAnonyString(accountName).c_str()); + if (IsDMServiceAdapterLoad()) { + dmServiceImplExt_->AccountIdLogout(userId, accountId); + } + if (!IsDMServiceImplReady()) { + LOGE("Init impl failed."); + return; + } + std::multimap deviceMap; + std::vector peerUdids; + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(userId, accountId); + for (const auto &item : deviceMap) { + peerUdids.emplace_back(item.first); + } + if (!peerUdids.empty()) { + char accountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accountId, reinterpret_cast(accountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); return; } - if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { - if (IsDMServiceAdapterLoad()) { - dmServiceImplExt_->AccountIdLogout(userId, MultipleUserConnector::GetSwitchOldAccountId()); - } - dmServiceImpl_->AccountCommonEventCallback(userId, commonEventType); + SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); + } + for (const auto &item : deviceMap) { + dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second); + } +} + +void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUserId) +{ + LOGI("currentUserId: %{public}d. previousUserId: %{public}d", curUserId, preUserId); + if (!IsDMServiceImplReady()) { + LOGE("Init impl failed."); + return; + } + std::map curUserDeviceMap; + std::map preUserDeviceMap; + std::vector peerUdids; + curUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(curUserId); + preUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(preUserId); + for (const auto &item : curUserDeviceMap) { + peerUdids.push_back(item.first); + } + for (const auto &item : preUserDeviceMap) { + if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) { + peerUdids.push_back(item.first); + } + } + dmServiceImpl_->HandleUserSwitched(preUserDeviceMap, curUserId, preUserId); + if (!peerUdids.empty()) { + std::vector foregroundUserVec; + int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec); + std::vector backgroundUserVec; + int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec); + if (retFront != DM_OK || retBack != DM_OK || foregroundUserVec.empty()) { + LOGE("Get userids failed, retFront: %{public}d, retBack: %{public}d, foreground user num: %{public}d", + retFront, retBack, static_cast(foregroundUserVec.size())); + } else { + LOGE("Send local foreground and background userids"); + SendUserIdsBroadCast(peerUdids, foregroundUserVec, backgroundUserVec, true); + } + } +} + +void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) +{ + LOGI("PreUserId %{public}d.", removedUserId); + if (!IsDMServiceImplReady()) { + LOGE("Init impl failed."); + return; + } + std::multimap deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(removedUserId); + std::vector peerUdids; + for (const auto &item : deviceMap) { + if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) { + peerUdids.emplace_back(item.first); + } + } + if (!peerUdids.empty()) { + // Send UserId Removed broadcast + SendUserRemovedBroadCast(peerUdids, removedUserId); + } + dmServiceImpl_->HandleUserRemoved(removedUserId); +} + +void DeviceManagerService::SendUserRemovedBroadCast(const std::vector &peerUdids, int32_t userId) +{ + LOGI("peerUdids: %{public}s, userId %{public}d.", GetAnonyStringList(peerUdids).c_str(), userId); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEL_USER; + msg.userId = userId; + msg.peerUdids = peerUdids; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::SendAccountLogoutBroadCast(const std::vector &peerUdids, + const std::string &accountId, const std::string &accountName, int32_t userId) +{ + LOGI("accountId %{public}s, accountName %{public}s, userId %{public}d.", GetAnonyString(accountId).c_str(), + GetAnonyString(accountName).c_str(), userId); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = static_cast(userId); + msg.peerUdids = peerUdids; + msg.accountId = accountId; + msg.accountName = accountName; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::SendUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, bool isNeedResponse) +{ + LOGI("peerUdids: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, isNeedRsp: %{public}s", + GetAnonyStringList(peerUdids).c_str(), GetIntegerList(foregroundUserIds).c_str(), + GetIntegerList(backgroundUserIds).c_str(), isNeedResponse ? "true" : "false"); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SYNC_USERID; + msg.peerUdids = peerUdids; + msg.syncUserIdFlag = isNeedResponse; + for (const auto &userId : foregroundUserIds) { + msg.userIdInfos.push_back({ true, static_cast(userId) }); + } + for (auto const &userId : backgroundUserIds) { + msg.userIdInfos.push_back({ false, static_cast(userId) }); + } + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::HandleUserIdsBroadCast(const std::vector &remoteUserIdInfos, + const std::string &remoteUdid, bool isNeedResponse) +{ + LOGI("rmtUdid: %{public}s, rmtUserIds: %{public}s, isNeedResponse: %{public}s,", + GetAnonyString(remoteUdid).c_str(), GetUserIdInfoList(remoteUserIdInfos).c_str(), + isNeedResponse ? "true" : "false"); + if (isNeedResponse) { + std::vector foregroundUserVec; + std::vector backgroundUserVec; + int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec); + int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec); + if (retFront != DM_OK || retBack!= DM_OK || foregroundUserVec.empty()) { + LOGE("Get userid failed, retFront: %{public}d, retBack: %{public}d, frontUserNum:%{public}d," + "backUserNum: %{public}d", retFront, retBack, static_cast(foregroundUserVec.size()), + static_cast(backgroundUserVec.size())); + } else { + LOGE("Send back local frontuserids: %{public}s, backuserids: %{public}s", + GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str()); + std::vector remoteUdids = { remoteUdid }; + SendUserIdsBroadCast(remoteUdids, foregroundUserVec, backgroundUserVec, false); + } + } + + std::vector foregroundUserIdInfos; + std::vector backgroundUserIdInfos; + GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos); + if (foregroundUserIdInfos.empty()) { + LOGE("receive remote foreground userid empty"); + } else { + LOGI("process foreground and background userids"); + // Notify received remote foreground userids to dsoftbus + std::vector foregroundUserIds; + for (const auto &u : foregroundUserIdInfos) { + foregroundUserIds.push_back(static_cast(u.userId)); + } + std::vector backgroundUserIds; + for (const auto &u : backgroundUserIdInfos) { + backgroundUserIds.push_back(static_cast(u.userId)); + } + if (softbusListener_ != nullptr) { + softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds); + } + + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid); } } } +void DeviceManagerService::ProcessSyncUserIds(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid) +{ + LOGI("process sync foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, remote udid: %{public}s", + GetIntegerList(foregroundUserIds).c_str(), GetIntegerList(backgroundUserIds).c_str(), + GetAnonyString(remoteUdid).c_str()); + + if (softbusListener_ != nullptr) { + softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds); + } + + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid); + } +} + void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType) { if (!IsDMImplSoLoaded()) { @@ -1607,7 +1848,7 @@ void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) { - LOGI("DeviceManagerService::HandleDeviceNotTrust."); + LOGI("Start."); if (msg.empty()) { LOGE("DeviceManagerService::HandleDeviceNotTrust msg is empty."); return; @@ -1624,15 +1865,469 @@ void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) std::string networkId = msgJsonObj[NETWORKID].get(); std::string udid = ""; SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid); - LOGI("HandleDeviceNotTrust networkId: %{public}s, udid: %{public}s.", + LOGI("NetworkId: %{public}s, udid: %{public}s.", GetAnonyString(networkId).c_str(), GetAnonyString(udid).c_str()); - if (IsDMImplSoLoaded()) { + if (IsDMServiceImplReady()) { dmServiceImpl_->HandleDeviceNotTrust(udid); } - if (IsDMServiceImplReady()) { + if (IsDMServiceAdapterLoad()) { dmServiceImplExt_->HandleDeviceNotTrust(udid); } return; } + +int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::map &policy) +{ + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGE("The caller does not have permission to call"); + return ERR_DM_NO_PERMISSION; + } + std::string processName = ""; + if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) { + LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str()); + return ERR_DM_FAILED; + } + if (!PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName)) { + LOGE("The caller: %{public}s is not in white list.", processName.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + auto policyStrategyIter = policy.find(PARAM_KEY_POLICY_STRATEGY_FOR_BLE); + if (policyStrategyIter == policy.end()) { + LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + auto timeOutIter = policy.find(PARAM_KEY_POLICY_TIME_OUT); + if (timeOutIter == policy.end()) { + LOGE("Invalid parameter, DM_POLICY_TIMEOUT is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!IsNumberString(policyStrategyIter->second)) { + LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is not number."); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!IsNumberString(timeOutIter->second)) { + LOGE("Invalid parameter, DM_POLICY_TIMEOUT is not number."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t policyStrategy = std::atoi(policyStrategyIter->second.c_str()); + int32_t timeOut = std::atoi(timeOutIter->second.c_str()); + LOGD("strategy: %{public}d, timeOut: %{public}d", policyStrategy, timeOut); + if (!IsDMServiceAdapterLoad()) { + LOGE("SetDnPolicy failed, instance not init or init failed."); + return ERR_DM_UNSUPPORTED_METHOD; + } + return dmServiceImplExt_->SetDnPolicy(policyStrategy, timeOut); +} + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +void DeviceManagerService::ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInfo) +{ + std::string udidHashTemp = ""; + if (ConvertUdidHashToAnoyDeviceId(deviceInfo.deviceId, udidHashTemp) == DM_OK) { + if (memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { + LOGE("ConvertUdidHashToAnoyDeviceId memset_s failed."); + return; + } + if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); + return; + } + } +} + +int32_t DeviceManagerService::ConvertUdidHashToAnoyDeviceId(const std::string &udidHash, std::string &result) +{ + LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str()); + std::string appId = AppManager::GetInstance().GetAppId(); + if (appId.empty()) { + LOGD("GetAppId failed"); + return ERR_DM_FAILED; + } + DmKVValue kvValue; + int32_t ret = Crypto::ConvertUdidHashToAnoyAndSave(appId, udidHash, kvValue); + if (ret != DM_OK) { + return ERR_DM_FAILED; + } + result = kvValue.anoyDeviceId; + return DM_OK; +} + +int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash) +{ + LOGI("anoyDeviceId %{public}s.", GetAnonyString(anoyDeviceId).c_str()); + DmKVValue kvValue; + if (KVAdapterManager::GetInstance().Get(anoyDeviceId, kvValue) != DM_OK) { + LOGD("Get kv value from DB failed"); + return ERR_DM_FAILED; + } + udidHash = kvValue.udidHash; + LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str()); + return DM_OK; +} + +void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, + uint64_t tokenId, int32_t bindLevel) +{ + LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); + if (bindLevel == DEVICE) { + SendDeviceUnBindBroadCast(peerUdids, userId); + return; + } + if (bindLevel == APP) { + SendAppUnBindBroadCast(peerUdids, userId, tokenId); + return; + } + if (bindLevel == SERVICE) { + SendServiceUnBindBroadCast(peerUdids, userId, tokenId); + return; + } +} + +void DeviceManagerService::SendDeviceUnBindBroadCast(const std::vector &peerUdids, int32_t userId) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEVICE_UNBIND; + msg.userId = static_cast(userId); + msg.peerUdids = peerUdids; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::SendAppUnBindBroadCast(const std::vector &peerUdids, int32_t userId, + uint64_t tokenId) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = static_cast(userId); + msg.peerUdids = peerUdids; + msg.tokenId = tokenId; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::SendServiceUnBindBroadCast(const std::vector &peerUdids, int32_t userId, + uint64_t tokenId) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SERVICE_UNBIND; + msg.userId = static_cast(userId); + msg.peerUdids = peerUdids; + msg.tokenId = tokenId; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) +{ + if (msg.empty()) { + LOGE("Msg is empty."); + return; + } + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + LOGI("Receive trust change msg: %{public}s", relationShipMsg.ToString().c_str()); + if (!IsDMServiceImplReady()) { + LOGE("Imp instance not init or init failed."); + return; + } + switch (relationShipMsg.type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + dmServiceImpl_->HandleAccountLogoutEvent(relationShipMsg.userId, relationShipMsg.accountId, + relationShipMsg.peerUdid); + break; + case RelationShipChangeType::DEVICE_UNBIND: + dmServiceImpl_->HandleDevUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid); + break; + case RelationShipChangeType::APP_UNBIND: + dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, + static_cast(relationShipMsg.tokenId)); + break; + case RelationShipChangeType::SYNC_USERID: + HandleUserIdsBroadCast(relationShipMsg.userIdInfos, + relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag); + break; + case RelationShipChangeType::DEL_USER: + dmServiceImpl_->HandleRemoteUserRemoved(relationShipMsg.userId, relationShipMsg.peerUdid); + break; + default: + LOGI("Dm have not this event type."); + break; + } + return; +} + +int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType, + bool &isChange) +{ + nlohmann::json msgJsonObj = nlohmann::json::parse(msg, nullptr, false); + if (msgJsonObj.is_discarded()) { + LOGE("msg prase error."); + return ERR_DM_FAILED; + } + if (!IsString(msgJsonObj, USERID_CHECKSUM_NETWORKID_KEY)) { + LOGE("msg not contain networkId."); + return ERR_DM_FAILED; + } + if (!IsUint32(msgJsonObj, USERID_CHECKSUM_DISCOVER_TYPE_KEY)) { + LOGE("msg not contain discoveryType."); + return ERR_DM_FAILED; + } + if (!IsBool(msgJsonObj, USERID_CHECKSUM_ISCHANGE_KEY)) { + LOGE("msg not contain ischange."); + return ERR_DM_FAILED; + } + networkId = msgJsonObj[USERID_CHECKSUM_NETWORKID_KEY].get(); + discoveryType = msgJsonObj[USERID_CHECKSUM_DISCOVER_TYPE_KEY].get(); + isChange = msgJsonObj[USERID_CHECKSUM_ISCHANGE_KEY].get(); + return DM_OK; +} + +void DeviceManagerService::ProcessCheckSumByWifi(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds) +{ + if (localNetWorkId_ == "") { + DmDeviceInfo deviceInfo; + SoftbusCache::GetInstance().GetLocalDeviceInfo(deviceInfo); + localNetWorkId_ = std::string(deviceInfo.networkId); + } + if (localNetWorkId_ >= networkId) { + LOGI("Local networkid big than remote, no need begin req"); + return; + } + // use connection to exchange foreground/background userid + LOGI("Try open softbus session to exchange foreground/background userid"); + std::vector foregroundUserIdsUInt; + for (auto const &u : foregroundUserIds) { + foregroundUserIdsUInt.push_back(static_cast(u)); + } + std::vector backgroundUserIdsUInt; + for (auto const &u : backgroundUserIds) { + backgroundUserIdsUInt.push_back(static_cast(u)); + } + DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backgroundUserIdsUInt); +} + +void DeviceManagerService::ProcessCheckSumByBT(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds) +{ + LOGI("Try send brodcast to exchange foreground userid"); + std::string udid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid); + if (udid.empty()) { + LOGE("Can not get udid for networkid: %{public}s", GetAnonyString(networkId).c_str()); + return; + } + + std::vector peerUdids = { udid }; + if (!foregroundUserIds.empty()) { + LOGI("Send local foreground and background userids"); + SendUserIdsBroadCast(peerUdids, foregroundUserIds, backgroundUserIds, true); + } else { + LOGE("local foreground userids empty"); + } +} + +void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg) +{ + if (msg.empty()) { + LOGE("Msg is empty."); + return; + } + LOGI("handle user trust change, msg: %{public}s", GetAnonyString(msg).c_str()); + std::string remoteNetworkId = ""; + uint32_t discoveryType = 0; + bool isPeerUserIdChanged = true; + int32_t ret = ParseCheckSumMsg(msg, remoteNetworkId, discoveryType, isPeerUserIdChanged); + if (ret != DM_OK) { + LOGE("Parse checksum msg error"); + return; + } + if (!isPeerUserIdChanged) { + LOGI("Peer foreground userId not change."); + return; + } + std::vector foregroundUserIds; + ret = MultipleUserConnector::GetForegroundUserIds(foregroundUserIds); + if (ret != DM_OK || foregroundUserIds.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + return; + } + + std::vector backgroundUserIds; + ret = MultipleUserConnector::GetBackgroundUserIds(backgroundUserIds); + if (ret != DM_OK || backgroundUserIds.empty()) { + LOGI("Can not get background userids, ret: %{public}d, background userid num: %{public}d", + ret, static_cast(backgroundUserIds.size())); + } + + if ((discoveryType & USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK) != 0x0) { + ProcessCheckSumByWifi(remoteNetworkId, foregroundUserIds, backgroundUserIds); + } else { + ProcessCheckSumByBT(remoteNetworkId, foregroundUserIds, backgroundUserIds); + } +} +#endif + +void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo) +{ + LOGI("PkgName: %{public}s, userId: %{public}d", processInfo.pkgName.c_str(), processInfo.userId); + CHECK_NULL_VOID(discoveryMgr_); + discoveryMgr_->ClearDiscoveryCache(processInfo); +} + +void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo) +{ + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleDeviceScreenStatusChange(deviceInfo); + } +} + +int32_t DeviceManagerService::GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) +{ + LOGI("Begin pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGE("The caller: %{public}s does not have permission to call GetDeviceScreenStatus.", pkgName.c_str()); + return ERR_DM_NO_PERMISSION; + } + if (pkgName.empty() || networkId.empty()) { + LOGE("Invalid parameter, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), + GetAnonyString(networkId).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); + int32_t ret = softbusListener_->GetDeviceScreenStatus(networkId.c_str(), screenStatus); + if (ret != DM_OK) { + LOGE("GetDeviceScreenStatus failed, ret = %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceManagerService::GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, + std::string &networkId) +{ + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGE("The caller: %{public}s does not have permission to call GetNetworkIdByUdid.", pkgName.c_str()); + return ERR_DM_NO_PERMISSION; + } + if (pkgName.empty() || udid.empty()) { + LOGE("Invalid parameter, pkgName: %{public}s, udid: %{public}s", pkgName.c_str(), GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + return SoftbusListener::GetNetworkIdByUdid(udid, networkId); +} + +void DeviceManagerService::SubscribePackageCommonEvent() +{ + LOGI("Start"); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (packageCommonEventManager_ == nullptr) { + packageCommonEventManager_ = std::make_shared(); + } + PackageEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) { + if (IsDMServiceImplReady()) { + dmServiceImpl_->ProcessAppUnintall(arg1, arg3); + } + KVAdapterManager::GetInstance().AppUnintall(arg1); + }; + std::vector commonEventVec; + commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + if (packageCommonEventManager_->SubscribePackageCommonEvent(commonEventVec, callback)) { + LOGI("Success"); + } +#endif +} + +void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) +{ + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); + } +} + +int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceName, + const std::string &localDisplayName) +{ + LOGI("DeviceManagerService Start SetLocalDeviceName!"); + CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); + int32_t ret = softbusListener_->SetLocalDeviceName(localDeviceName, localDisplayName); + if (ret != DM_OK) { + LOGE("SetLocalDeviceName error, failed ret: %{public}d", ret); + return ret; + } + return DM_OK; +} + +void DeviceManagerService::RemoveNotifyRecord(const ProcessInfo &processInfo) +{ + LOGI("start"); + CHECK_NULL_VOID(listener_); + listener_->OnProcessRemove(processInfo); +} + +int32_t DeviceManagerService::RegDevStateCallbackToService(const std::string &pkgName) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL); + std::vector deviceList; + GetTrustedDeviceList(pkgName, deviceList); + if (deviceList.size() == 0) { + return DM_OK; + } + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = userId; + listener_->OnDevStateCallbackAdd(processInfo, deviceList); +#else + (void)pkgName; +#endif + return DM_OK; +} + +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList) +{ + LOGI("Begin for pkgName = %{public}s.", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + std::vector onlineDeviceList; + CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); + int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList); + if (ret != DM_OK) { + LOGE("failed"); + return ret; + } + if (!onlineDeviceList.empty() && IsDMServiceImplReady()) { + std::unordered_map udidMap; + if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) { + udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME)); + } else { + udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName); + } + for (auto item : onlineDeviceList) { + std::string udid = ""; + SoftbusListener::GetUdidByNetworkId(item.networkId, udid); + if (udidMap.find(udid) != udidMap.end()) { + item.authForm = udidMap[udid]; + deviceList.push_back(item); + } + } + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index e0dee7d7419ac18ab234339a512824057f4a966d..fadb9def0ff48b22766231f022274156cac100a3 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -13,18 +13,25 @@ * limitations under the License. */ +#include + #include "device_manager_service_listener.h" +#include "app_manager.h" #include "device_manager_ipc_interface_code.h" +#include "device_manager_service_notify.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_log.h" +#include "dm_softbus_cache.h" #include "ipc_create_pin_holder_req.h" +#include "ipc_credential_auth_status_req.h" #include "ipc_destroy_pin_holder_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" #include "ipc_notify_credential_req.h" +#include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_device_found_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_device_state_req.h" @@ -32,210 +39,231 @@ #include "ipc_notify_pin_holder_event_req.h" #include "ipc_notify_publish_result_req.h" #include "ipc_server_stub.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "datetime_ex.h" +#include "kv_adapter_manager.h" +#include "multiple_user_connector.h" +#endif +#include "parameter.h" #include "permission_manager.h" namespace OHOS { namespace DistributedHardware { -std::mutex DeviceManagerServiceListener::dmListenerMapLock_; -std::mutex DeviceManagerServiceListener::udidHashMapLock_; -std::map DeviceManagerServiceListener::dmListenerMap_ = {}; -std::map> DeviceManagerServiceListener::udidHashMap_ = {}; -std::mutex DeviceManagerServiceListener::alreadyOnlineSetLock_; -std::unordered_set DeviceManagerServiceListener::alreadyOnlineSet_ = {}; -const int32_t LAST_APP_ONLINE_NUMS = 5; +std::mutex DeviceManagerServiceListener::alreadyNotifyPkgNameLock_; +std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::unordered_set DeviceManagerServiceListener::highPriorityPkgNameSet_ = { "ohos.deviceprofile", + "ohos.distributeddata.service" }; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { - (void)memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + (void)pkgName; + if (memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != DM_OK) { + LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed."); + return; + } + if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + return; } if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + return; } + if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); + return; } + deviceBasicInfo.deviceTypeId = info.deviceTypeId; } void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptr pReq, - const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo) { - LOGI("DeviceManagerServiceListener::SetDeviceInfo"); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); + pReq->SetProcessInfo(processInfo); pReq->SetDeviceState(state); - pReq->SetDeviceInfo(deviceInfo); + DmDeviceInfo dmDeviceInfo = deviceInfo; + FillUdidAndUuidToDeviceInfo(processInfo.pkgName, dmDeviceInfo); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string appId = ""; + if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) { + pReq->SetDeviceInfo(dmDeviceInfo); + pReq->SetDeviceBasicInfo(deviceBasicInfo); + return; + } + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); + DmDeviceBasicInfo dmDeviceBasicInfo = deviceBasicInfo; + if (memset_s(dmDeviceBasicInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); + return; + } + if (memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), dmDeviceInfo.deviceId, + std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(dmDeviceInfo.deviceId))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); + return; + } + pReq->SetDeviceInfo(dmDeviceInfo); + pReq->SetDeviceBasicInfo(dmDeviceBasicInfo); + return; +#endif + pReq->SetDeviceInfo(dmDeviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); } -std::string DeviceManagerServiceListener::ComposeOnlineKey(const std::string &pkgName, const std::string &devId) +int32_t DeviceManagerServiceListener::FillUdidAndUuidToDeviceInfo(const std::string &pkgName, + DmDeviceInfo &dmDeviceInfo) { - return pkgName + "_" + devId; -} - -void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, - const DmDeviceBasicInfo &deviceBasicInfo) -{ - LOGI("DeviceManagerServiceListener::ProcessDeviceStateChange"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); - if (state == DEVICE_STATE_OFFLINE) { - for (const auto &it : PkgNameVec) { - std::string notifyKey = ComposeOnlineKey(it, std::string(info.deviceId)); - { - std::lock_guard autoLock(alreadyOnlineSetLock_); - alreadyOnlineSet_.erase(notifyKey); - } - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } + if (highPriorityPkgNameSet_.find(pkgName) == highPriorityPkgNameSet_.end()) { + return DM_OK; } - if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : PkgNameVec) { - std::string notifyKey = ComposeOnlineKey(it, std::string(info.deviceId)); - DmDeviceState notifyState = state; - { - std::lock_guard autoLock(alreadyOnlineSetLock_); - if (alreadyOnlineSet_.find(notifyKey) != alreadyOnlineSet_.end()) { - notifyState = DmDeviceState::DEVICE_INFO_CHANGED; - } else { - alreadyOnlineSet_.insert(notifyKey); - } - } - SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } + std::string extraData = dmDeviceInfo.extraData; + std::string udid = ""; + std::string uuid = ""; + if (SoftbusCache::GetInstance().GetUdidFromCache(dmDeviceInfo.networkId, udid) != DM_OK) { + LOGE("GetUdidFromCache fail, networkId:%{public}s ", GetAnonyString(dmDeviceInfo.networkId).c_str()); + return ERR_DM_FAILED; } - if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - for (const auto &it : PkgNameVec) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } + if (SoftbusCache::GetInstance().GetUuidFromCache(dmDeviceInfo.networkId, uuid) != DM_OK) { + LOGE("GetUuidFromCache fail, networkId:%{public}s ", GetAnonyString(dmDeviceInfo.networkId).c_str()); + return ERR_DM_FAILED; + } + nlohmann::json extraJson; + if (!extraData.empty()) { + extraJson = nlohmann::json::parse(extraData, nullptr, false); + } + if (!extraJson.is_discarded()) { + extraJson[PARAM_KEY_UDID] = udid; + extraJson[PARAM_KEY_UUID] = uuid; + dmDeviceInfo.extraData = to_string(extraJson); } + return DM_OK; } -void DeviceManagerServiceListener::ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, +void DeviceManagerServiceListener::ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { - LOGI("DeviceManagerServiceListener::ProcessAppStateChange"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); - if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : notifyPkgnames) { - std::string notifyKey = it + "_" + info.deviceId; - { - std::lock_guard autoLock(alreadyOnlineSetLock_); - if (alreadyOnlineSet_.find(notifyKey) != alreadyOnlineSet_.end()) { - continue; - } - alreadyOnlineSet_.insert(notifyKey); - } - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_STATE_OFFLINE) { - if (alreadyOnlineSet_.size() == LAST_APP_ONLINE_NUMS) { - { - std::lock_guard autoLock(alreadyOnlineSetLock_); - alreadyOnlineSet_.clear(); - } - for (const auto &it : notifyPkgnames) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } + LOGI("In"); + std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId, + DmCommonNotifyEvent::REG_DEVICE_STATE); + std::vector hpProcessInfoVec; + std::vector lpProcessInfoVec; + for (const auto &it : processInfoVec) { + if (highPriorityPkgNameSet_.find(it.pkgName) != highPriorityPkgNameSet_.end()) { + hpProcessInfoVec.push_back(it); } else { - std::string notifyKey = pkgName + "_" + info.deviceId; - { - std::lock_guard autoLock(alreadyOnlineSetLock_); - if (alreadyOnlineSet_.find(notifyKey) != alreadyOnlineSet_.end()) { - alreadyOnlineSet_.erase(notifyKey); - } - } - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + lpProcessInfoVec.push_back(it); } } - if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + + switch (static_cast(state)) { + case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): + ProcessDeviceOnline(hpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceOnline(lpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_STATE_OFFLINE): + ProcessDeviceOffline(lpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceOffline(hpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_INFO_READY): + case static_cast(DmDeviceState::DEVICE_INFO_CHANGED): + ProcessDeviceInfoChange(hpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceInfoChange(lpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + break; + default: + break; } } -void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, +void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("In"); + std::vector processInfoVec = GetWhiteListSAProcessInfo(DmCommonNotifyEvent::REG_DEVICE_STATE); + ProcessInfo bindProcessInfo = DealBindProcessInfo(processInfo); + processInfoVec.push_back(bindProcessInfo); + switch (static_cast(state)) { + case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): + ProcessAppOnline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_STATE_OFFLINE): + ProcessAppOffline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_INFO_READY): + case static_cast(DmDeviceState::DEVICE_INFO_CHANGED): + ProcessDeviceInfoChange(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + default: + break; + } +} + +void DeviceManagerServiceListener::OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info) { LOGI("OnDeviceStateChange, state = %{public}d", state); DmDeviceBasicInfo deviceBasicInfo; - ConvertDeviceInfoToDeviceBasicInfo(pkgName, info, deviceBasicInfo); - if (pkgName == std::string(DM_PKG_NAME)) { - ProcessDeviceStateChange(state, info, deviceBasicInfo); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, info, deviceBasicInfo); + if (processInfo.pkgName == std::string(DM_PKG_NAME)) { + ProcessDeviceStateChange(processInfo, state, info, deviceBasicInfo); } else { - ProcessAppStateChange(pkgName, state, info, deviceBasicInfo); + ProcessAppStateChange(processInfo, state, info, deviceBasicInfo); } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + KVAdapterManager::GetInstance().DeleteAgedEntry(); +#endif } -void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, +void DeviceManagerServiceListener::OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - + DmDeviceInfo deviceInfo = info; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, deviceInfo); +#endif DmDeviceBasicInfo devBasicInfo; - ConvertDeviceInfoToDeviceBasicInfo(pkgName, info, devBasicInfo); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, deviceInfo, devBasicInfo); pReq->SetDeviceBasicInfo(devBasicInfo); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId(subscribeId); - pReq->SetDeviceInfo(info); + pReq->SetDeviceInfo(deviceInfo); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } -void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, - DmDeviceBasicInfo &info) -{ - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::string udIdHash = CalcDeviceId(pkgName, info.deviceId); - if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udIdHash.c_str(), udIdHash.length()) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); - } - pReq->SetPkgName(pkgName); - pReq->SetSubscribeId(subscribeId); - pReq->SetDeviceBasicInfo(info); - ipcServerListener_.SendRequest(SERVER_DEVICE_DISCOVERY, pReq, pRsp); -} - -void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, +void DeviceManagerServiceListener::OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) { LOGI("DeviceManagerServiceListener::OnDiscoveryFailed"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId(subscribeId); pReq->SetResult(failedReason); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +void DeviceManagerServiceListener::OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) { LOGI("DeviceManagerServiceListener::OnDiscoverySuccess"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId((uint16_t)subscribeId); pReq->SetResult(DM_OK); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } @@ -251,7 +279,7 @@ void DeviceManagerServiceListener::OnPublishResult(const std::string &pkgName, i ipcServerListener_.SendRequest(SERVER_PUBLISH_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, +void DeviceManagerServiceListener::OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) { std::shared_ptr pReq = std::make_shared(); @@ -259,40 +287,48 @@ void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, cons if (status < STATUS_DM_AUTH_FINISH && status > STATUS_DM_AUTH_DEFAULT) { status = STATUS_DM_AUTH_DEFAULT; } - - pReq->SetPkgName(pkgName); pReq->SetDeviceId(deviceId); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, deviceId, deviceIdTemp) == DM_OK) { + pReq->SetDeviceId(deviceIdTemp); + } +#endif + pReq->SetPkgName(processInfo.pkgName); pReq->SetToken(token); pReq->SetStatus(status); pReq->SetReason(reason); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnUiCall(std::string &pkgName, std::string ¶mJson) +void DeviceManagerServiceListener::OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) { LOGI("OnUiCall in"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetJsonParam(paramJson); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_FA_NOTIFY, pReq, pRsp); } -void DeviceManagerServiceListener::OnCredentialResult(const std::string &pkgName, int32_t action, +void DeviceManagerServiceListener::OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) { - LOGI("call OnCredentialResult for %{public}s, action %{public}d", pkgName.c_str(), action); + LOGI("call OnCredentialResult for %{public}s, action %{public}d", processInfo.pkgName.c_str(), action); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetCredentialAction(action); pReq->SetCredentialResult(resultInfo); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREDENTIAL_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) { std::shared_ptr pReq = std::make_shared(); @@ -300,160 +336,543 @@ void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, cons if (status < STATUS_DM_AUTH_FINISH && status > STATUS_DM_AUTH_DEFAULT) { status = STATUS_DM_AUTH_DEFAULT; } - - pReq->SetPkgName(pkgName); - pReq->SetPeerTargetId(targetId); + PeerTargetId returnTargetId = targetId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + DmKVValue kvValue; + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { + returnTargetId.deviceId = deviceIdTemp; + } +#endif + pReq->SetPkgName(processInfo.pkgName); + pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetStatus(status); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(BIND_TARGET_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - - pReq->SetPkgName(pkgName); - pReq->SetPeerTargetId(targetId); + PeerTargetId returnTargetId = targetId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + DmKVValue kvValue; + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { + returnTargetId.deviceId = deviceIdTemp; + } +#endif + pReq->SetPkgName(processInfo.pkgName); + pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(UNBIND_TARGET_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::RegisterDmListener(const std::string &pkgName, const std::string &appId) -{ - std::lock_guard autoLock(dmListenerMapLock_); - dmListenerMap_[pkgName] = appId; -} - -void DeviceManagerServiceListener::UnRegisterDmListener(const std::string &pkgName) -{ - std::lock_guard autoLock(dmListenerMapLock_); - dmListenerMap_.erase(pkgName); -} - -void DeviceManagerServiceListener::DeleteDeviceIdFromMap(const std::string &deviceId, const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - std::map &udidMap = udidHashMap_[pkgName]; - auto iter = udidMap.find(deviceId); - if (iter == udidMap.end()) { - return; - } - udidMap.erase(deviceId); -} -void DeviceManagerServiceListener::SetUdidHashMap(const std::string &udidHash, const std::string &deviceId, - const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - udidHashMap_[pkgName][deviceId] = udidHash; -} - -std::string DeviceManagerServiceListener::GetDeviceId(const std::string &udidHash, const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - std::map &udidMap = udidHashMap_[pkgName]; - for (auto iter = udidMap.begin(); iter != udidMap.end(); iter++) { - if (udidHash == iter->second) { - return iter->first; - } - } - return ""; -} - -std::string DeviceManagerServiceListener::GetUdidHash(const std::string &deviceId, const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - return udidHashMap_[pkgName].count(deviceId) > 0 ? udidHashMap_[pkgName][deviceId] : ""; -} - -std::string DeviceManagerServiceListener::GetAppId(const std::string &pkgName) -{ - std::lock_guard autoLock(dmListenerMapLock_); - return dmListenerMap_.count(pkgName) > 0 ? dmListenerMap_[pkgName] : ""; -} - -std::string DeviceManagerServiceListener::CalcDeviceId(const std::string &pkgName, const std::string &udidHash) -{ - std::string appId = GetAppId(pkgName); - LOGI("CalcDeviceId, appId : %{public}s, udidHash : %{public}s.", GetAnonyString(appId).c_str(), - GetAnonyString(udidHash).c_str()); - if (appId.empty()) { - return udidHash; - } - std::string deviceId = GetDeviceId(udidHash, pkgName); - if (deviceId.empty()) { - deviceId = Crypto::Sha256(appId + udidHash); - SetUdidHashMap(udidHash, deviceId, pkgName); - return deviceId; - } - return deviceId; -} - -void DeviceManagerServiceListener::OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, +void DeviceManagerServiceListener::OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) { - LOGI("DeviceManagerServiceListener::OnPinHolderCreate : %{public}s", pkgName.c_str()); + LOGI("DeviceManagerServiceListener::OnPinHolderCreate : %{public}s", processInfo.pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetDeviceId(deviceId); pReq->SetPinType(pinType); pReq->SetPayload(payload); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREATE_PIN_HOLDER, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, +void DeviceManagerServiceListener::OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) { - LOGI("DeviceManagerServiceListener::OnPinHolderDestroy : %{public}s", pkgName.c_str()); + LOGI("DeviceManagerServiceListener::OnPinHolderDestroy : %{public}s", processInfo.pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPinType(pinType); pReq->SetPayload(payload); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DESTROY_PIN_HOLDER, pReq, pRsp); } -void DeviceManagerServiceListener::OnCreateResult(const std::string &pkgName, int32_t result) +void DeviceManagerServiceListener::OnCreateResult(const ProcessInfo &processInfo, int32_t result) { LOGI("DeviceManagerServiceListener::OnCreateResult : %{public}d", result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetResult(result); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREATE_PIN_HOLDER_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnDestroyResult(const std::string &pkgName, int32_t result) +void DeviceManagerServiceListener::OnDestroyResult(const ProcessInfo &processInfo, int32_t result) { LOGI("DeviceManagerServiceListener::OnDestroyResult : %{public}d", result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetResult(result); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DESTROY_PIN_HOLDER_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, +void DeviceManagerServiceListener::OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) { LOGI("OnPinHolderEvent pkgName: %{public}s, event: %{public}d, result: %{public}d", - pkgName.c_str(), event, result); + processInfo.pkgName.c_str(), event, result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPinHolderEvent(event); pReq->SetResult(result); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_ON_PIN_HOLDER_EVENT, pReq, pRsp); } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoyAndSave(const std::string &pkgName, DmDeviceInfo &deviceInfo) +{ + LOGD("pkgName %{public}s.", pkgName.c_str()); + std::string appId = ""; + if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + LOGD("GetAppIdByPkgName failed"); + return ERR_DM_FAILED; + } + DmKVValue kvValue; + int32_t ret = Crypto::ConvertUdidHashToAnoyAndSave(appId, std::string(deviceInfo.deviceId), kvValue); + if (ret != DM_OK) { + return ERR_DM_FAILED; + } + if (memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { + LOGE("ConvertUdidHashToAnoyAndSave memset failed."); + return ERR_DM_FAILED; + } + if (memcpy_s(deviceInfo.deviceId, sizeof(deviceInfo.deviceId), kvValue.anoyDeviceId.c_str(), + std::min(sizeof(deviceInfo.deviceId), kvValue.anoyDeviceId.length())) != DM_OK) { + LOGE("copy deviceId data failed."); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, + const std::string &udidHash, std::string &anoyDeviceId) +{ + LOGI("pkgName %{public}s, udidHash %{public}s.", pkgName.c_str(), GetAnonyString(udidHash).c_str()); + std::string appId = ""; + if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + LOGD("GetAppIdByPkgName failed"); + return ERR_DM_FAILED; + } + DmKVValue kvValue; + int32_t ret = Crypto::ConvertUdidHashToAnoyDeviceId(appId, udidHash, kvValue); + if (ret == DM_OK) { + anoyDeviceId = kvValue.anoyDeviceId; + } + return ret; +} +#endif + +void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, const std::string &uuid, + DmAuthForm authForm) +{ + LOGI("udid %{public}s, authForm %{public}d, uuid %{public}s.", GetAnonyString(udid).c_str(), + authForm, GetAnonyString(uuid).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetFirstForegroundUserId(); +#endif + std::vector processInfoVec = GetNotifyProcessInfoByUserId(userId, + DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE); + for (const auto &item : processInfoVec) { + pReq->SetPkgName(item.pkgName); + pReq->SetUdid(udid); + pReq->SetUuid(uuid); + pReq->SetAuthForm(authForm); + pReq->SetProcessInfo(item); + ipcServerListener_.SendRequest(REMOTE_DEVICE_TRUST_CHANGE, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::SetDeviceScreenInfo(std::shared_ptr pReq, + const ProcessInfo &processInfo, const DmDeviceInfo &deviceInfo) +{ + LOGI("In"); + pReq->SetPkgName(processInfo.pkgName); + pReq->SetProcessInfo(processInfo); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string appId = ""; + if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) { + pReq->SetDeviceInfo(deviceInfo); + return; + } + DmDeviceInfo dmDeviceInfo = deviceInfo; + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); + pReq->SetDeviceInfo(dmDeviceInfo); + return; +#endif + pReq->SetDeviceInfo(deviceInfo); +} + +void DeviceManagerServiceListener::OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) +{ + LOGI("In, pkgName = %{public}s", processInfo.pkgName.c_str()); + if (processInfo.pkgName == std::string(DM_PKG_NAME)) { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetFirstForegroundUserId(); +#endif + std::vector processInfoVec = + GetNotifyProcessInfoByUserId(userId, DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE); + for (const auto &item : processInfoVec) { + SetDeviceScreenInfo(pReq, item, devInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); + } + } else { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + std::vector processInfoVec = + GetWhiteListSAProcessInfo(DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE); + processInfoVec.push_back(processInfo); + for (const auto &item : processInfoVec) { + SetDeviceScreenInfo(pReq, item, devInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); + } + } +} + +void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) +{ + LOGI("udidHash: %{public}s.", GetAnonyString(info.deviceId).c_str()); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + for (auto item = alreadyOnlinePkgName_.begin(); item != alreadyOnlinePkgName_.end();) { + if (std::string(item->second.deviceId) == std::string(info.deviceId)) { + item = alreadyOnlinePkgName_.erase(item); + } else { + ++item; + } + } + } +} + +void DeviceManagerServiceListener::OnCredentialAuthStatus(const ProcessInfo &processInfo, + const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) +{ + LOGI("In, pkgName = %{public}s", processInfo.pkgName.c_str()); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetFirstForegroundUserId(); +#endif + std::vector processInfoVec = + GetNotifyProcessInfoByUserId(userId, DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY); + for (const auto &item : processInfoVec) { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + pReq->SetDeviceList(deviceList); + pReq->SetDeviceTypeId(deviceTypeId); + pReq->SetErrCode(errcode); + pReq->SetPkgName(item.pkgName); + pReq->SetProcessInfo(item); + ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) +{ + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + it = alreadyOnlinePkgName_.erase(it); + } else { + ++it; + } + } +} + +void DeviceManagerServiceListener::OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, + int32_t result, int32_t status, std::string content) +{ + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + if (status < STATUS_DM_AUTH_FINISH && status > STATUS_DM_AUTH_DEFAULT) { + status = STATUS_DM_AUTH_DEFAULT; + } + PeerTargetId returnTargetId = targetId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + DmKVValue kvValue; + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { + returnTargetId.deviceId = deviceIdTemp; + } +#endif + pReq->SetPkgName(processInfo.pkgName); + std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); + ProcessInfo processInfoTemp; + for (auto item : processInfos) { + if (item.pkgName == processInfo.pkgName) { + processInfoTemp = item; + } + } + if (processInfoTemp.pkgName.empty()) { + LOGI("not register listener"); + return; + } + pReq->SetProcessInfo(processInfoTemp); + pReq->SetPeerTargetId(returnTargetId); + pReq->SetResult(result); + pReq->SetStatus(status); + pReq->SetContent(content); + ipcServerListener_.SendRequest(SINK_BIND_TARGET_RESULT, pReq, pRsp); +} + +std::vector DeviceManagerServiceListener::GetWhiteListSAProcessInfo( + DmCommonNotifyEvent dmCommonNotifyEvent) +{ + if (!IsDmCommonNotifyEventValid(dmCommonNotifyEvent)) { + LOGE("Invalid dmCommonNotifyEvent: %{public}d.", dmCommonNotifyEvent); + return {}; + } + std::set notifyProcessInfos; + DeviceManagerServiceNotify::GetInstance().GetCallBack(dmCommonNotifyEvent, notifyProcessInfos); + if (notifyProcessInfos.size() == 0) { + LOGE("callback not exist dmCommonNotifyEvent: %{public}d", dmCommonNotifyEvent); + return {}; + } + std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); + std::vector processInfos; + for (const auto &it : notifyPkgnames) { + ProcessInfo processInfo; + processInfo.pkgName = it; + processInfo.userId = 0; + if (notifyProcessInfos.find(processInfo) == notifyProcessInfos.end()) { + continue; + } + processInfos.push_back(processInfo); + } + return processInfos; +} + +std::vector DeviceManagerServiceListener::GetNotifyProcessInfoByUserId(int32_t userId, + DmCommonNotifyEvent dmCommonNotifyEvent) +{ + if (!IsDmCommonNotifyEventValid(dmCommonNotifyEvent)) { + LOGE("Invalid dmCommonNotifyEvent: %{public}d.", dmCommonNotifyEvent); + return {}; + } + std::set notifyProcessInfos; + DeviceManagerServiceNotify::GetInstance().GetCallBack(dmCommonNotifyEvent, notifyProcessInfos); + if (notifyProcessInfos.size() == 0) { + LOGE("callback not exist dmCommonNotifyEvent: %{public}d", dmCommonNotifyEvent); + return {}; + } + std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); + std::set systemSA = ipcServerListener_.GetSystemSA(); + std::vector processInfosTemp; + for (auto item : processInfos) { + if (systemSA.find(item.pkgName) != systemSA.end()) { + item.userId = 0; + if (notifyProcessInfos.find(item) == notifyProcessInfos.end()) { + continue; + } + processInfosTemp.push_back(item); + } else if (item.userId == userId) { + if (notifyProcessInfos.find(item) == notifyProcessInfos.end()) { + continue; + } + processInfosTemp.push_back(item); + } + } + return processInfosTemp; +} + +ProcessInfo DeviceManagerServiceListener::DealBindProcessInfo(const ProcessInfo &processInfo) +{ + std::set systemSA = ipcServerListener_.GetSystemSA(); + if (systemSA.find(processInfo.pkgName) == systemSA.end()) { + return processInfo; + } + ProcessInfo bindProcessInfo = processInfo; + bindProcessInfo.userId = 0; + return bindProcessInfo; +} + +void DeviceManagerServiceListener::ProcessDeviceOnline(const std::vector &procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); + DmDeviceState notifyState = state; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + notifyState = DmDeviceState::DEVICE_INFO_CHANGED; + } else { + alreadyOnlinePkgName_[notifyPkgName] = info; + } + } + SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessDeviceOffline(const std::vector &procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyPkgName); + } else { + continue; + } + } + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessDeviceInfoChange(const std::vector &procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessAppOnline(const std::vector &procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); + DmDeviceState notifyState = state; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + notifyState = DmDeviceState::DEVICE_INFO_CHANGED; + } else { + alreadyOnlinePkgName_[notifyPkgName] = info; + } + } + SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessAppOffline(const std::vector &procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { + for (const auto &it : procInfoVec) { + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyPkgName); + } else { + continue; + } + } + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } + } else { + std::string notifyPkgName = processInfo.pkgName + "#" + std::to_string(processInfo.userId) + "#" + + std::string(info.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyPkgName); + } else { + return; + } + } + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::OnProcessRemove(const ProcessInfo &processInfo) +{ + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + std::string notifyPkgName = processInfo.pkgName + "#" + std::to_string(processInfo.userId); + for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { + if (it->first.find(notifyPkgName) != std::string::npos) { + it = alreadyOnlinePkgName_.erase(it); + } else { + ++it; + } + } +} + +void DeviceManagerServiceListener::OnDevStateCallbackAdd(const ProcessInfo &processInfo, + const std::vector &deviceList) +{ + for (auto item : deviceList) { + std::string notifyPkgName = processInfo.pkgName + "#" + std::to_string(processInfo.userId) + "#" + + std::string(item.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + continue; + } + alreadyOnlinePkgName_[notifyPkgName] = item; + } + DmDeviceBasicInfo deviceBasicInfo; + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, item, deviceBasicInfo); + SetDeviceInfo(pReq, processInfo, DmDeviceState::DEVICE_STATE_ONLINE, item, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f0dfa3fc1fdb615183c74bb137c388043473caf --- /dev/null +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "account_boot_listener.h" + +#include + +#include "common_event_support.h" +#include "device_manager_service.h" +#include "parameter.h" + +#include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif + +namespace OHOS { +namespace DistributedHardware { +namespace { + const char * const BOOTEVENT_ACCOUNT_READY = "bootevent.account.ready"; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + const char * const ACCOUNT_BOOT_EVENT = "account_boot_event"; +#endif +} + +std::mutex AccountBootListener::depSaStatelock_; + +static void AccountBootCb(const char *key, const char *value, void *context) +{ + if (key == nullptr || value == nullptr || context == nullptr) { + LOGE("key or value or context is null, param is error!"); + return; + } + if (strcmp(key, BOOTEVENT_ACCOUNT_READY) != 0 || strcmp(value, "true") != 0) { + return; + } + AccountBootListener *accountBootListener = static_cast(context); + + if (accountBootListener == nullptr) { + LOGE("accountBootListener is null"); + return; + } + LOGI("Trigger"); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { accountBootListener->DoAccountBootProc(); }); +#else + std::thread dealThread([=]() { + accountBootListener->DoAccountBootProc(); + }); + int32_t ret = pthread_setname_np(dealThread.native_handle(), ACCOUNT_BOOT_EVENT); + if (ret != DM_OK) { + LOGE("dealThread setname failed."); + } + dealThread.detach(); +#endif +} + +AccountBootListener::AccountBootListener() : isRegAccountBootCb_(false), + localDeviceMgr_(std::make_shared()), isDmSaReady_(false), isDataShareReady_(false), + dataShareCommonEventManager_(std::make_shared()) +{ + LOGI("Ctor AccountBootListener"); +} + +AccountBootListener::~AccountBootListener() +{ + LOGI("Dtor AccountBootListener"); +} + +void AccountBootListener::RegisterAccountBootCb() +{ + if (isRegAccountBootCb_) { + return; + } + LOGI("start"); + int32_t ret = WatchParameter(BOOTEVENT_ACCOUNT_READY, AccountBootCb, this); + if (ret != 0) { + LOGE("watch account boot event fail"); + } + isRegAccountBootCb_ = true; +} + +void AccountBootListener::DoAccountBootProc() +{ + LOGI("start"); + if (localDeviceMgr_ == nullptr) { + LOGE("localDeviceMgr_ is null"); + return; + } + localDeviceMgr_->RegisterDeviceNameChangeCb(); + localDeviceMgr_->RegisterDisplayNameChangeCb(); + localDeviceMgr_->QueryLocalDisplayName(); + localDeviceMgr_->QueryLocalDeviceName(); +} + +void AccountBootListener::SetSaTriggerFlag(SaTriggerFlag triggerFlag) +{ + LOGI("start"); + std::lock_guard lock(depSaStatelock_); + switch (triggerFlag) { + case SaTriggerFlag::DM_SA_READY: + isDmSaReady_ = true; + LOGI("DM SA ready!"); + break; + case SaTriggerFlag::DATA_SHARE_SA_REDDY: + LOGI("DATA SHARE SA ready!"); + this->InitDataShareEvent(); + break; + default: + break; + } + LOGI("isDmSaReady_: %{public}d, isDataShareReady_: %{public}d", + std::atomic_load(&isDmSaReady_), std::atomic_load(&isDataShareReady_)); + if (isDmSaReady_ && isDataShareReady_) { + LOGI("dm and data_share is ready!"); + this->RegisterAccountBootCb(); + } +} + +void AccountBootListener::InitDataShareEvent() +{ + LOGI("Start"); + if (dataShareCommonEventManager_ == nullptr) { + dataShareCommonEventManager_ = std::make_shared(); + } + DataShareEventCallback callback = [=]() { + this->DataShareCallback(); + }; + std::vector dataShareEventVec; + dataShareEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY); + if (dataShareCommonEventManager_->SubscribeDataShareCommonEvent(dataShareEventVec, callback)) { + LOGI("Success"); + } + return; +} + +void AccountBootListener::DataShareCallback() +{ + LOGI("Start"); + std::lock_guard lock(depSaStatelock_); + isDataShareReady_ = true; + LOGI("isDmSaReady_: %{public}d, isDataShareReady_: %{public}d", + std::atomic_load(&isDmSaReady_), std::atomic_load(&isDataShareReady_)); + if (isDmSaReady_ && isDataShareReady_) { + LOGI("dm and data_share is ready!"); + this->RegisterAccountBootCb(); + } +} + +std::string AccountBootListener::GetLocalDisplayName() const +{ + if (localDeviceMgr_ == nullptr) { + LOGE("logcalDeviceMgr_ is null"); + return ""; + } + return localDeviceMgr_->GetLocalDisplayName(); +} + +std::string AccountBootListener::GetLocalDeviceName() const +{ + if (localDeviceMgr_ == nullptr) { + LOGE("logcalDeviceMgr_ is null"); + return ""; + } + return localDeviceMgr_->GetLocalDeviceName(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9564ee56fa2eaad93db32abcc6132be0b6c469ce --- /dev/null +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -0,0 +1,301 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "local_device_name_mgr.h" + +#include "data_ability_observer_stub.h" +#include "datashare_helper.h" +#include "datashare_predicates.h" +#include "datashare_result_set.h" +#include "ohos_account_kits.h" +#include "os_account_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "uri.h" + +#include "device_manager_service.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "settings_data_event_monitor.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const std::string SETTINGS_DATA_BASE_URI = + "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; + const std::string SETTINGS_DATA_SECURE_URI = + "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE_"; + constexpr const char *SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility"; + constexpr const char *SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD"; + constexpr const char *SETTINGS_DATA_FIELD_VALUE = "VALUE"; + constexpr const char *PREDICATES_STRING = "settings.general.device_name"; + constexpr const char *USER_DEFINED_STRING = "settings.general.user_defined_device_name"; + constexpr const char *DISPLAY_DEVICE_NAME_STRING = "settings.general.display_device_name"; +} + +std::mutex LocalDeviceNameMgr::devNameMtx_; + +LocalDeviceNameMgr::LocalDeviceNameMgr() : localDeviceName_(""), localDisplayName_("") +{ + LOGI("Ctor LocalDeviceNameMgr"); +} + +LocalDeviceNameMgr::~LocalDeviceNameMgr() +{ + std::lock_guard lock(devNameMtx_); + localDeviceName_ = ""; + localDisplayName_ = ""; + LOGI("Dtor LocalDeviceNameMgr"); +} + +std::shared_ptr LocalDeviceNameMgr::GetDataShareHelper() +{ + sptr saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saManager == nullptr) { + LOGE("saManager NULL"); + return nullptr; + } + + sptr remoteObject = saManager->GetSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + if (remoteObject == nullptr) { + LOGE("remoteObject NULL"); + return nullptr; + } + return DataShare::DataShareHelper::Creator(remoteObject, SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI); +} + +int32_t LocalDeviceNameMgr::GetDeviceNameFromDataShareHelper( + std::shared_ptr dataShareHelper, std::shared_ptr uri, + const char *key, std::string &deviceName) +{ + if (dataShareHelper == nullptr || uri == nullptr || key == nullptr) { + LOGE("dataShareHelper or uri or key is null, param is error!"); + return ERR_DM_FAILED; + } + int32_t numRows = 0; + std::string val; + std::vector columns; + columns.emplace_back(SETTINGS_DATA_FIELD_VALUE); + DataShare::DataSharePredicates predicates; + predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, key); + + auto resultSet = dataShareHelper->Query(*uri, predicates, columns); + if (resultSet == nullptr) { + LOGE("query fail."); + return ERR_DM_FAILED; + } + resultSet->GetRowCount(numRows); + if (numRows <= 0) { + LOGE("row zero."); + resultSet->Close(); + return ERR_DM_FAILED; + } + + int columnIndex; + resultSet->GoToFirstRow(); + resultSet->GetColumnIndex(SETTINGS_DATA_FIELD_VALUE, columnIndex); + if (resultSet->GetString(columnIndex, val) != DM_OK) { + LOGE("GetString val fail"); + resultSet->Close(); + return ERR_DM_FAILED; + } + deviceName = val; + LOGI("deviceName=%{public}s.", deviceName.c_str()); + resultSet->Close(); + return DM_OK; +} + +int32_t LocalDeviceNameMgr::GetDefaultDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName) +{ + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null, param is error!"); + return ERR_DM_FAILED; + } + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); + LOGI("get default deviceName"); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, PREDICATES_STRING, deviceName); +} + +int32_t LocalDeviceNameMgr::GetUserDefinedDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName) +{ + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null, param is error!"); + return ERR_DM_FAILED; + } + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + LOGE("osAccountId acquire fail!"); + return ERR_DM_FAILED; + } + std::string accountIdStr = std::to_string(osAccountId); + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + + USER_DEFINED_STRING); + LOGI("get user defined deviceName, accountId=%{public}s", accountIdStr.c_str()); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, USER_DEFINED_STRING, deviceName); +} + +int32_t LocalDeviceNameMgr::GetDisplayDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName) +{ + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null, param is error!"); + return ERR_DM_FAILED; + } + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + LOGE("osAccountId acquire fail!"); + return ERR_DM_FAILED; + } + std::string accountIdStr = std::to_string(osAccountId); + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + + DISPLAY_DEVICE_NAME_STRING); + LOGI("get user defined deviceName, accountId=%{public}s", accountIdStr.c_str()); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, DISPLAY_DEVICE_NAME_STRING, deviceName); +} + +int32_t LocalDeviceNameMgr::GetActiveOsAccountIds() +{ + std::vector accountId; + int32_t ret = OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountId); + if (ret != DM_OK || accountId.empty()) { + LOGE("QueryActiveOsAccountIds failed"); + return ERR_DM_FAILED; + } + LOGI("account id=%{public}d", accountId[0]); + return accountId[0]; +} + +int32_t LocalDeviceNameMgr::QueryLocalDeviceName() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return ERR_DM_FAILED; + } + std::string localDeviceName = ""; + int32_t ret = GetUserDefinedDeviceName(dataShareHelper, localDeviceName); + if (ret == DM_OK && !localDeviceName.empty()) { + std::lock_guard lock(devNameMtx_); + localDeviceName_ = localDeviceName; + dataShareHelper->Release(); + LOGI("get user defined deviceName=%{public}s", localDeviceName.c_str()); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName_, localDisplayName_); + return DM_OK; + } + ret = GetDefaultDeviceName(dataShareHelper, localDeviceName); + if (ret != DM_OK || localDeviceName.empty()) { + LOGE("get default deviceName failed"); + return ERR_DM_FAILED; + } + std::lock_guard lock(devNameMtx_); + localDeviceName_ = localDeviceName; + dataShareHelper->Release(); + LOGI("get default deviceName=%{public}s", localDeviceName.c_str()); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName_, localDisplayName_); + return DM_OK; +} + +void LocalDeviceNameMgr::RegisterDeviceNameChangeCb() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return; + } + + auto uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); + sptr settingDataObserver = + sptr(new SettingsDataEventMonitor(shared_from_this(), + SettingsDataMonitorType::USER_DEFINED_DEVICE_NAME_MONITOR)); + dataShareHelper->RegisterObserver(*uri, settingDataObserver); + + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + LOGE("Get OsAccountId error"); + return; + } + std::string accountIdStr = std::to_string(osAccountId); + uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + + "?Proxy=true&key=" + USER_DEFINED_STRING); + + dataShareHelper->RegisterObserver(*uri, settingDataObserver); + dataShareHelper->Release(); + LOGI("register device name change cb success"); +} + +int32_t LocalDeviceNameMgr::QueryLocalDisplayName() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return ERR_DM_FAILED; + } + std::string localDisplayName = ""; + int32_t ret = GetDisplayDeviceName(dataShareHelper, localDisplayName); + if (ret != DM_OK || localDisplayName.empty()) { + LOGE("get display device name failed"); + return ERR_DM_FAILED; + } + std::lock_guard lock(devNameMtx_); + localDisplayName_ = localDisplayName; + dataShareHelper->Release(); + LOGI("get display deviceName=%{public}s", localDisplayName.c_str()); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName_, localDisplayName_); + return DM_OK; +} + +void LocalDeviceNameMgr::RegisterDisplayNameChangeCb() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return; + } + + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + LOGE("Get OsAccountId error"); + return; + } + std::string accountIdStr = std::to_string(osAccountId); + auto uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + + "?Proxy=true&key=" + DISPLAY_DEVICE_NAME_STRING); + sptr settingDataObserver = + sptr(new SettingsDataEventMonitor(shared_from_this(), + SettingsDataMonitorType::DISPLAY_DEVICE_NAME_MONITOR)); + dataShareHelper->RegisterObserver(*uri, settingDataObserver); + dataShareHelper->Release(); + LOGI("register display device name change cb success"); +} + +std::string LocalDeviceNameMgr::GetLocalDisplayName() const +{ + std::lock_guard lock(devNameMtx_); + return localDisplayName_; +} + +std::string LocalDeviceNameMgr::GetLocalDeviceName() const +{ + std::lock_guard lock(devNameMtx_); + return localDeviceName_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/settings_data_event_monitor.cpp b/services/service/src/devicenamemgr/settings_data_event_monitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..421acfc7bf4f39a444fda0ad5b8fb988406f6fd4 --- /dev/null +++ b/services/service/src/devicenamemgr/settings_data_event_monitor.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "settings_data_event_monitor.h" + +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +SettingsDataEventMonitor::SettingsDataEventMonitor(std::shared_ptr localDeviceNameMgr, + SettingsDataMonitorType monitorType) + : localDeviceNameMgrWPtr_(localDeviceNameMgr), monitorType_(monitorType) +{ + LOGI("Ctor SettingsDataEventMonitor, monitorType: %{public}d", (int32_t)monitorType); +} + +void SettingsDataEventMonitor::OnChange() +{ + if (localDeviceNameMgrWPtr_.expired()) { + LOGE("localDeviceNameMgrWPtr_ expired"); + return; + } + LOGI("Settings OnChange type: %{public}d", (int32_t)monitorType_); + std::shared_ptr localDevNameSPtr = localDeviceNameMgrWPtr_.lock(); + if (localDevNameSPtr == nullptr) { + LOGE("localDevNameSPtr is null!"); + return; + } + switch (monitorType_) { + case SettingsDataMonitorType::USER_DEFINED_DEVICE_NAME_MONITOR: + localDevNameSPtr->QueryLocalDeviceName(); + break; + case SettingsDataMonitorType::DISPLAY_DEVICE_NAME_MONITOR: + localDevNameSPtr->QueryLocalDisplayName(); + break; + default: + LOGE("unknwon monitor type"); + break; + } +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/discovery/discovery_filter.cpp b/services/service/src/discovery/discovery_filter.cpp index 00b5dc4eca789b923f951a421668b4796071db57..bf835ccbfd7a2e2e88ba5016fe6a0a5385aaa2a7 100644 --- a/services/service/src/discovery/discovery_filter.cpp +++ b/services/service/src/discovery/discovery_filter.cpp @@ -27,7 +27,7 @@ const std::string FILTERS_TYPE_OR = "OR"; const std::string FILTERS_TYPE_AND = "AND"; const int32_t DM_OK = 0; const int32_t ERR_DM_INPUT_PARA_INVALID = 96929749; -enum DmDiscoveryDeviceFilter { +enum class DmDiscoveryDeviceFilter : int32_t { DM_INVALID_DEVICE = 0, DM_VALID_DEVICE = 1, DM_ALL_DEVICE = 2 @@ -115,7 +115,7 @@ int32_t DeviceFilterOption::TransformToFilter(const std::string &filterOptions) filterOp_ = FILTERS_TYPE_OR; DeviceFilters deviceFilters; deviceFilters.type = "credible"; - deviceFilters.value = DM_INVALID_DEVICE; + deviceFilters.value = static_cast(DmDiscoveryDeviceFilter::DM_INVALID_DEVICE); filters_.push_back(deviceFilters); return DM_OK; } @@ -129,7 +129,7 @@ int32_t DeviceFilterOption::TransformFilterOption(const std::string &filterOptio filterOp_ = FILTERS_TYPE_OR; DeviceFilters deviceFilters; deviceFilters.type = "credible"; - deviceFilters.value = DM_INVALID_DEVICE; + deviceFilters.value = static_cast(DmDiscoveryDeviceFilter::DM_INVALID_DEVICE); filters_.push_back(deviceFilters); return DM_OK; } @@ -138,13 +138,13 @@ int32_t DeviceFilterOption::TransformFilterOption(const std::string &filterOptio bool DiscoveryFilter::FilterByDeviceState(int32_t value, bool isActive) { - if (value == DM_INVALID_DEVICE) { + if (value == static_cast(DmDiscoveryDeviceFilter::DM_INVALID_DEVICE)) { return !isActive; } - if (value == DM_VALID_DEVICE) { + if (value == static_cast(DmDiscoveryDeviceFilter::DM_VALID_DEVICE)) { return isActive; } - return (value == DM_ALL_DEVICE); + return (value == static_cast(DmDiscoveryDeviceFilter::DM_ALL_DEVICE)); } bool DiscoveryFilter::FilterByRange(int32_t value, int32_t range) diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index c283cccaf7059eedc06f76bd4521f107b0d3e0ce..a68fe4667a39fe5c0b51a3e46dd274597e8c1eb1 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -23,6 +23,9 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -30,6 +33,7 @@ const int32_t DISCOVERY_TIMEOUT = 120; const uint16_t DM_INVALID_FLAG_ID = 0; constexpr const char* LNN_DISC_CAPABILITY = "capability"; const std::string TYPE_MINE = "findDeviceMode"; +const int32_t DECIMALISM = 10; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) static std::mutex comDependencyLoadLock; @@ -61,10 +65,10 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = AddMultiUserIdentify(pkgName); DmSubscribeInfo dmSubInfo; dmSubInfo.subscribeId = DM_INVALID_FLAG_ID; dmSubInfo.mode = DmDiscoverMode::DM_DISCOVER_MODE_PASSIVE; - dmSubInfo.medium = DmExchangeMedium::DM_BLE; dmSubInfo.freq = DmExchangeFreq::DM_LOW; dmSubInfo.isSameAccount = false; dmSubInfo.isWakeRemote = false; @@ -72,7 +76,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGE("capability copy err."); return ERR_DM_ENABLE_DISCOVERY_LISTENER_FAILED; } - + UpdateInfoFreq(discoverParam, dmSubInfo); if (discoverParam.find(PARAM_KEY_META_TYPE) != discoverParam.end()) { std::string metaType = discoverParam.find(PARAM_KEY_META_TYPE)->second; LOGI("EnableDiscoveryListener, input MetaType = %{public}s in discoverParam map.", metaType.c_str()); @@ -81,7 +85,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, dmSubInfo.subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); { std::lock_guard autoLock(subIdMapLocks_); - pkgName2SubIdMap_[pkgName] = dmSubInfo.subscribeId; + pkgName2SubIdMap_[pkgNameTemp] = dmSubInfo.subscribeId; } } if (discoverParam.find(PARAM_KEY_DISC_CAPABILITY) != discoverParam.end()) { @@ -94,15 +98,15 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGI("EnableDiscoveryListener capability = %{public}s,", std::string(dmSubInfo.capability).c_str()); { std::lock_guard capLock(capabilityMapLocks_); - capabilityMap_[pkgName] = std::string(dmSubInfo.capability); + capabilityMap_[pkgNameTemp] = std::string(dmSubInfo.capability); } - + UpdateInfoMedium(discoverParam, dmSubInfo); int32_t ret = softbusListener_->RefreshSoftbusLNN(DM_PKG_NAME, dmSubInfo, LNN_DISC_CAPABILITY); if (ret != DM_OK) { LOGE("EnableDiscoveryListener failed, softbus refresh lnn ret: %{public}d.", ret); return ret; } - softbusListener_->RegisterSoftbusLnnOpsCbk(pkgName, shared_from_this()); + softbusListener_->RegisterSoftbusLnnOpsCbk(pkgNameTemp, shared_from_this()); return DM_OK; } @@ -114,7 +118,7 @@ int32_t DiscoveryManager::DisableDiscoveryListener(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - + std::string pkgNameTemp = RemoveMultiUserIdentify(pkgName); if (extraParam.find(PARAM_KEY_META_TYPE) != extraParam.end()) { LOGI("DisableDiscoveryListener, input MetaType = %{public}s", (extraParam.find(PARAM_KEY_META_TYPE)->second).c_str()); @@ -124,16 +128,16 @@ int32_t DiscoveryManager::DisableDiscoveryListener(const std::string &pkgName, subscribeId = std::atoi((extraParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); { std::lock_guard autoLock(subIdMapLocks_); - pkgName2SubIdMap_.erase(pkgName); + pkgName2SubIdMap_.erase(pkgNameTemp); } } { std::lock_guard capLock(capabilityMapLocks_); - if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { - capabilityMap_.erase(pkgName); + if (capabilityMap_.find(pkgNameTemp) != capabilityMap_.end()) { + capabilityMap_.erase(pkgNameTemp); } } - softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); return softbusListener_->StopRefreshSoftbusLNN(subscribeId); } @@ -145,9 +149,10 @@ int32_t DiscoveryManager::StartDiscovering(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = AddMultiUserIdentify(pkgName); DmSubscribeInfo dmSubInfo; ConfigDiscParam(discoverParam, &dmSubInfo); - if (HandleDiscoveryQueue(pkgName, dmSubInfo.subscribeId, filterOptions) != DM_OK) { + if (HandleDiscoveryQueue(pkgNameTemp, dmSubInfo.subscribeId, filterOptions) != DM_OK) { return ERR_DM_DISCOVERY_REPEATED; } @@ -157,17 +162,17 @@ int32_t DiscoveryManager::StartDiscovering(const std::string &pkgName, isStandardMetaNode = (metaType == MetaNodeType::PROXY_TRANSMISION); } - softbusListener_->RegisterSoftbusLnnOpsCbk(pkgName, shared_from_this()); - StartDiscoveryTimer(pkgName); + softbusListener_->RegisterSoftbusLnnOpsCbk(pkgNameTemp, shared_from_this()); + StartDiscoveryTimer(pkgNameTemp); auto it = filterOptions.find(PARAM_KEY_FILTER_OPTIONS); nlohmann::json jsonObject = nlohmann::json::parse(it->second, nullptr, false); if (!jsonObject.is_discarded() && jsonObject.contains(TYPE_MINE)) { - return StartDiscovering4MineLibary(pkgName, dmSubInfo, it->second); + return StartDiscovering4MineLibary(pkgNameTemp, dmSubInfo, it->second); } - int32_t ret = isStandardMetaNode ? StartDiscoveringNoMetaType(pkgName, dmSubInfo, discoverParam) : - StartDiscovering4MetaType(pkgName, dmSubInfo, discoverParam); + int32_t ret = isStandardMetaNode ? StartDiscoveringNoMetaType(pkgNameTemp, dmSubInfo, discoverParam) : + StartDiscovering4MetaType(pkgNameTemp, dmSubInfo, discoverParam); if (ret != DM_OK) { LOGE("StartDiscovering for meta node process failed, ret = %{public}d", ret); return ret; @@ -306,24 +311,27 @@ int32_t DiscoveryManager::StopDiscovering(const std::string &pkgName, uint16_t s LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = RemoveMultiUserIdentify(pkgName); { std::lock_guard autoLock(locks_); - if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { - pkgNameSet_.erase(pkgName); + if (pkgNameSet_.find(pkgNameTemp) != pkgNameSet_.end()) { + pkgNameSet_.erase(pkgNameTemp); } - if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { - discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(pkgName); + if (discoveryContextMap_.find(pkgNameTemp) != discoveryContextMap_.end()) { + discoveryContextMap_.erase(pkgNameTemp); + if (timer_ != nullptr) { + timer_->DeleteTimer(pkgNameTemp); + } } } { std::lock_guard capLock(capabilityMapLocks_); - if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { - capabilityMap_.erase(pkgName); + if (capabilityMap_.find(pkgNameTemp) != capabilityMap_.end()) { + capabilityMap_.erase(pkgNameTemp); } } - softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); #if (defined(MINE_HARMONY)) return mineSoftbusListener_->StopRefreshSoftbusLNN(subscribeId); #else @@ -333,12 +341,16 @@ int32_t DiscoveryManager::StopDiscovering(const std::string &pkgName, uint16_t s void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info, bool isOnline) { + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); DeviceFilterPara filterPara; filterPara.isOnline = false; filterPara.range = info.range; filterPara.deviceType = info.deviceTypeId; std::string deviceIdHash = static_cast(info.deviceId); - if (isOnline && GetDeviceAclParam(pkgName, deviceIdHash, filterPara.isOnline, filterPara.authForm) != DM_OK) { + if (isOnline && GetDeviceAclParam(callerPkgName, userId, deviceIdHash, filterPara.isOnline, + filterPara.authForm) != DM_OK) { LOGE("The found device get online param failed."); } nlohmann::json jsonObject = nlohmann::json::parse(info.extraData, nullptr, false); @@ -357,6 +369,12 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceI void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara) { + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = callerPkgName; bool isIndiscoveryContextMap = false; DiscoveryContext discoveryContext; { @@ -380,8 +398,8 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t std::lock_guard autoLock(subIdMapLocks_); subscribeId = pkgName2SubIdMap_[pkgName]; } - LOGI("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); - listener_->OnDeviceFound(pkgName, subscribeId, info); + LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); + listener_->OnDeviceFound(processInfo, subscribeId, info); return; } DiscoveryFilter filter; @@ -393,8 +411,8 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t return; } } - LOGI("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); + LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); + listener_->OnDeviceFound(processInfo, discoveryContext.subscribeId, info); } } @@ -412,6 +430,12 @@ bool DiscoveryManager::CompareCapability(uint32_t capabilityType, const std::str void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t subscribeId, int32_t result) { LOGI("DiscoveryManager::OnDiscoveringResult, subscribeId = %{public}d, result = %{public}d.", subscribeId, result); + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = callerPkgName; if (pkgName.empty() || (listener_ == nullptr)) { LOGE("DiscoveryManager::OnDiscoveringResult failed, IDeviceManagerServiceListener is null."); return; @@ -419,7 +443,7 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s if (result == 0) { std::lock_guard autoLock(locks_); discoveryContextMap_[pkgName].subscribeId = (uint32_t)subscribeId; - listener_->OnDiscoverySuccess(pkgName, subscribeId); + listener_->OnDiscoverySuccess(processInfo, subscribeId); return; } { @@ -429,7 +453,9 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s } if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(pkgName); + if (timer_ != nullptr) { + timer_->DeleteTimer(pkgName); + } } } { @@ -438,7 +464,7 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s capabilityMap_.erase(pkgName); } } - listener_->OnDiscoveryFailed(pkgName, (uint32_t)subscribeId, result); + listener_->OnDiscoveryFailed(processInfo, (uint32_t)subscribeId, result); softbusListener_->StopRefreshSoftbusLNN(subscribeId); } @@ -499,7 +525,30 @@ void DiscoveryManager::HandleDiscoveryTimeout(const std::string &pkgName) StopDiscovering(pkgName, subscribeId); } -int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, std::string deviceId, +void DiscoveryManager::UpdateInfoFreq( + const std::map &discoverParam, DmSubscribeInfo &dmSubInfo) +{ + if (auto it = discoverParam.find(PARAM_KEY_DISC_FREQ); it != discoverParam.end()) { + int32_t freq = StringToInt(it->second, DECIMALISM); + if (freq < DmExchangeFreq::DM_LOW || freq > DmExchangeFreq::DM_FREQ_BUTT) { + LOGE("Invalid freq value."); + return; + } + dmSubInfo.freq = static_cast(freq); + } +} + +void DiscoveryManager::UpdateInfoMedium( + const std::map &discoverParam, DmSubscribeInfo &dmSubInfo) +{ + dmSubInfo.medium = DmExchangeMedium::DM_BLE; + if (discoverParam.find(PARAM_KEY_DISC_MEDIUM) != discoverParam.end()) { + int32_t medium = std::atoi((discoverParam.find(PARAM_KEY_DISC_MEDIUM)->second).c_str()); + dmSubInfo.medium = static_cast(medium); + } +} + +int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, int32_t &authForm) { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -510,6 +559,7 @@ int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, std::str discoveryInfo.pkgname = pkgName; discoveryInfo.localDeviceId = requestDeviceId; discoveryInfo.remoteDeviceIdHash = deviceId; + discoveryInfo.userId = userId; if (DiscoveryManager::IsCommonDependencyReady() && DiscoveryManager::GetCommonDependencyObj() != nullptr) { if (DiscoveryManager::GetCommonDependencyObj()->GetDeviceAclParam(discoveryInfo, isOnline, authForm) != DM_OK) { LOGE("GetDeviceAclParam failed."); @@ -532,15 +582,12 @@ bool DiscoveryManager::IsCommonDependencyReady() if (isSoLoaded_ && dpConnector_ != nullptr && dpConnectorHandle_ != nullptr) { return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_DM_COMDENPENDENCY_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; + dpConnectorHandle_ = dlopen(LIB_DM_COMDENPENDENCY_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (dpConnectorHandle_ == nullptr) { + dpConnectorHandle_ = dlopen(LIB_DM_COMDENPENDENCY_NAME, RTLD_NOW | RTLD_NODELETE); } - dpConnectorHandle_ = dlopen(path, RTLD_NOW | RTLD_NODELETE); if (dpConnectorHandle_ == nullptr) { - LOGE("load libdevicemanagerdependency so %{public}s failed, errMsg: %{public}s.", soName.c_str(), dlerror()); + LOGE("load libdevicemanagerdependency so failed, errMsg: %{public}s.", dlerror()); return false; } dlerror(); @@ -576,5 +623,129 @@ bool DiscoveryManager::CloseCommonDependencyObj() return true; } #endif + +void DiscoveryManager::ClearDiscoveryCache(const ProcessInfo &processInfo) +{ + LOGI("PkgName: %{public}s, userId: %{public}d", processInfo.pkgName.c_str(), processInfo.userId); + std::string pkgName = processInfo.pkgName + "#"; + std::set subscribeIdSet = ClearDiscoveryPkgName(pkgName); + + CHECK_NULL_VOID(softbusListener_); + for (auto it : subscribeIdSet) { + std::string pkgNameTemp = (ComposeStr(ComposeStr(processInfo.pkgName, it), processInfo.userId)); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); + softbusListener_->StopRefreshSoftbusLNN(it); + } + + CHECK_NULL_VOID(timer_); + for (auto it : subscribeIdSet) { + std::string pkgNameTemp = (ComposeStr(ComposeStr(processInfo.pkgName, it), processInfo.userId)); + timer_->DeleteTimer(pkgNameTemp); + } +} + +std::set DiscoveryManager::ClearDiscoveryPkgName(const std::string &pkgName) +{ + std::set subscribeIdSet; + { + std::lock_guard autoLock(locks_); + for (auto it = pkgNameSet_.begin(); it != pkgNameSet_.end();) { + if ((*it).find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from pkgNameSet.", (*it).c_str()); + it = pkgNameSet_.erase(it); + } else { + ++it; + } + } + for (auto it = discoveryContextMap_.begin(); it != discoveryContextMap_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from discoveryContextMap_.", it->first.c_str()); + subscribeIdSet.insert(it->second.subscribeId); + it = discoveryContextMap_.erase(it); + } else { + ++it; + } + } + } + { + std::lock_guard capLock(capabilityMapLocks_); + for (auto it = capabilityMap_.begin(); it != capabilityMap_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from capabilityMap_.", it->first.c_str()); + it = capabilityMap_.erase(it); + } else { + ++it; + } + } + } + { + std::lock_guard autoLock(subIdMapLocks_); + for (auto it = pkgName2SubIdMap_.begin(); it != pkgName2SubIdMap_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from pkgName2SubIdMap_.", it->first.c_str()); + subscribeIdSet.insert(it->second); + it = pkgName2SubIdMap_.erase(it); + } else { + ++it; + } + } + } + return subscribeIdSet; +} + +std::string DiscoveryManager::AddMultiUserIdentify(const std::string &pkgName) +{ + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif + if (userId == -1) { + LOGE("Get caller userId failed."); + return pkgName; + } + MultiUserDiscovery multiUserDisc; + multiUserDisc.pkgName = pkgName; + multiUserDisc.userId = userId; + std::string pkgNameTemp = ComposeStr(pkgName, userId); + { + std::lock_guard autoLock(multiUserDiscLocks_); + multiUserDiscMap_[pkgNameTemp] = multiUserDisc; + } + return pkgNameTemp; +} + +std::string DiscoveryManager::RemoveMultiUserIdentify(const std::string &pkgName) +{ + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif + if (userId == -1) { + LOGE("Get caller userId failed."); + return pkgName; + } + std::string pkgNameTemp = ComposeStr(pkgName, userId); + { + std::lock_guard autoLock(multiUserDiscLocks_); + if (multiUserDiscMap_.find(pkgNameTemp) != multiUserDiscMap_.end()) { + multiUserDiscMap_.erase(pkgNameTemp); + } + } + return pkgNameTemp; +} + +void DiscoveryManager::GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, + int32_t &userId) +{ + { + std::lock_guard autoLock(multiUserDiscLocks_); + if (multiUserDiscMap_.find(pkgName) != multiUserDiscMap_.end()) { + callerPkgName = GetCallerPkgName(multiUserDiscMap_[pkgName].pkgName); + userId = multiUserDiscMap_[pkgName].userId; + return; + } + } + LOGE("find failed PkgName %{public}s.", pkgName.c_str()); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/lite/ipc_cmd_parser.cpp b/services/service/src/ipc/lite/ipc_cmd_parser.cpp index 9154339c21937856cf2166444359cd4bf3c919ee..37bec133e610254c2a34d144830565b3639e44ea 100644 --- a/services/service/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/lite/ipc_cmd_parser.cpp @@ -15,8 +15,10 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_service.h" +#include "device_manager_service_notify.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" #include "ipc_cmd_register.h" #include "ipc_def.h" @@ -159,27 +161,6 @@ ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) } } -ON_IPC_SERVER_CMD(START_DEVICE_DISCOVERY, IpcIo &req, IpcIo &reply) -{ - LOGI("StartDeviceDiscovery service listener."); - std::string pkgName = (const char *)ReadString(&req, nullptr); - std::string extra = (const char *)ReadString(&req, nullptr); - uint16_t subscribeId = 0; - ReadUint16(&req, &subscribeId); - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, extra); - WriteInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) -{ - LOGI("StopDeviceDiscovery service listener."); - std::string pkgName = (const char *)ReadString(&req, nullptr); - uint16_t subscribeId = 0; - ReadUint16(&req, &subscribeId); - int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - WriteInt32(&reply, ret); -} - ON_IPC_SERVER_CMD(REQUEST_CREDENTIAL, IpcIo &req, IpcIo &reply) { LOGI("request credential service listener."); @@ -258,5 +239,17 @@ ON_IPC_SERVER_CMD(DELETE_CREDENTIAL, IpcIo &req, IpcIo &reply) WriteString(&reply, outParamStr.c_str()); } } + +ON_IPC_SERVER_CMD(SYNC_CALLBACK, IpcIo &req, IpcIo &reply) +{ + LOGI("start."); + std::string pkgName = (const char*)ReadString(&req, nullptr); + int32_t dmCommonNotifyEvent = 0; + ReadInt32(&req, &dmCommonNotifyEvent); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + int32_t ret = DeviceManagerServiceNotify::GetInstance().RegisterCallBack(dmCommonNotifyEvent, processInfo); + WriteInt32(&reply, ret); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/lite/ipc_server_listener.cpp b/services/service/src/ipc/lite/ipc_server_listener.cpp index 9543725599ad1ac3d3656fa3be74fe9d52c43b3a..249b705d0405f3ff39b6d2bee354252c10f33e37 100644 --- a/services/service/src/ipc/lite/ipc_server_listener.cpp +++ b/services/service/src/ipc/lite/ipc_server_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -43,6 +43,10 @@ int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity * int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { + if (req == nullptr || rsp == nullptr) { + LOGE("SendRequest req or rsp is nullptr."); + return ERR_DM_POINT_NULL; + } std::string pkgName = req->GetPkgName(); SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { @@ -66,40 +70,21 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr return DM_OK; } -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::vector IpcServerListener::GetAllProcessInfo() { + std::vector processInfoVec; const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); for (const auto &kv : listenerMap) { - SvcIdentity svc; - IpcIo io; - uint8_t data[MAX_DM_IPC_LEN] = {0}; - std::string pkgName = kv.first; - - req->SetPkgName(pkgName); - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) { - LOGE("SetRequest failed cmdCode:%{public}d", cmdCode); - continue; - } - CommonSvcId svcId = kv.second; - CommonSvcToIdentity(&svcId, &svc); - MessageOption option; - MessageOptionInit(&option); - option.flags = TF_OP_ASYNC; - if (::SendRequest(svc, cmdCode, &io, nullptr, option, nullptr) != DM_OK) { - LOGI("SendRequest failed cmdCode:%{public}d", cmdCode); - } + ProcessInfo processInfo; + processInfo.pkgName = kv.first; + processInfoVec.push_back(processInfo); } - return DM_OK; + return processInfoVec; } -std::vector IpcServerListener::GetAllPkgName() +std::set IpcServerListener::GetSystemSA() { - std::vector pkgNameList; - const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); - for (const auto &kv : listenerMap) { - pkgNameList.push_back(kv.first); - } - return pkgNameList; + return {}; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 626580fbb441346e697f5b8474043b82d0bd8e44..4c40447b67de8913ed5f9ba119e30d3505d7031f 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -19,6 +19,7 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_service.h" +#include "device_manager_service_notify.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_device_info.h" @@ -29,7 +30,9 @@ #include "ipc_cmd_register.h" #include "ipc_def.h" #include "ipc_create_pin_holder_req.h" +#include "ipc_credential_auth_status_req.h" #include "ipc_destroy_pin_holder_req.h" +#include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" #include "ipc_notify_credential_req.h" @@ -41,9 +44,12 @@ #include "ipc_notify_pin_holder_event_req.h" #include "ipc_server_client_proxy.h" #include "ipc_server_stub.h" - +#include "multiple_user_connector.h" #include "nlohmann/json.hpp" - +#include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { const unsigned int XCOLLIE_TIMEOUT_S = 5; @@ -417,8 +423,11 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); return ERR_DM_POINT_NULL; } - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); - int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, callback); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); + int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, callback); if (!reply.WriteInt32(result)) { LOGE("write result failed"); OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); @@ -431,8 +440,11 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); - int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); + int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); if (!reply.WriteInt32(result)) { LOGE("write result failed"); return ERR_DM_IPC_WRITE_FAILED; @@ -440,48 +452,6 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce return DM_OK; } -ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string extra = data.ReadString(); - DmSubscribeInfo *subscribeInfo = - static_cast(const_cast(data.ReadRawData(sizeof(DmSubscribeInfo)))); - int32_t result = ERR_DM_POINT_NULL; - - if (subscribeInfo != nullptr) { - result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo, extra); - } - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_CMD(START_DEVICE_DISCOVERY, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string filterOption = data.ReadString(); - uint16_t subscribeId = data.ReadUint16(); - int32_t result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOption); - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - uint16_t subscribeId = data.ReadUint16(); - int32_t result = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} ON_IPC_CMD(PUBLISH_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) { @@ -1100,6 +1070,51 @@ ON_IPC_READ_RESPONSE(BIND_TARGET_RESULT, MessageParcel &reply, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + PeerTargetId targetId = pReq->GetPeerTargetId(); + int32_t result = pReq->GetResult(); + int32_t status = pReq->GetStatus(); + std::string content = pReq->GetContent(); + + if (!data.WriteString(pkgName)) { + LOGE("write bind pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!EncodePeerTargetId(targetId, data)) { + LOGE("write bind peer target id failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(result)) { + LOGE("write bind result code failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(status)) { + LOGE("write bind result status failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(content)) { + LOGE("write bind result content failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SINK_BIND_TARGET_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_SET_REQUEST(UNBIND_TARGET_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) { if (pBaseReq == nullptr) { @@ -1443,5 +1458,191 @@ ON_IPC_CMD(SHIFT_LNN_GEAR, MessageParcel &data, MessageParcel &reply) } return DM_OK; } + +ON_IPC_CMD(SET_DN_POLICY, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string policyStr = data.ReadString(); + std::map policy; + ParseMapFromJsonString(policyStr, policy); + int32_t result = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(STOP_AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + int32_t result = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_SET_REQUEST(REMOTE_DEVICE_TRUST_CHANGE, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string udid = pReq->GetUdid(); + int32_t authForm = pReq->GetAuthForm(); + std::string uuid = pReq->GetUuid(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(udid)) { + LOGE("write udid failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(authForm)) { + LOGE("write authForm code failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(uuid)) { + LOGE("write uuid code failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(REMOTE_DEVICE_TRUST_CHANGE, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DEVICE_SCREEN_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!EncodeDmDeviceInfo(deviceInfo, data)) { + LOGE("write dm device info failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_SCREEN_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_CMD(GET_DEVICE_SCREEN_STATUS, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string networkId = data.ReadString(); + int32_t screenStatus = -1; + int32_t result = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + if (!reply.WriteInt32(result)) { + return ERR_DM_IPC_WRITE_FAILED; + } + if (!reply.WriteInt32(screenStatus)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string udid = data.ReadString(); + std::string netWorkId; + int32_t result = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, netWorkId); + + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!reply.WriteString(netWorkId)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceList = pReq->GetDeviceList(); + uint16_t deviceTypeId = pReq->GetDeviceTypeId(); + int32_t errCode = pReq->GetErrCode(); + + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(deviceList)) { + LOGE("write deviceList failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteUint16(deviceTypeId)) { + LOGE("write deviceTypeId failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(errCode)) { + LOGE("write errCode failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_CMD(SYNC_CALLBACK, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + int32_t dmCommonNotifyEvent = data.ReadInt32(); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); + int32_t result = DeviceManagerServiceNotify::GetInstance().RegisterCallBack(dmCommonNotifyEvent, processInfo); + if (dmCommonNotifyEvent == static_cast(DmCommonNotifyEvent::REG_DEVICE_STATE)) { + DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); + } + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index a9dc4c9f4cad5e8df52c98e5b0d547da249983b5..04ba46250de95508837e7594fcd5d0673b02d2ff 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,43 +24,34 @@ namespace OHOS { namespace DistributedHardware { int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - if (rsp == nullptr) { + if (rsp == nullptr || req == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { LOGE("IpcServerListener::SendRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - std::string pkgName = req->GetPkgName(); - if (pkgName.empty()) { + ProcessInfo processInfo = req->GetProcessInfo(); + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - sptr listener = IpcServerStub::GetInstance().GetDmListener(pkgName); + sptr listener = IpcServerStub::GetInstance().GetDmListener(processInfo); if (listener == nullptr) { - LOGI("cannot get listener for package:%{public}s.", pkgName.c_str()); + LOGI("cannot get listener for package:%{public}s.", processInfo.pkgName.c_str()); return ERR_DM_POINT_NULL; } return listener->SendCmd(cmdCode, req, rsp); } -std::vector IpcServerListener::GetAllPkgName() +std::vector IpcServerListener::GetAllProcessInfo() { - return IpcServerStub::GetInstance().GetAllPkgName(); + return IpcServerStub::GetInstance().GetAllProcessInfo(); } -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::set IpcServerListener::GetSystemSA() { - if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { - LOGE("IpcServerListener::SendAll cmdCode param invalid!"); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - int32_t ret = IpcServerStub::GetInstance().SendALL(cmdCode, req, rsp); - if (ret != DM_OK) { - LOGE("IpcServerListener::SendAll failed!"); - return ret; - } - return DM_OK; + return IpcServerStub::GetInstance().GetSystemSA(); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 548ca3dc98f75eb4378751028a1fac40a2fb419f..e36593386f133dff40121a5727b05da25ba51a8e 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -15,19 +15,29 @@ #include "ipc_server_stub.h" -#include "device_manager_ipc_interface_code.h" -#include "device_manager_service.h" -#include "dm_constants.h" -#include "dm_log.h" #include "if_system_ability_manager.h" #include "ipc_cmd_register.h" #include "ipc_skeleton.h" #include "ipc_types.h" #include "iservice_registry.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "kv_adapter_manager.h" +#endif +#ifdef SUPPORT_MEMMGR #include "mem_mgr_client.h" #include "mem_mgr_proxy.h" +#endif // SUPPORT_MEMMGR + #include "string_ex.h" #include "system_ability_definition.h" +#include "device_manager_ipc_interface_code.h" +#include "device_manager_service.h" +#include "device_manager_service_notify.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "multiple_user_connector.h" +#include "permission_manager.h" namespace OHOS { namespace DistributedHardware { @@ -35,11 +45,13 @@ DM_IMPLEMENT_SINGLE_INSTANCE(IpcServerStub); const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&IpcServerStub::GetInstance()); constexpr int32_t DM_IPC_THREAD_NUM = 32; +constexpr int32_t MAX_CALLBACK_NUM = 5000; IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true) { registerToService_ = false; state_ = ServiceRunningState::STATE_NOT_START; + accountBootListener_ = std::make_shared(); } void IpcServerStub::OnStart() @@ -54,52 +66,61 @@ void IpcServerStub::OnStart() LOGI("called:AddAbilityListener begin!"); AddSystemAbilityListener(DISTRIBUTED_HARDWARE_SA_ID); +#ifdef SUPPORT_MEMMGR AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); +#endif // SUPPORT_MEMMGR AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN); AddSystemAbilityListener(SCREENLOCK_SERVICE_ID); - - { - std::lock_guard lock(dependsSASetLock_); - dependsSASet_.emplace(SOFTBUS_SERVER_SA_ID); -#ifdef SUPPORT_POWER_MANAGER - dependsSASet_.emplace(POWER_MANAGER_SERVICE_ID); // power -#endif // SUPPORT_POWER_MANAGER - } - AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID); -#ifdef SUPPORT_POWER_MANAGER - AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID); // power -#endif // SUPPORT_POWER_MANAGER LOGI("called:AddAbilityListener end!"); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); +#endif + DeviceManagerService::GetInstance().SubscribePackageCommonEvent(); } void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) { LOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId); - { - std::lock_guard lock(dependsSASetLock_); - if (dependsSASet_.find(systemAbilityId) != dependsSASet_.end()) { - dependsSASet_.erase(systemAbilityId); - if (dependsSASet_.empty()) { - DeviceManagerService::GetInstance().InitSoftbusListener(); - if (!Init()) { - LOGE("failed to init IpcServerStub"); - state_ = ServiceRunningState::STATE_NOT_START; - return; - } - state_ = ServiceRunningState::STATE_RUNNING; - } + if (systemAbilityId == SOFTBUS_SERVER_SA_ID) { + DeviceManagerService::GetInstance().InitSoftbusListener(); + if (!Init()) { + LOGE("failed to init IpcServerStub"); + state_ = ServiceRunningState::STATE_NOT_START; + return; } + state_ = ServiceRunningState::STATE_RUNNING; + return; } +#ifdef SUPPORT_MEMMGR if (systemAbilityId == MEMORY_MANAGER_SA_ID) { int pid = getpid(); Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 1, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); - } else if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + return; + } +#endif // SUPPORT_MEMMGR + + if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + MultipleUserConnector::SetAccountInfo(MultipleUserConnector::GetCurrentAccountUserID(), dmAccountInfo); DeviceManagerService::GetInstance().InitAccountInfo(); - } else if (systemAbilityId == SCREENLOCK_SERVICE_ID) { + return; + } + + if (systemAbilityId == SCREENLOCK_SERVICE_ID) { DeviceManagerService::GetInstance().InitScreenLockEvent(); + return; + } + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) { + KVAdapterManager::GetInstance().ReInit(); + return; } +#endif } void IpcServerStub::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) @@ -123,6 +144,7 @@ bool IpcServerStub::Init() return false; } registerToService_ = true; + KVAdapterManager::GetInstance().Init(); } return true; } @@ -133,8 +155,10 @@ void IpcServerStub::OnStop() DeviceManagerService::GetInstance().UninitDMServiceListener(); state_ = ServiceRunningState::STATE_NOT_START; registerToService_ = false; +#ifdef SUPPORT_MEMMGR int pid = getpid(); Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 0, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); +#endif // SUPPORT_MEMMGR LOGI("IpcServerStub::OnStop end."); } @@ -180,119 +204,109 @@ ServiceRunningState IpcServerStub::QueryServiceState() const return state_; } -int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr listener) +int32_t IpcServerStub::RegisterDeviceManagerListener(const ProcessInfo &processInfo, sptr listener) { - if (pkgName.empty() || listener == nullptr) { + if (processInfo.pkgName.empty() || listener == nullptr) { LOGE("RegisterDeviceManagerListener error: input parameter invalid."); return ERR_DM_POINT_NULL; } - LOGI("Register device manager listener for package name: %{public}s", pkgName.c_str()); + LOGI("Register device manager listener for package name: %{public}s", processInfo.pkgName.c_str()); std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(pkgName); + auto iter = dmListener_.find(processInfo); if (iter != dmListener_.end()) { - LOGI("RegisterDeviceManagerListener: listener already exists"); - auto recipientIter = appRecipient_.find(pkgName); + LOGI("Listener already exists"); + auto recipientIter = appRecipient_.find(processInfo); if (recipientIter == appRecipient_.end()) { - LOGI("RegisterDeviceManagerListener: appRecipient not exists"); - dmListener_.erase(pkgName); + LOGI("AppRecipient not exists"); + dmListener_.erase(processInfo); } else { auto listener = iter->second; auto appRecipient = recipientIter->second; listener->AsObject()->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(pkgName); - dmListener_.erase(pkgName); + appRecipient_.erase(processInfo); + dmListener_.erase(processInfo); } } - sptr appRecipient = sptr(new AppDeathRecipient()); if (!listener->AsObject()->AddDeathRecipient(appRecipient)) { - LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); + LOGE("AddDeathRecipient Failed"); + } + if (dmListener_.size() > MAX_CALLBACK_NUM || appRecipient_.size() > MAX_CALLBACK_NUM) { + LOGE("dmListener_ or appRecipient_ size exceed the limit!"); + return ERR_DM_FAILED; } - dmListener_[pkgName] = listener; - appRecipient_[pkgName] = appRecipient; - LOGI("RegisterDeviceManagerListener: Register listener complete."); + dmListener_[processInfo] = listener; + appRecipient_[processInfo] = appRecipient; + AddSystemSA(processInfo.pkgName); + LOGI("Register listener complete."); return DM_OK; } -int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) +int32_t IpcServerStub::UnRegisterDeviceManagerListener(const ProcessInfo &processInfo) { - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("IpcServerStub::UnRegisterDeviceManagerListener In, pkgName: %{public}s", pkgName.c_str()); + LOGI("IpcServerStub::UnRegisterDeviceManagerListener In, pkgName: %{public}s", processInfo.pkgName.c_str()); std::lock_guard autoLock(listenerLock_); - auto listenerIter = dmListener_.find(pkgName); + auto listenerIter = dmListener_.find(processInfo); if (listenerIter == dmListener_.end()) { - LOGI("UnRegisterDeviceManagerListener: listener not exists"); + LOGI("Listener not exists"); return DM_OK; } - auto recipientIter = appRecipient_.find(pkgName); + auto recipientIter = appRecipient_.find(processInfo); if (recipientIter == appRecipient_.end()) { - LOGI("UnRegisterDeviceManagerListener: appRecipient not exists"); - dmListener_.erase(pkgName); + LOGI("AppRecipient not exists"); + dmListener_.erase(processInfo); return DM_OK; } auto listener = listenerIter->second; auto appRecipient = recipientIter->second; listener->AsObject()->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(pkgName); - dmListener_.erase(pkgName); - return DM_OK; -} - -int32_t IpcServerStub::SendALL(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - std::lock_guard autoLock(listenerLock_); - for (const auto &iter : dmListener_) { - auto pkgName = iter.first; - auto listener = iter.second; - req->SetPkgName(pkgName); - if (listener == nullptr) { - LOGE("IpcServerStub::SendALL, listener is nullptr, pkgName : %{public}s.", pkgName.c_str()); - continue; - } - listener->SendCmd(cmdCode, req, rsp); - } + appRecipient_.erase(processInfo); + dmListener_.erase(processInfo); + RemoveSystemSA(processInfo.pkgName); + DeviceManagerService::GetInstance().RemoveNotifyRecord(processInfo); return DM_OK; } -std::vector IpcServerStub::GetAllPkgName() +std::vector IpcServerStub::GetAllProcessInfo() { - std::vector PkgNameVec; + std::vector processInfoVec; std::lock_guard autoLock(listenerLock_); for (const auto &iter : dmListener_) { - PkgNameVec.push_back(iter.first); + processInfoVec.push_back(iter.first); } - return PkgNameVec; + return processInfoVec; } -const sptr IpcServerStub::GetDmListener(std::string pkgName) const +const sptr IpcServerStub::GetDmListener(ProcessInfo processInfo) const { - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return nullptr; } std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(pkgName); + auto iter = dmListener_.find(processInfo); if (iter == dmListener_.end()) { return nullptr; } return iter->second; } -const std::string IpcServerStub::GetDmListenerPkgName(const wptr &remote) const +const ProcessInfo IpcServerStub::GetDmListenerPkgName(const wptr &remote) const { - std::string pkgName = ""; + ProcessInfo processInfo; std::lock_guard autoLock(listenerLock_); for (const auto &iter : dmListener_) { if ((iter.second)->AsObject() == remote.promote()) { - pkgName = iter.first; + processInfo = iter.first; break; } } - return pkgName; + return processInfo; } int32_t IpcServerStub::Dump(int32_t fd, const std::vector& args) @@ -319,9 +333,35 @@ int32_t IpcServerStub::Dump(int32_t fd, const std::vector& args) void AppDeathRecipient::OnRemoteDied(const wptr &remote) { - std::string pkgName = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); - LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", pkgName.c_str()); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ProcessInfo processInfo = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); + LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", processInfo.pkgName.c_str()); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); + DeviceManagerServiceNotify::GetInstance().ClearDiedProcessCallback(processInfo); +} + +void IpcServerStub::AddSystemSA(const std::string &pkgName) +{ + if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) { + systemSA_.insert(pkgName); + } +} + +void IpcServerStub::RemoveSystemSA(const std::string &pkgName) +{ + if (PermissionManager::GetInstance().CheckSystemSA(pkgName) || systemSA_.find(pkgName) != systemSA_.end()) { + systemSA_.erase(pkgName); + } +} + +std::set IpcServerStub::GetSystemSA() +{ + std::lock_guard autoLock(listenerLock_); + std::set systemSA; + for (const auto &item : systemSA_) { + systemSA.insert(item); + } + return systemSA; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/notify/device_manager_service_notify.cpp b/services/service/src/notify/device_manager_service_notify.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55b8b9b3f87f1f2b31400b6fcd76f8dfd9ec8c2a --- /dev/null +++ b/services/service/src/notify/device_manager_service_notify.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_service_notify.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerServiceNotify); +namespace { +constexpr uint32_t MAX_CALLBACK_LEN = 1000; +const static std::map unRegNotifyEventMap_ = { + {DmCommonNotifyEvent::UN_REG_DEVICE_STATE, DmCommonNotifyEvent::REG_DEVICE_STATE}, + {DmCommonNotifyEvent::UN_REG_DEVICE_SCREEN_STATE, DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE}, + {DmCommonNotifyEvent::UN_REG_REMOTE_DEVICE_TRUST_CHANGE, DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE}, + {DmCommonNotifyEvent::UN_REG_CREDENTIAL_AUTH_STATUS_NOTIFY, DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY} +}; + +const static std::set regNotifyEventSet_ = { + DmCommonNotifyEvent::REG_DEVICE_STATE, + DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE, + DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE, + DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY +}; +} + +int32_t DeviceManagerServiceNotify::RegisterCallBack(int32_t dmCommonNotifyEvent, const ProcessInfo &processInfo) +{ + LOGI("start event %{public}d pkgName: %{public}s.", dmCommonNotifyEvent, processInfo.pkgName.c_str()); + if (processInfo.pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + DmCommonNotifyEvent notifyEvent = static_cast(dmCommonNotifyEvent); + std::lock_guard autoLock(callbackLock_); + if (unRegNotifyEventMap_.find(notifyEvent) != unRegNotifyEventMap_.end()) { + if (callbackMap_.find(unRegNotifyEventMap_.at(notifyEvent)) == callbackMap_.end()) { + LOGI("notifyEvent is not exist %{public}d.", unRegNotifyEventMap_.at(notifyEvent)); + return DM_OK; + } + callbackMap_.at(unRegNotifyEventMap_.at(notifyEvent)).erase(processInfo); + return DM_OK; + } + if (regNotifyEventSet_.find(notifyEvent) == regNotifyEventSet_.end()) { + LOGE("notifyEvent is not support %{public}d.", notifyEvent); + return ERR_DM_INPUT_PARA_INVALID; + } + if (callbackMap_.find(notifyEvent) == callbackMap_.end()) { + std::set processInfoSet; + processInfoSet.insert(processInfo); + callbackMap_[notifyEvent] = processInfoSet; + return DM_OK; + } + if (callbackMap_[notifyEvent].size() >= MAX_CALLBACK_LEN) { + LOGE("too many callbacks dmCommonNotifyEvent: %{public}d, pkgName: %{public}s", dmCommonNotifyEvent, + processInfo.pkgName.c_str()); + return ERR_DM_FAILED; + } + callbackMap_.at(notifyEvent).insert(processInfo); + return DM_OK; +} + +void DeviceManagerServiceNotify::GetCallBack(int32_t dmCommonNotifyEvent, std::set &processInfos) +{ + LOGI("start event %{public}d.", dmCommonNotifyEvent); + DmCommonNotifyEvent notifyEvent = static_cast(dmCommonNotifyEvent); + std::lock_guard autoLock(callbackLock_); + if (regNotifyEventSet_.find(notifyEvent) == regNotifyEventSet_.end()) { + LOGE("notifyEvent is not support %{public}d.", notifyEvent); + return; + } + if (callbackMap_.find(notifyEvent) == callbackMap_.end()) { + LOGE("callback is empty %{public}d.", notifyEvent); + return; + } + processInfos = callbackMap_.at(notifyEvent); +} + +void DeviceManagerServiceNotify::ClearDiedProcessCallback(const ProcessInfo &processInfo) +{ + LOGI("start pkgName %{public}s.", processInfo.pkgName.c_str()); + std::lock_guard autoLock(callbackLock_); + for (auto iter = callbackMap_.begin(); iter != callbackMap_.end();) { + iter->second.erase(processInfo); + if (iter->second.empty()) { + iter = callbackMap_.erase(iter); + } else { + ++iter; + } + } +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/service/src/permission/lite/permission_manager.cpp b/services/service/src/permission/lite/permission_manager.cpp index f6d416435c9e75fce670e9c26c830b45398f5cd0..3b479ef978a13a14966d3eedd2ad02f6a96cc4fe 100644 --- a/services/service/src/permission/lite/permission_manager.cpp +++ b/services/service/src/permission/lite/permission_manager.cpp @@ -54,15 +54,27 @@ bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &proc return true; } -bool PermissionManager::CheckSystemSA(const std::string &pkgName) +bool PermissionManager::CheckWhiteListSystemSA(const std::string &pkgName) { (void)pkgName; return true; } -std::unordered_set PermissionManager::GetSystemSA() +std::unordered_set PermissionManager::GetWhiteListSystemSA() { return std::unordered_set{}; } + +bool PermissionManager::CheckSystemSA(const std::string &pkgName) +{ + (void)pkgName; + return true; +} + +bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) +{ + (void)processName; + return true; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 914ddf819dd63313ab8d12c3077a403a2b923379..971d0da127c558c884f470e4b0ec8925183d474b 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -37,24 +37,32 @@ constexpr const char* DM_MONITOR_DEVICE_NETWORK_STATE_PERMISSION = "ohos.permiss constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; constexpr int32_t PKG_NAME_SIZE_MAX = 256; -#define AUTH_CODE_WHITE_LIST_NUM (3) +constexpr int32_t AUTH_CODE_WHITE_LIST_NUM = 3; constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "com.huawei.msdp.hmringgenerator", "com.huawei.msdp.hmringdiscriminator", "CollaborationFwk", }; -#define PIN_HOLDER_WHITE_LIST_NUM (1) +constexpr int32_t PIN_HOLDER_WHITE_LIST_NUM = 1; constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "CollaborationFwk", }; -#define SYSTEM_SA_WHITE_LIST_NUM (4) +constexpr int32_t SYSTEM_SA_WHITE_LIST_NUM = 7; constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", "ohos.dslm", "ohos.deviceprofile", + "distributed_bundle_framework", + "ohos.dhardware", + "ohos.security.distributed_access_token", +}; + +constexpr uint32_t SETDNPOLICY_WHITE_LIST_NUM = 1; +constexpr const static char g_setDnPolicyWhiteList[SETDNPOLICY_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "collaboration_service", }; } @@ -189,7 +197,7 @@ bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &proc return false; } -bool PermissionManager::CheckSystemSA(const std::string &pkgName) +bool PermissionManager::CheckWhiteListSystemSA(const std::string &pkgName) { for (uint16_t index = 0; index < SYSTEM_SA_WHITE_LIST_NUM; ++index) { std::string tmp(systemSaWhiteList[index]); @@ -200,7 +208,7 @@ bool PermissionManager::CheckSystemSA(const std::string &pkgName) return false; } -std::unordered_set PermissionManager::GetSystemSA() +std::unordered_set PermissionManager::GetWhiteListSystemSA() { std::unordered_set systemSA; for (uint16_t index = 0; index < SYSTEM_SA_WHITE_LIST_NUM; ++index) { @@ -209,5 +217,37 @@ std::unordered_set PermissionManager::GetSystemSA() } return systemSA; } + +bool PermissionManager::CheckSystemSA(const std::string &pkgName) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("CheckMonitorPermission GetCallingTokenID error."); + return false; + } + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + return true; + } + return false; +} + +bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) +{ + if (processName.empty()) { + LOGE("ProcessName is empty"); + return false; + } + uint16_t index = 0; + for (; index < SETDNPOLICY_WHITE_LIST_NUM; ++index) { + std::string tmp(g_setDnPolicyWhiteList[index]); + if (processName == tmp) { + return true; + } + } + + LOGE("Process name: %{public}s invalid.", processName.c_str()); + return false; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 49c2d3b06b3d49a12de682f6ec71b2147e45a625..5463d186628b9773e9c641b885663e0b023bbb39 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -20,6 +20,9 @@ #include "dm_log.h" #include "dm_radar_helper.h" #include "nlohmann/json.hpp" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -34,6 +37,7 @@ constexpr int32_t MSG_TYPE_DESTROY_PIN_HOLDER = 650; constexpr int32_t MSG_TYPE_DESTROY_PIN_HOLDER_RESP = 651; constexpr int32_t MSG_TYPE_PIN_HOLDER_CHANGE = 700; constexpr int32_t MSG_TYPE_PIN_HOLDER_CHANGE_RESP = 701; +constexpr int32_t MSG_TYPE_PIN_CLOSE_SESSION = 800; constexpr const char* PINHOLDER_CREATE_TIMEOUT_TASK = "deviceManagerTimer:pinholdercreate"; constexpr int32_t PIN_HOLDER_SESSION_CREATE_TIMEOUT = 60; @@ -45,6 +49,8 @@ constexpr const char* TAG_REMOTE_DEVICE_ID = "REMOTE_DEVICE_ID"; constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; +constexpr int32_t ERR_DM_TIME_OUT = 96929745; +constexpr int32_t ERR_DM_CREATE_PIN_HOLDER_BUSY = 96929821; constexpr const char* TAG_MSG_TYPE = "MSG_TYPE"; constexpr const char* TAG_DM_VERSION = "DM_VERSION"; constexpr const char* DM_CONNECTION_DISCONNECTED = "DM_CONNECTION_DISCONNECTED"; @@ -81,7 +87,12 @@ int32_t PinHolder::RegisterPinHolderCallback(const std::string &pkgName) LOGE("RegisterPinHolderCallback session is nullptr."); return ERR_DM_FAILED; } - registerPkgName_ = pkgName; + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif + processInfo_.userId = userId; + processInfo_.pkgName = pkgName; session_->RegisterSessionCallback(shared_from_this()); return DM_OK; } @@ -90,7 +101,7 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload) { LOGI("CreatePinHolder."); - if (registerPkgName_.empty() || registerPkgName_ != pkgName) { + if (processInfo_.pkgName.empty() || processInfo_.pkgName != pkgName) { LOGE("CreatePinHolder pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -116,13 +127,14 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, sessionId_ = session_->OpenSessionServer(targetId); int32_t stageRes = sessionId_ > 0 ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); - DmRadarHelper::GetInstance().ReportCreatePinHolder(registerPkgName_, - sessionId_, targetId.deviceId, sessionId_, stageRes); + DmRadarHelper::GetInstance().ReportCreatePinHolder( + processInfo_.pkgName, sessionId_, targetId.deviceId, sessionId_, stageRes); if (sessionId_ < 0) { LOGE("[SOFTBUS]open session error, sessionId: %{public}d.", sessionId_); - listener_->OnCreateResult(registerPkgName_, sessionId_); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, + listener_->OnCreateResult(processInfo_, sessionId_); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, sessionId_, ""); + sessionId_ = SESSION_ID_INVALID; return sessionId_; } pinType_ = pinType; @@ -138,7 +150,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget LOGE("DestroyPinHolder listener or session is nullptr."); return ERR_DM_FAILED; } - if (registerPkgName_.empty() || pkgName != registerPkgName_) { + if (processInfo_.pkgName.empty() || pkgName != processInfo_.pkgName) { LOGE("DestroyPinHolder pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -149,33 +161,34 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget } if (sessionId_ == SESSION_ID_INVALID) { LOGI("DestroyPinHolder session already destroy."); - listener_->OnDestroyResult(registerPkgName_, ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ret, ""); + listener_->OnDestroyResult(processInfo_, ret); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ret, ""); return ret; } if (sourceState_ != SOURCE_CREATE) { LOGE("DestroyPinHolder failed, state is %{public}d.", sourceState_); return ERR_DM_FAILED; } - timer_->DeleteTimer(PINHOLDER_CREATE_TIMEOUT_TASK); + if (timer_ != nullptr) { + timer_->DeleteTimer(PINHOLDER_CREATE_TIMEOUT_TASK); + } nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; jsonObj[TAG_PIN_TYPE] = pinType; jsonObj[TAG_PAYLOAD] = payload; pinType_ = pinType; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); LOGI("DestroyPinHolder, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER, pinType); ret = session_->SendData(sessionId_, message); int32_t stageRes = ret == DM_OK ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); - DmRadarHelper::GetInstance().ReportDestroyPinHolder(registerPkgName_, - targetId.deviceId, ret, stageRes); + DmRadarHelper::GetInstance().ReportDestroyPinHolder(processInfo_.pkgName, targetId.deviceId, ret, stageRes); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + listener_->OnDestroyResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); return ret; } return ret; @@ -187,27 +200,29 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() LOGE("CreateGeneratePinHolderMsg listener or session is nullptr."); return ERR_DM_FAILED; } - - timer_->DeleteAll(); - timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, - [this] (std::string name) { - PinHolder::CloseSession(name); - }); + if (timer_ != nullptr) { + timer_->DeleteAll(); + timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, + [this] (std::string name) { + PinHolder::CloseSession(name); + }); + } nlohmann::json jsonObj; jsonObj[TAG_PIN_TYPE] = pinType_; jsonObj[TAG_PAYLOAD] = payload_; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; jsonObj[TAG_DM_VERSION] = ""; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); LOGI("CreateGeneratePinHolderMsg, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER, pinType_); int32_t ret = session_->SendData(sessionId_, message); int32_t bizStage = static_cast(PinHolderStage::SEND_CREATE_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("CreateGeneratePinHolderMsg")); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, + std::string("CreateGeneratePinHolderMsg"), ""); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnCreateResult(registerPkgName_, ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ret, ""); + listener_->OnCreateResult(processInfo_, ret); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ret, ""); return ret; } return ret; @@ -228,6 +243,20 @@ int32_t PinHolder::ParseMsgType(const std::string &message) return msgType; } +void PinHolder::ProcessCloseSessionMsg(const std::string &message) +{ + if (listener_ == nullptr || session_ == nullptr) { + LOGE("ProcessCloseSessionMsg listener or session is nullptr."); + return; + } + LOGI("CloseSessionMsg, message type is: %{public}d.", MSG_TYPE_PIN_CLOSE_SESSION); + session_->CloseSessionServer(sessionId_); + sessionId_ = SESSION_ID_INVALID; + sourceState_ = SOURCE_INIT; + sinkState_ = SINK_INIT; + listener_->OnCreateResult(processInfo_, ERR_DM_CREATE_PIN_HOLDER_BUSY); +} + void PinHolder::ProcessCreateMsg(const std::string &message) { if (listener_ == nullptr || session_ == nullptr) { @@ -247,7 +276,7 @@ void PinHolder::ProcessCreateMsg(const std::string &message) std::string payload = jsonObject[TAG_PAYLOAD].get(); isRemoteSupported_ = jsonObject.contains(TAG_DM_VERSION); int32_t bizStage = static_cast(PinHolderStage::RECEIVE_CREATE_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessCreateMsg")); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessCreateMsg"), ""); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; if (sinkState_ != SINK_INIT) { @@ -256,17 +285,17 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; sinkState_ = SINK_CREATE; sourceState_ = SOURCE_CREATE; - listener_->OnPinHolderCreate(registerPkgName_, remoteDeviceId_, pinType, payload); + listener_->OnPinHolderCreate(processInfo_, remoteDeviceId_, pinType, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE, DM_OK, content); + std::string content = SafetyDump(jsonContent); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; - std::string msg = jsonObj.dump(); + std::string msg = SafetyDump(jsonObj); LOGI("ProcessCreateMsg, message type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -293,15 +322,19 @@ void PinHolder::ProcessCreateRespMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnCreateResult(registerPkgName_, DM_OK); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, DM_OK, ""); + listener_->OnCreateResult(processInfo_, DM_OK); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, DM_OK, ""); sourceState_ = SOURCE_CREATE; sinkState_ = SINK_CREATE; } else { LOGE("ProcessCreateRespMsg remote state is wrong."); - listener_->OnCreateResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); + listener_->OnCreateResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); session_->CloseSessionServer(sessionId_); + sessionId_ = SESSION_ID_INVALID; + destroyState_ = STATE_REMOTE_WRONG; + sourceState_ = SOURCE_INIT; + sinkState_ = SINK_INIT; } } @@ -323,7 +356,7 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) DmPinType pinType = static_cast(jsonObject[TAG_PIN_TYPE].get()); std::string payload = jsonObject[TAG_PAYLOAD].get(); int32_t bizStage = static_cast(PinHolderStage::RECEIVE_DESTROY_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessDestroyMsg")); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessDestroyMsg"), ""); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; if (sinkState_ != SINK_CREATE) { @@ -332,15 +365,18 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; sinkState_ = SINK_INIT; sourceState_ = SOURCE_INIT; - listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); - nlohmann::json jsonContent; - jsonContent[TAG_PIN_TYPE] = pinType; - jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); - } - - std::string msg = jsonObj.dump(); + if (!isDestroy_.load()) { + listener_->OnPinHolderDestroy(processInfo_, pinType, payload); + nlohmann::json jsonContent; + jsonContent[TAG_PIN_TYPE] = pinType; + jsonContent[TAG_PAYLOAD] = payload; + std::string content = SafetyDump(jsonContent); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); + isDestroy_.store(true); + } + } + + std::string msg = SafetyDump(jsonObj); LOGI("ProcessDestroyMsg, message type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -358,17 +394,21 @@ void PinHolder::CloseSession(const std::string &name) } nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(); - if (listener_ != nullptr) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); + std::string payload = SafetyDump(jsonObj); + if (listener_ != nullptr && !isDestroy_.load()) { + listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + std::string content = SafetyDump(jsonContent); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + isDestroy_.store(true); } session_->CloseSessionServer(sessionId_); - timer_->DeleteAll(); + if (timer_ != nullptr) { + timer_->DeleteAll(); + } + destroyState_ = STATE_TIME_OUT; sessionId_ = SESSION_ID_INVALID; sinkState_ = SINK_INIT; sourceState_ = SOURCE_INIT; @@ -393,15 +433,19 @@ void PinHolder::ProcessDestroyResMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnDestroyResult(registerPkgName_, DM_OK); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, DM_OK, ""); + listener_->OnDestroyResult(processInfo_, DM_OK); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, DM_OK, ""); sourceState_ = SOURCE_INIT; sinkState_ = SINK_INIT; - timer_->DeleteAll(); + if (timer_ != nullptr) { + timer_->DeleteAll(); + } } else { LOGE("ProcessDestroyResMsg remote state is wrong."); - listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + listener_->OnDestroyResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + sinkState_ = SINK_INIT; + sourceState_ = SOURCE_INIT; } session_->CloseSessionServer(sessionId_); sessionId_ = SESSION_ID_INVALID; @@ -412,8 +456,23 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) { int32_t msgType = ParseMsgType(message); LOGI("OnDataReceived, msgType: %{public}d.", msgType); - + int32_t sessionSide = GetSessionSide(sessionId); + if (sessionSide == SESSION_SIDE_SERVER && sessionId != sessionId_) { + LOGE("another session opened, close this sessionId: %{public}d.", sessionId); + nlohmann::json jsonObj; + jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; + std::string msg = SafetyDump(jsonObj); + int32_t ret = session_->SendData(sessionId, msg); + if (ret != DM_OK) { + LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); + } + return; + } switch (msgType) { + case MSG_TYPE_PIN_CLOSE_SESSION: + ProcessCloseSessionMsg(message); + break; case MSG_TYPE_CREATE_PIN_HOLDER: ProcessCreateMsg(message); break; @@ -459,12 +518,25 @@ void PinHolder::GetPeerDeviceId(int32_t sessionId, std::string &udidHash) void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { - sessionId_ = sessionId; + isDestroy_.store(false); + destroyState_ = STATE_UNKNOW; + char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; + int32_t ret = ::GetPeerDeviceId(sessionId, &peerDeviceId[0], DEVICE_UUID_LENGTH); + if (ret != DM_OK) { + LOGE("[SOFTBUS]GetPeerDeviceId failed for session: %{public}d.", sessionId); + } + LOGI("OnSessionOpened, peerDeviceId: %{public}s.", GetAnonyString(peerDeviceId).c_str()); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(static_cast(PinHolderStage::SESSION_OPENED), + std::string("OnSessionOpened"), std::string(peerDeviceId)); if (sessionSide == SESSION_SIDE_SERVER) { LOGI("[SOFTBUS]onSesssionOpened success, side is sink. sessionId: %{public}d.", sessionId); GetPeerDeviceId(sessionId, remoteDeviceId_); + if (sessionId_ == SESSION_ID_INVALID) { + sessionId_ = sessionId; + } return; } + sessionId_ = sessionId; if (result == DM_OK) { CreateGeneratePinHolderMsg(); return; @@ -472,14 +544,17 @@ void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t LOGE("[SOFTBUS]onSesssionOpened failed. sessionId: %{public}d.", sessionId); sessionId_ = SESSION_ID_INVALID; if (listener_ != nullptr) { - listener_->OnCreateResult(registerPkgName_, result); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, result, ""); + listener_->OnCreateResult(processInfo_, result); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, result, ""); } return; } void PinHolder::OnSessionClosed(int32_t sessionId) { + if (sessionId != sessionId_) { + return; + } LOGI("[SOFTBUS]OnSessionClosed sessionId: %{public}d.", sessionId); sessionId_ = SESSION_ID_INVALID; sinkState_ = SINK_INIT; @@ -488,14 +563,21 @@ void PinHolder::OnSessionClosed(int32_t sessionId) isRemoteSupported_ = false; nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(); - if (listener_ != nullptr) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); + std::string payload = SafetyDump(jsonObj); + if (listener_ != nullptr && !isDestroy_.load()) { + listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + std::string content = SafetyDump(jsonContent); + if (destroyState_ == STATE_UNKNOW) { + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); + } else if (destroyState_ == STATE_REMOTE_WRONG) { + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_FAILED, content); + } else if (destroyState_ == STATE_TIME_OUT) { + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + } + isDestroy_.store(true); } if (timer_ != nullptr) { timer_->DeleteAll(); @@ -519,7 +601,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s LOGE("NotifyPinHolderEvent listener or session is nullptr."); return ERR_DM_FAILED; } - if (registerPkgName_.empty() || pkgName != registerPkgName_ || event.empty()) { + if (processInfo_.pkgName.empty() || pkgName != processInfo_.pkgName || event.empty()) { LOGE("NotifyPinHolderEvent pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -536,22 +618,24 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s LOGE("ProcessChangeMsg DecodeRequest jsonStr error."); return ERR_DM_FAILED; } - timer_->DeleteAll(); - timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, - [this] (std::string name) { - PinHolder::CloseSession(name); - }); + if (timer_ != nullptr) { + timer_->DeleteAll(); + timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, + [this] (std::string name) { + PinHolder::CloseSession(name); + }); + } DmPinType pinType = static_cast(jsonObject[TAG_PIN_TYPE].get()); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; jsonObj[TAG_PIN_TYPE] = pinType; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); LOGI("NotifyPinHolderEvent, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE, pinType); int32_t ret = session_->SendData(sessionId_, message); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); return ERR_DM_FAILED; } return ret; @@ -582,16 +666,18 @@ void PinHolder::ProcessChangeMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); - timer_->DeleteAll(); - timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, - [this] (std::string name) { - PinHolder::CloseSession(name); - }); - } - - std::string msg = jsonObj.dump(); + std::string content = SafetyDump(jsonContent); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); + if (timer_ != nullptr) { + timer_->DeleteAll(); + timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, + [this] (std::string name) { + PinHolder::CloseSession(name); + }); + } + } + + std::string msg = SafetyDump(jsonObj); LOGI("ProcessChangeMsg, message type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -617,10 +703,10 @@ void PinHolder::ProcessChangeRespMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, DM_OK, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, DM_OK, ""); } else { LOGE("ProcessChangeRespMsg remote state is wrong."); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); } } } // namespace DistributedHardware diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 3e97a5c24a12fe36615468fe35cb5a79041d64d3..8ade6ac27689c29deb49d440b32966f87566a438 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -22,6 +22,9 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif #include "iservice_registry.h" #include "multiple_user_connector.h" #include "system_ability_definition.h" @@ -31,7 +34,9 @@ namespace DistributedHardware { using OHOS::EventFwk::MatchingSkills; using OHOS::EventFwk::CommonEventManager; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEAL_THREAD = "account_common_event"; +#endif constexpr int32_t MAX_TRY_TIMES = 3; std::vector DmAccountEventSubscriber::GetSubscriberEventNameVec() const @@ -131,25 +136,41 @@ bool DmAccountCommonEventManager::UnsubscribeAccountCommonEvent() void DmAccountEventSubscriber::OnReceiveEvent(const CommonEventData &data) { std::string receiveEvent = data.GetWant().GetAction(); - LOGI("Received account event: %{public}s", receiveEvent.c_str()); - int32_t userId = data.GetCode(); + int32_t currentUserId = -1; + int32_t beforeUserId = -1; + bool accountValidEvent = false; + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - userId = data.GetCode(); - } else if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - userId = data.GetWant().GetIntParam("userId", 0); - } else if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { - userId = data.GetWant().GetIntParam("userId", 0); - } - if (userId <= 0) { - LOGE("userId is less zero"); + currentUserId = data.GetCode(); + beforeUserId = std::atoi(data.GetWant().GetStringParam("oldId").c_str()); + accountValidEvent = true; + } + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + beforeUserId = data.GetCode(); + accountValidEvent = true; + } + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT || + receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { + currentUserId = data.GetWant().GetIntParam("userId", 0); + beforeUserId = currentUserId; + accountValidEvent = true; + } + LOGI("Received account event: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", + receiveEvent.c_str(), currentUserId, beforeUserId); + if (!accountValidEvent) { + LOGE("Invalied account type event."); return; } - std::thread dealThread([=]() { callback_(userId, receiveEvent); }); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { callback_(receiveEvent, currentUserId, beforeUserId); }); +#else + std::thread dealThread([=]() { callback_(receiveEvent, currentUserId, beforeUserId); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); } dealThread.detach(); +#endif } void DmAccountCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( @@ -168,13 +189,15 @@ void DmAccountCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystem if (!CommonEventManager::SubscribeCommonEvent(changeSubscriber_)) { LOGE("failed to subscribe account commom event: %{public}zu", eventNameVec.size()); } + DMAccountInfo dmAccountInfo; int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - LOGI("after subscribe account event accountId: %{public}s, userId: %{public}s", - GetAnonyString(accountId).c_str(), GetAnonyInt32(userId).c_str()); + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + LOGI("after subscribe account event accountId: %{public}s, userId: %{public}s, accountName: %{public}s", + GetAnonyString(dmAccountInfo.accountId).c_str(), GetAnonyInt32(userId).c_str(), + GetAnonyString(dmAccountInfo.accountName).c_str()); if (userId > 0) { - MultipleUserConnector::SetSwitchOldUserId(userId); - MultipleUserConnector::SetSwitchOldAccountId(accountId); + MultipleUserConnector::SetAccountInfo(userId, dmAccountInfo); } } diff --git a/services/service/src/publishcommonevent/dm_data_share_common_event.cpp b/services/service/src/publishcommonevent/dm_data_share_common_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7e43b10f55446d28477058896f75e6a180541d9 --- /dev/null +++ b/services/service/src/publishcommonevent/dm_data_share_common_event.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_data_share_common_event.h" + +#include +#include + +#include "common_event_support.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif +#include "iservice_registry.h" +#include "multiple_user_connector.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::MatchingSkills; +using OHOS::EventFwk::CommonEventManager; + +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) +constexpr const char* DEAL_THREAD = "data_share"; +#endif +constexpr int32_t MAX_TRY_TIMES = 3; + +std::vector DmDataShareEventSubscriber::GetSubscriberEventNameVec() const +{ + return eventNameVec_; +} + +DmDataShareCommonEventManager::~DmDataShareCommonEventManager() +{ + DmDataShareCommonEventManager::UnsubscribeDataShareCommonEvent(); +} + +bool DmDataShareCommonEventManager::SubscribeDataShareCommonEvent(const std::vector &eventNameVec, + const DataShareEventCallback &callback) +{ + LOGI("start"); + if (eventNameVec.empty() || callback == nullptr) { + LOGE("eventNameVec is empty or callback is nullptr."); + return false; + } + std::lock_guard locker(evenSubscriberMutex_); + if (eventValidFlag_) { + LOGE("failed to subscribe data share commom eventName size: %{public}zu", eventNameVec.size()); + return false; + } + + MatchingSkills matchingSkills; + for (auto &item : eventNameVec) { + matchingSkills.AddEvent(item); + } + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + subscriber_ = std::make_shared(subscriberInfo, callback, eventNameVec); + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + subscriber_ = nullptr; + return false; + } + statusChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener(subscriber_); + if (statusChangeListener_ == nullptr) { + LOGE("statusChangeListener_ is nullptr"); + subscriber_ = nullptr; + return false; + } + while (counter_ != MAX_TRY_TIMES) { + if (samgrProxy->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_) == ERR_OK) { + LOGI("SubscribeDataShareEvent success."); + counter_ = 0; + break; + } + if (++counter_ == MAX_TRY_TIMES) { + LOGI("SubscribeDataShareEvent failed."); + } + sleep(1); + } + eventNameVec_ = eventNameVec; + eventValidFlag_ = true; + LOGI("success to subscribe data share commom event name size: %{public}zu", eventNameVec.size()); + return true; +} + +bool DmDataShareCommonEventManager::UnsubscribeDataShareCommonEvent() +{ + std::lock_guard locker(evenSubscriberMutex_); + if (!eventValidFlag_) { + LOGE("failed to unsubscribe data share commom event name size: %{public}zu because event is invalid.", + eventNameVec_.size()); + return false; + } + if (subscriber_ != nullptr) { + LOGI("start to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + if (!CommonEventManager::UnSubscribeCommonEvent(subscriber_)) { + LOGE("failed to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + return false; + } + LOGI("success to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + subscriber_ = nullptr; + } + if (statusChangeListener_ != nullptr) { + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + return false; + } + int32_t ret = samgrProxy->UnSubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_); + if (ret != ERR_OK) { + LOGE("failed to unsubscribe system ability COMMON_EVENT_SERVICE_ID ret:%{public}d", ret); + return false; + } + statusChangeListener_ = nullptr; + } + + LOGI("success to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + eventValidFlag_ = false; + return true; +} + +void DmDataShareEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + std::string receiveEvent = data.GetWant().GetAction(); + LOGI("Received data share event: %{public}s", receiveEvent.c_str()); + if (receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY) { + return; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { callback_();}); +#else + std::thread dealThread(callback_); + int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); + if (ret != DM_OK) { + LOGE("dealThread setname failed."); + } + dealThread.detach(); +#endif +} + +void DmDataShareCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is added with said: %{public}d.", systemAbilityId); + if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { + return; + } + if (changeSubscriber_ == nullptr) { + LOGE("failed to subscribe data share commom event because changeSubscriber_ is nullptr."); + return; + } + std::vector eventNameVec = changeSubscriber_->GetSubscriberEventNameVec(); + LOGI("start to subscribe data share commom eventName: %{public}zu", eventNameVec.size()); + if (!CommonEventManager::SubscribeCommonEvent(changeSubscriber_)) { + LOGE("failed to subscribe data share commom event: %{public}zu", eventNameVec.size()); + } +} + +void DmDataShareCommonEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is removed with said: %{public}d.", systemAbilityId); +} +} // namespace DistributedHardware +} \ No newline at end of file diff --git a/services/service/src/publishcommonevent/dm_package_common_event.cpp b/services/service/src/publishcommonevent/dm_package_common_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d49a5d8faa97f572052e567a1b02a4045bb662a5 --- /dev/null +++ b/services/service/src/publishcommonevent/dm_package_common_event.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_package_common_event.h" + +#include +#include + +#include "common_event_support.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::MatchingSkills; +using OHOS::EventFwk::CommonEventManager; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) +constexpr const char* DEAL_THREAD = "package_common_event"; +#endif +const std::string APP_ID = "appId"; +const std::string ACCESS_TOKEN_ID = "accessTokenId"; +constexpr int32_t MAX_TRY_TIMES = 3; + +std::vector DmPackageEventSubscriber::GetSubscriberEventNameVec() const +{ + return eventNameVec_; +} + +DmPackageCommonEventManager::~DmPackageCommonEventManager() +{ + DmPackageCommonEventManager::UnsubscribePackageCommonEvent(); +} + +bool DmPackageCommonEventManager::SubscribePackageCommonEvent(const std::vector &eventNameVec, + const PackageEventCallback &callback) +{ + if (eventNameVec.empty() || callback == nullptr) { + LOGE("eventNameVec is empty or callback is nullptr."); + return false; + } + std::lock_guard locker(evenSubscriberMutex_); + if (eventValidFlag_) { + LOGE("failed to subscribe package commom eventName size: %{public}zu", eventNameVec.size()); + return false; + } + + MatchingSkills matchingSkills; + for (auto &item : eventNameVec) { + matchingSkills.AddEvent(item); + } + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + subscriber_ = std::make_shared(subscriberInfo, callback, eventNameVec); + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + subscriber_ = nullptr; + return false; + } + statusChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener(subscriber_); + if (statusChangeListener_ == nullptr) { + LOGE("statusChangeListener_ is nullptr"); + subscriber_ = nullptr; + return false; + } + while (counter_ != MAX_TRY_TIMES) { + if (samgrProxy->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_) == ERR_OK) { + LOGI("SubscribePackageEvent success."); + counter_ = 0; + break; + } + if (++counter_ == MAX_TRY_TIMES) { + LOGI("SubscribePackageEvent failed."); + } + sleep(1); + } + eventNameVec_ = eventNameVec; + eventValidFlag_ = true; + LOGI("success to subscribe package commom event name size: %{public}zu", eventNameVec.size()); + return true; +} + +bool DmPackageCommonEventManager::UnsubscribePackageCommonEvent() +{ + std::lock_guard locker(evenSubscriberMutex_); + if (!eventValidFlag_) { + LOGE("failed to unsubscribe package commom event name size: %{public}zu because event is invalid.", + eventNameVec_.size()); + return false; + } + if (subscriber_ != nullptr) { + LOGI("start to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + if (!CommonEventManager::UnSubscribeCommonEvent(subscriber_)) { + LOGE("failed to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + return false; + } + LOGI("success to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + subscriber_ = nullptr; + } + if (statusChangeListener_ != nullptr) { + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + return false; + } + int32_t ret = samgrProxy->UnSubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_); + if (ret != ERR_OK) { + LOGE("failed to unsubscribe system ability COMMON_EVENT_SERVICE_ID ret:%{public}d", ret); + return false; + } + statusChangeListener_ = nullptr; + } + + LOGI("success to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + eventValidFlag_ = false; + return true; +} + +void DmPackageEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + std::string receiveEvent = data.GetWant().GetAction(); + std::string appId = data.GetWant().GetStringParam(APP_ID); + int32_t accessTokenId = static_cast(data.GetWant().GetIntParam(ACCESS_TOKEN_ID, 0)); + LOGI("Received package event: %{public}s", receiveEvent.c_str()); + + if (receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED && + receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + LOGE("Invalied package type event."); + return; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { callback_(appId, receiveEvent, accessTokenId); }); +#else + std::thread dealThread([=]() { callback_(appId, receiveEvent); }); + int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); + if (ret != DM_OK) { + LOGE("dealThread setname failed."); + } + dealThread.detach(); +#endif +} + +void DmPackageCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is added with said: %{public}d.", systemAbilityId); + if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { + return; + } + if (changeSubscriber_ == nullptr) { + LOGE("failed to subscribe package commom event because changeSubscriber_ is nullptr."); + return; + } + std::vector eventNameVec = changeSubscriber_->GetSubscriberEventNameVec(); + LOGI("start to subscribe package commom eventName: %{public}zu", eventNameVec.size()); + if (!CommonEventManager::SubscribeCommonEvent(changeSubscriber_)) { + LOGE("failed to subscribe package commom event: %{public}zu", eventNameVec.size()); + } +} + +void DmPackageCommonEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is removed with said: %{public}d.", systemAbilityId); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/service/src/publishcommonevent/dm_publish_common_event.cpp b/services/service/src/publishcommonevent/dm_publish_common_event.cpp index 85e6009a2e52443b858c9f8068a679dfb20aa435..4c9af611df4452b28875e2dc279db1a6f8d7c96d 100644 --- a/services/service/src/publishcommonevent/dm_publish_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_publish_common_event.cpp @@ -27,13 +27,18 @@ #include "wifi_msg.h" #endif // SUPPORT_WIFI #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif namespace OHOS { namespace DistributedHardware { using OHOS::EventFwk::MatchingSkills; using OHOS::EventFwk::CommonEventManager; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEAL_THREAD = "publish_common_event"; +#endif constexpr int32_t MAX_TRY_TIMES = 3; std::vector DmPublishEventSubscriber::GetSubscriberEventNameVec() const @@ -232,12 +237,16 @@ void DmPublishEventSubscriber::OnReceiveEvent(const CommonEventData &data) } #endif // SUPPORT_WIFI +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { callback_(bluetoothState_, wifiState_, screenState_); }); +#else std::thread dealThread([=]() { callback_(bluetoothState_, wifiState_, screenState_); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); } dealThread.detach(); +#endif } void DmPublishCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( diff --git a/services/service/src/publishcommonevent/dm_screen_common_event.cpp b/services/service/src/publishcommonevent/dm_screen_common_event.cpp index d683d87615b6c6394bb1de680d19ec5c0627ba2c..943cbcffdb657d9dc2f487dc6913fae8bf586f92 100644 --- a/services/service/src/publishcommonevent/dm_screen_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_screen_common_event.cpp @@ -22,6 +22,9 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif #include "iservice_registry.h" #include "multiple_user_connector.h" #include "system_ability_definition.h" @@ -31,7 +34,9 @@ namespace DistributedHardware { using OHOS::EventFwk::MatchingSkills; using OHOS::EventFwk::CommonEventManager; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEAL_THREAD = "screen_lock"; +#endif constexpr int32_t MAX_TRY_TIMES = 3; std::vector DmScreenEventSubscriber::GetSubscriberEventNameVec() const @@ -135,12 +140,16 @@ void DmScreenEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { return; } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { callback_(receiveEvent); }); +#else std::thread dealThread(callback_, receiveEvent); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); } dealThread.detach(); +#endif } void DmScreenCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( diff --git a/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d735c57f9e42664b807152e289e719849cf3b4a4 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_comm_tool.h" + +#include "cJSON.h" + +#include "device_manager_service.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_transport.h" +#include "dm_transport_msg.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { +DMCommTool::DMCommTool() : dmTransportPtr_(nullptr) +{ + LOGI("Ctor DMCommTool"); +} + +void DMCommTool::Init() +{ + LOGI("Init DMCommTool"); + dmTransportPtr_ = std::make_shared(shared_from_this()); + std::shared_ptr runner = AppExecFwk::EventRunner::Create(true); + eventHandler_ = std::make_shared(runner, shared_from_this()); + dmTransportPtr_->Init(); +} + +void DMCommTool::UnInit() +{ + LOGI("UnInit DMCommTool"); + if (dmTransportPtr_ == nullptr) { + LOGI("dmTransportPtr_ is null"); + return; + } + dmTransportPtr_->UnInit(); +} + +std::shared_ptr DMCommTool::GetInstance() +{ + static std::shared_ptr instance = std::make_shared(); + return instance; +} + +void DMCommTool::SendUserIds(const std::string rmtNetworkId, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds) +{ + if (!IsIdLengthValid(rmtNetworkId) || foregroundUserIds.empty() || dmTransportPtr_ == nullptr) { + LOGE("param invalid, networkId: %{public}s, foreground userids size: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), static_cast(foregroundUserIds.size())); + return; + } + + if (dmTransportPtr_->StartSocket(rmtNetworkId) != DM_OK) { + LOGE("Start socket error"); + return; + } + + UserIdsMsg userIdsMsg(foregroundUserIds, backgroundUserIds); + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + LOGE("Create cJSON object failed."); + return; + } + ToJson(root, userIdsMsg); + char *msg = cJSON_PrintUnformatted(root); + if (msg == nullptr) { + cJSON_Delete(root); + return; + } + std::string msgStr(msg); + cJSON_Delete(root); + CommMsg commMsg(DM_COMM_SEND_LOCAL_USERIDS, msgStr); + std::string payload = GetCommMsgString(commMsg); + + int32_t ret = dmTransportPtr_->Send(rmtNetworkId, payload); + if (ret != DM_OK) { + LOGE("Send local foreground userids failed, ret: %{public}d", ret); + return; + } + LOGI("Send local foreground userids success"); +} + +void DMCommTool::RspLocalFrontOrBackUserIds(const std::string rmtNetworkId, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds) +{ + UserIdsMsg userIdsMsg(foregroundUserIds, backgroundUserIds); + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + LOGE("Create cJSON object failed."); + return; + } + ToJson(root, userIdsMsg); + char *msg = cJSON_PrintUnformatted(root); + if (msg == nullptr) { + cJSON_Delete(root); + return; + } + std::string msgStr(msg); + cJSON_Delete(root); + CommMsg commMsg(DM_COMM_RSP_LOCAL_USERIDS, msgStr); + std::string payload = GetCommMsgString(commMsg); + + int32_t ret = dmTransportPtr_->Send(rmtNetworkId, payload); + if (ret != DM_OK) { + LOGE("Response local foreground userids failed, ret: %{public}d", ret); + return; + } + LOGI("Response local foreground userids success"); +} + +DMCommTool::DMCommToolEventHandler::DMCommToolEventHandler(const std::shared_ptr runner, + std::shared_ptr dmCommToolPtr) : AppExecFwk::EventHandler(runner), dmCommToolWPtr_(dmCommToolPtr) +{ + LOGI("Ctor DMCommToolEventHandler"); +} + +void DMCommTool::DMCommToolEventHandler::ProcessEvent( + const AppExecFwk::InnerEvent::Pointer &event) +{ + uint32_t eventId = event->GetInnerEventId(); + std::shared_ptr commMsg = event->GetSharedObject(); + if (commMsg == nullptr) { + LOGE("ProcessEvent commMsg is null"); + return; + } + if (dmCommToolWPtr_.expired()) { + LOGE("dmCommToolWPtr_ is expired"); + return; + } + std::shared_ptr dmCommToolPtr = dmCommToolWPtr_.lock(); + if (dmCommToolPtr == nullptr) { + LOGE("dmCommToolPtr is null"); + return; + } + switch (eventId) { + case DM_COMM_SEND_LOCAL_USERIDS: { + // Process remote foreground userids and send back local user ids + dmCommToolPtr->ProcessReceiveUserIdsEvent(commMsg); + break; + } + case DM_COMM_RSP_LOCAL_USERIDS: { + // Process remote foreground userids and close session + dmCommToolPtr->ProcessResponseUserIdsEvent(commMsg); + break; + } + default: + LOGE("event is undefined, id is %{public}d", eventId); + break; + } +} + +void DMCommTool::ProcessReceiveUserIdsEvent(const std::shared_ptr commMsg) +{ + LOGI("Receive remote userids, process and rsp local userid"); + std::string rmtUdid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(commMsg->remoteNetworkId.c_str(), rmtUdid); + if (rmtUdid.empty()) { + LOGE("Can not find remote udid by networkid: %{public}s", commMsg->remoteNetworkId.c_str()); + return; + } + + std::string payload = commMsg->commMsg->msg; + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + UserIdsMsg userIdsMsg; + FromJson(root, userIdsMsg); + cJSON_Delete(root); + uint32_t totalUserNum = static_cast(userIdsMsg.foregroundUserIds.size()) + + static_cast(userIdsMsg.backgroundUserIds.size()); + if (userIdsMsg.foregroundUserIds.empty()) { + LOGE("Parse but get none remote foreground userids"); + } else { + // step1: process remote foreground/background userids + DeviceManagerService::GetInstance().ProcessSyncUserIds(userIdsMsg.foregroundUserIds, + userIdsMsg.backgroundUserIds, rmtUdid); + } + + // step2: send back local userids + std::vector foregroundUserIds; + std::vector backgroundUserIds; + MultipleUserConnector::GetForegroundUserIds(foregroundUserIds); + MultipleUserConnector::GetBackgroundUserIds(backgroundUserIds); + std::vector foregroundUserIdsU32; + std::vector backgroundUserIdsU32; + for (auto const &u : foregroundUserIds) { + foregroundUserIdsU32.push_back(static_cast(u)); + } + for (auto const &u : backgroundUserIds) { + backgroundUserIdsU32.push_back(static_cast(u)); + } + RspLocalFrontOrBackUserIds(commMsg->remoteNetworkId, foregroundUserIdsU32, backgroundUserIdsU32); +} + +void DMCommTool::ProcessResponseUserIdsEvent(const std::shared_ptr commMsg) +{ + LOGI("process receive remote userids response"); + // step1: close socket + this->dmTransportPtr_->StopSocket(commMsg->remoteNetworkId); + + std::string rmtUdid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(commMsg->remoteNetworkId.c_str(), rmtUdid); + if (rmtUdid.empty()) { + LOGE("Can not find remote udid by networkid: %{public}s", commMsg->remoteNetworkId.c_str()); + return; + } + + std::string payload = commMsg->commMsg->msg; + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + UserIdsMsg userIdsMsg; + FromJson(root, userIdsMsg); + cJSON_Delete(root); + if (userIdsMsg.foregroundUserIds.empty()) { + LOGE("Parse but get none remote userids"); + return; + } + // step2: process remote foreground/background userids + if (!userIdsMsg.foregroundUserIds.empty()) { + DeviceManagerService::GetInstance().ProcessSyncUserIds(userIdsMsg.foregroundUserIds, + userIdsMsg.backgroundUserIds, rmtUdid); + } else { + LOGE("Receive remote foreground userid empty"); + } +} + +std::shared_ptr DMCommTool::GetEventHandler() +{ + return this->eventHandler_; +} + +const std::shared_ptr DMCommTool::GetDMTransportPtr() +{ + return this->dmTransportPtr_; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/dm_transport.cpp b/services/service/src/relationshipsyncmgr/dm_transport.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b51103803f7fc9bc9afc9251b92b88f6f93b7b2 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_transport.cpp @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_transport.h" + +#include + +#include "cJSON.h" +#include +#include "dm_anonymous.h" +#include "dm_comm_tool.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" +#include "dm_transport_msg.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +// Dsoftbus sendBytes max message length: 4MB +constexpr uint32_t MAX_SEND_MSG_LENGTH = 4 * 1024 * 1024; +constexpr uint32_t INTERCEPT_STRING_LENGTH = 20; +constexpr uint32_t MAX_ROUND_SIZE = 1000; +static QosTV g_qosInfo[] = { + { .qos = QOS_TYPE_MIN_BW, .value = 256 * 1024}, + { .qos = QOS_TYPE_MAX_LATENCY, .value = 8000 }, + { .qos = QOS_TYPE_MIN_LATENCY, .value = 2000 } +}; +static uint32_t g_qosTvParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); +static std::weak_ptr g_dmCommToolWPtr_; +} + +DMTransport::DMTransport(std::shared_ptr dmCommToolPtr) : remoteDevSocketIds_({}), localServerSocket_(-1), + localSocketName_(""), isSocketSvrCreateFlag_(false), dmCommToolWPtr_(dmCommToolPtr) +{ + LOGI("Ctor DMTransport"); + g_dmCommToolWPtr_ = dmCommToolPtr; +} + +int32_t DMTransport::OnSocketOpened(int32_t socketId, const PeerSocketInfo &info) +{ + LOGI("OnSocketOpened, socket: %{public}d, peerSocketName: %{public}s, peerNetworkId: %{public}s, " + "peerPkgName: %{public}s", socketId, info.name, GetAnonyString(info.networkId).c_str(), info.pkgName); + std::lock_guard lock(rmtSocketIdMtx_); + remoteDevSocketIds_[info.networkId] = socketId; + return DM_OK; +} + +void DMTransport::OnSocketClosed(int32_t socketId, ShutdownReason reason) +{ + LOGI("OnSocketClosed, socket: %{public}d, reason: %{public}d", socketId, (int32_t)reason); + std::lock_guard lock(rmtSocketIdMtx_); + for (auto iter = remoteDevSocketIds_.begin(); iter != remoteDevSocketIds_.end(); ++iter) { + if (iter->second == socketId) { + remoteDevSocketIds_.erase(iter); + break; + } + } +} + +void DMTransport::OnBytesReceived(int32_t socketId, const void *data, uint32_t dataLen) +{ + if (socketId < 0 || data == nullptr || dataLen == 0 || dataLen > MAX_SEND_MSG_LENGTH) { + LOGE("OnBytesReceived param check failed"); + return; + } + + std::string remoteNeworkId = GetRemoteNetworkIdBySocketId(socketId); + if (remoteNeworkId.empty()) { + LOGE("Can not find the remote network id by socketId: %{public}d", socketId); + return; + } + + uint8_t *buf = reinterpret_cast(calloc(dataLen + 1, sizeof(uint8_t))); + if (buf == nullptr) { + LOGE("OnBytesReceived: malloc memory failed"); + return; + } + + if (memcpy_s(buf, dataLen + 1, reinterpret_cast(data), dataLen) != EOK) { + LOGE("OnBytesReceived: memcpy memory failed"); + free(buf); + return; + } + + std::string message(buf, buf + dataLen); + LOGI("Receive message size: %{public}" PRIu32, dataLen); + HandleReceiveMessage(socketId, message); + free(buf); + return; +} + +void DMTransport::HandleReceiveMessage(const int32_t socketId, const std::string &payload) +{ + std::string rmtNetworkId = GetRemoteNetworkIdBySocketId(socketId); + if (rmtNetworkId.empty()) { + LOGE("Can not find networkId by socketId: %{public}d", socketId); + return; + } + if (payload.empty() || payload.size() > MAX_SEND_MSG_LENGTH) { + LOGE("payload invalid"); + return; + } + LOGI("Receive msg: %{public}s", payload.c_str()); + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + std::shared_ptr commMsg = std::make_shared(); + FromJson(root, *commMsg); + cJSON_Delete(root); + + std::shared_ptr innerMsg = std::make_shared(rmtNetworkId, commMsg); + + LOGI("Receive DM msg, code: %{public}d, msg: %{public}s", commMsg->code, GetAnonyString(commMsg->msg).c_str()); + AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(commMsg->code, innerMsg); + std::shared_ptr dmCommToolSPtr = dmCommToolWPtr_.lock(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + if (dmCommToolSPtr->GetEventHandler() == nullptr) { + LOGE("Can not get eventHandler"); + return; + } + dmCommToolSPtr->GetEventHandler()->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE); +} + +std::shared_ptr GetDMCommToolPtr() +{ + if (g_dmCommToolWPtr_.expired()) { + LOGE("DMCommTool Weak ptr expired"); + return nullptr; + } + + std::shared_ptr dmCommToolSPtr = g_dmCommToolWPtr_.lock(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return nullptr; + } + + return dmCommToolSPtr; +} + +void OnBind(int32_t socket, PeerSocketInfo info) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnSocketOpened(socket, info); +} + +void OnShutdown(int32_t socket, ShutdownReason reason) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnSocketClosed(socket, reason); +} + +void OnBytes(int32_t socket, const void *data, uint32_t dataLen) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnBytesReceived(socket, data, dataLen); +} + +void OnMessage(int32_t socket, const void *data, uint32_t dataLen) +{ + (void)socket; + (void)data; + (void)dataLen; + LOGI("socket: %{public}d, dataLen:%{public}" PRIu32, socket, dataLen); +} + +void OnStream(int32_t socket, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param) +{ + (void)socket; + (void)data; + (void)ext; + (void)param; + LOGI("socket: %{public}d", socket); +} + +void OnFile(int32_t socket, FileEvent *event) +{ + (void)event; + LOGI("socket: %{public}d", socket); +} + +void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) +{ + if (qosCount == 0 || qosCount > MAX_ROUND_SIZE) { + LOGE("qosCount is invalid!"); + return; + } + LOGI("OnQos, socket: %{public}d, QoSEvent: %{public}d, qosCount: %{public}" PRIu32, + socket, (int32_t)eventId, qosCount); + for (uint32_t idx = 0; idx < qosCount; idx++) { + LOGI("QosTV: type: %{public}d, value: %{public}d", (int32_t)qos[idx].qos, qos[idx].value); + } +} + +ISocketListener iSocketListener = { + .OnBind = OnBind, + .OnShutdown = OnShutdown, + .OnBytes = OnBytes, + .OnMessage = OnMessage, + .OnStream = OnStream, + .OnFile = OnFile, + .OnQos = OnQos +}; + +int32_t DMTransport::CreateServerSocket() +{ + LOGI("CreateServerSocket start"); + localSocketName_ = DM_SYNC_USERID_SESSION_NAME; + LOGI("CreateServerSocket , local socketName: %{public}s", localSocketName_.c_str()); + std::string dmPkgName(DM_PKG_NAME); + SocketInfo info = { + .name = const_cast(localSocketName_.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + int32_t socket = Socket(info); + LOGI("CreateServerSocket Finish, socket: %{public}d", socket); + return socket; +} + +int32_t DMTransport::CreateClientSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("CreateClientSocket start, peerNetworkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + std::string peerSocketName = DM_SYNC_USERID_SESSION_NAME; + std::string dmPkgName(DM_PKG_NAME); + SocketInfo info = { + .name = const_cast(localSocketName_.c_str()), + .peerName = const_cast(peerSocketName.c_str()), + .peerNetworkId = const_cast(rmtNetworkId.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + int32_t socket = Socket(info); + LOGI("Bind Socket server, socket: %{public}d, localSocketName: %{public}s, peerSocketName: %{public}s", + socket, localSocketName_.c_str(), peerSocketName.c_str()); + return socket; +} + +int32_t DMTransport::Init() +{ + LOGI("Init DMTransport"); + if (isSocketSvrCreateFlag_.load()) { + LOGI("SocketServer already create success."); + return DM_OK; + } + int32_t socket = CreateServerSocket(); + if (socket < DM_OK) { + LOGE("CreateSocketServer failed, ret: %{public}d", socket); + return ERR_DM_FAILED; + } + + int32_t ret = Listen(socket, g_qosInfo, g_qosTvParamIndex, &iSocketListener); + if (ret != DM_OK) { + LOGE("Socket Listen failed, error code %{public}d.", ret); + return ERR_DM_FAILED; + } + isSocketSvrCreateFlag_.store(true); + localServerSocket_ = socket; + LOGI("Finish Init DSoftBus Server Socket, socket: %{public}d", socket); + return DM_OK; +} + +int32_t DMTransport::UnInit() +{ + { + std::lock_guard lock(rmtSocketIdMtx_); + for (auto iter = remoteDevSocketIds_.begin(); iter != remoteDevSocketIds_.end(); ++iter) { + LOGI("Shutdown client socket: %{public}d to remote dev: %{public}s", iter->second, + GetAnonyString(iter->first).c_str()); + Shutdown(iter->second); + } + remoteDevSocketIds_.clear(); + } + + if (!isSocketSvrCreateFlag_.load()) { + LOGI("DSoftBus Server Socket already remove success."); + } else { + LOGI("Shutdown DSoftBus Server Socket, socket: %{public}d", localServerSocket_.load()); + Shutdown(localServerSocket_.load()); + localServerSocket_ = -1; + isSocketSvrCreateFlag_.store(false); + } + return DM_OK; +} + +bool DMTransport::IsDeviceSessionOpened(const std::string &rmtNetworkId, int32_t &socketId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return false; + } + std::lock_guard lock(rmtSocketIdMtx_); + if (remoteDevSocketIds_.find(rmtNetworkId) == remoteDevSocketIds_.end()) { + return false; + } + socketId = remoteDevSocketIds_.at(rmtNetworkId); + LOGI("DeviceSession has opened, rmtNetworkId: %{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socketId); + return true; +} + +std::string DMTransport::GetRemoteNetworkIdBySocketId(int32_t socketId) +{ + std::lock_guard lock(rmtSocketIdMtx_); + std::string networkId = ""; + for (auto const &item : remoteDevSocketIds_) { + if (item.second == socketId) { + networkId = item.first; + break; + } + } + return networkId; +} + +void DMTransport::ClearDeviceSocketOpened(const std::string &remoteDevId) +{ + if (!IsIdLengthValid(remoteDevId)) { + return; + } + std::lock_guard lock(rmtSocketIdMtx_); + remoteDevSocketIds_.erase(remoteDevId); +} + +int32_t DMTransport::StartSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGE("Softbus session has already opened, deviceId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return DM_OK; + } + + int32_t socket = CreateClientSocket(rmtNetworkId); + if (socket < DM_OK) { + LOGE("StartSocket failed, ret: %{public}d", socket); + return ERR_DM_FAILED; + } + + int32_t ret = Bind(socket, g_qosInfo, g_qosTvParamIndex, &iSocketListener); + if (ret < DM_OK) { + LOGE("OpenSession fail, rmtNetworkId: %{public}s, socket: %{public}d, ret: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socket, ret); + Shutdown(socket); + return ERR_DM_FAILED; + } + + LOGI("Bind Socket success, rmtNetworkId:%{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socket); + std::string peerSocketName = DM_SYNC_USERID_SESSION_NAME; + std::string dmPkgName(DM_PKG_NAME); + PeerSocketInfo peerSocketInfo = { + .name = const_cast(peerSocketName.c_str()), + .networkId = const_cast(rmtNetworkId.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + OnSocketOpened(socket, peerSocketInfo); + return DM_OK; +} + +int32_t DMTransport::StopSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (!IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGI("remote dev may be not opened, rmtNetworkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return ERR_DM_FAILED; + } + + LOGI("StopSocket rmtNetworkId: %{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socketId); + Shutdown(socketId); + ClearDeviceSocketOpened(rmtNetworkId); + return DM_OK; +} + +int32_t DMTransport::Send(const std::string &rmtNetworkId, const std::string &payload) +{ + if (!IsIdLengthValid(rmtNetworkId) || !IsMessageLengthValid(payload)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (!IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGI("The session is not open, target networkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return ERR_DM_FAILED; + } + uint32_t payLoadSize = payload.size(); + LOGI("Send payload size: %{public}" PRIu32 ", target networkId: %{public}s, socketId: %{public}d", + static_cast(payload.size()), GetAnonyString(rmtNetworkId).c_str(), socketId); + + if (payLoadSize > MAX_SEND_MSG_LENGTH) { + LOGE("Send error: msg size: %{public}" PRIu32 " too long", payLoadSize); + return ERR_DM_FAILED; + } + uint8_t *buf = reinterpret_cast(calloc((payLoadSize), sizeof(uint8_t))); + if (buf == nullptr) { + LOGE("Send: malloc memory failed"); + return ERR_DM_FAILED; + } + + if (memcpy_s(buf, payLoadSize, reinterpret_cast(payload.c_str()), + payLoadSize) != EOK) { + LOGE("Send: memcpy memory failed"); + free(buf); + return ERR_DM_FAILED; + } + + int32_t ret = SendBytes(socketId, buf, payLoadSize); + free(buf); + if (ret != DM_OK) { + LOGE("dsoftbus send error, ret: %{public}d", ret); + return ERR_DM_FAILED; + } + LOGI("Send payload success"); + return DM_OK; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp b/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fa4e699647cf263e060e3fc4cdfe86f97d60497 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_transport_msg.h" + +#include "dm_anonymous.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const int32_t MAX_USER_ID_NUM = 5; + const int32_t MAX_BACKGROUND_USER_ID_NUM = 5; +} +void ToJson(cJSON *jsonObject, const UserIdsMsg &userIdsMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *foregroundUserIdArr = cJSON_CreateArray(); + if (foregroundUserIdArr == nullptr) { + return; + } + for (auto const &userId : userIdsMsg.foregroundUserIds) { + cJSON_AddItemToArray(foregroundUserIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, FOREGROUND_USERIDS_MSG_USERIDS_KEY, foregroundUserIdArr); + + cJSON *backgroundUserIdArr = cJSON_CreateArray(); + if (backgroundUserIdArr == nullptr) { + return; + } + for (auto const &userId : userIdsMsg.backgroundUserIds) { + cJSON_AddItemToArray(backgroundUserIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, BACKGROUND_USERIDS_MSG_USERIDS_KEY, backgroundUserIdArr); +} + +void FromJson(const cJSON *jsonObject, UserIdsMsg &userIdsMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *foregroundUserIdsArr = cJSON_GetObjectItem(jsonObject, FOREGROUND_USERIDS_MSG_USERIDS_KEY); + if (cJSON_IsArray(foregroundUserIdsArr)) { + int32_t arrSize = cJSON_GetArraySize(foregroundUserIdsArr); + if (arrSize > MAX_USER_ID_NUM) { + LOGE("Receive too many foreground userids, %{public}d", arrSize); + return; + } + for (int32_t i = 0; i < arrSize; i++) { + cJSON *userIdItem = cJSON_GetArrayItem(foregroundUserIdsArr, i); + if (cJSON_IsNumber(userIdItem)) { + uint32_t userId = static_cast(userIdItem->valueint); + userIdsMsg.foregroundUserIds.push_back(userId); + } + } + } + + cJSON *backgroundUserIdsArr = cJSON_GetObjectItem(jsonObject, BACKGROUND_USERIDS_MSG_USERIDS_KEY); + if (cJSON_IsArray(backgroundUserIdsArr)) { + int32_t arrSize = cJSON_GetArraySize(backgroundUserIdsArr); + if (arrSize > MAX_BACKGROUND_USER_ID_NUM) { + LOGE("Receive too many background userids, %{public}d", arrSize); + return; + } + for (int32_t i = 0; i < arrSize; i++) { + cJSON *userIdItem = cJSON_GetArrayItem(backgroundUserIdsArr, i); + if (cJSON_IsNumber(userIdItem)) { + uint32_t userId = static_cast(userIdItem->valueint); + userIdsMsg.backgroundUserIds.push_back(userId); + } + } + } +} + +void ToJson(cJSON *jsonObject, const CommMsg &commMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON_AddNumberToObject(jsonObject, COMM_MSG_CODE_KEY, commMsg.code); + const char *msg = commMsg.msg.c_str(); + cJSON_AddStringToObject(jsonObject, COMM_MSG_MSG_KEY, msg); +} + +void FromJson(const cJSON *jsonObject, CommMsg &commMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *codeObj = cJSON_GetObjectItem(jsonObject, COMM_MSG_CODE_KEY); + if (cJSON_IsNumber(codeObj)) { + commMsg.code = codeObj->valueint; + } + + cJSON *msgObj = cJSON_GetObjectItem(jsonObject, COMM_MSG_MSG_KEY); + if (cJSON_IsString(msgObj)) { + commMsg.msg = msgObj->valuestring; + } +} + +std::string GetCommMsgString(const CommMsg &commMsg) +{ + cJSON *rootMsg = cJSON_CreateObject(); + if (rootMsg == nullptr) { + LOGE("Create cJSON object failed."); + return ""; + } + ToJson(rootMsg, commMsg); + char *msg = cJSON_PrintUnformatted(rootMsg); + if (msg == nullptr) { + cJSON_Delete(rootMsg); + return ""; + } + std::string msgStr = std::string(msg); + cJSON_free(msg); + cJSON_Delete(rootMsg); + + return msgStr; +} + +void ToJson(cJSON *jsonObject, const NotifyUserIds ¬ifyUserIds) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + + cJSON_AddStringToObject(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY, notifyUserIds.remoteUdid.c_str()); + + cJSON *userIdArr = cJSON_CreateArray(); + if (userIdArr == nullptr) { + return; + } + for (auto const &userId : notifyUserIds.userIds) { + cJSON_AddItemToArray(userIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY, userIdArr); +} + +void FromJson(const cJSON *jsonObject, NotifyUserIds ¬ifyUserIds) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + + cJSON *msgObj = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY); + if (cJSON_IsString(msgObj)) { + notifyUserIds.remoteUdid = msgObj->valuestring; + } + + cJSON *userIdsArr = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY); + if (cJSON_IsArray(userIdsArr)) { + int32_t arrSize = cJSON_GetArraySize(userIdsArr); + if (arrSize > MAX_USER_ID_NUM) { + LOGE("Receive too many userids, %{public}d", arrSize); + return; + } + for (int32_t i = 0; i < arrSize; i++) { + cJSON *userIdItem = cJSON_GetArrayItem(userIdsArr, i); + if (cJSON_IsNumber(userIdItem)) { + uint32_t userId = static_cast(userIdItem->valueint); + notifyUserIds.userIds.push_back(userId); + } + } + } +} + +std::string NotifyUserIds::ToString() +{ + cJSON *msg = cJSON_CreateObject(); + if (msg == NULL) { + LOGE("failed to create cjson object"); + return ""; + } + + ToJson(msg, *this); + char *retStr = cJSON_PrintUnformatted(msg); + if (retStr == nullptr) { + LOGE("to json is nullptr."); + cJSON_Delete(msg); + return ""; + } + std::string ret = std::string(retStr); + cJSON_Delete(msg); + cJSON_free(retStr); + return ret; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d2c88dcb4affee8b06cdef920e742b4a901f90a --- /dev/null +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -0,0 +1,625 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "relationship_sync_mgr.h" + +#include +#include +#include "dm_anonymous.h" +#include "dm_crypto.h" +#include "dm_log.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { + DM_IMPLEMENT_SINGLE_INSTANCE(ReleationShipSyncMgr); +namespace { + /** + * @brief account logout payload length 8 bytes + * | 2 bytes | 6 bytes | + * | userid lower 2 bytes | account id first 6 bytes | + */ + const int32_t ACCOUNT_LOGOUT_PAYLOAD_LEN = 8; + /** + * @brief device unbind payload length 2 bytes + * | 2 bytes | + * | userid lower 2 bytes | + */ + const int32_t DEVICE_UNBIND_PAYLOAD_LEN = 2; + /** + * @brief app unbind payload length 6 bytes + * | 2 bytes | 4 bytes | + * | userid lower 2 bytes | token id lower 4 bytes | + */ + const int32_t APP_UNBIND_PAYLOAD_LEN = 6; + /** + * @brief delete user payload length 2 bytes + * | 2 bytes | + * | userid lower 2 bytes | + */ + const int32_t DEL_USER_PAYLOAD_LEN = 2; + /** + * @brief the userid payload cost 2 bytes. + * + */ + const int32_t USERID_PAYLOAD_LEN = 2; + const int32_t ACCOUNTID_PAYLOAD_LEN = 6; + const int32_t SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MAX_LEN = 11; + const int32_t SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MIN_LEN = 3; + const int32_t USERID_BYTES = 2; + const int32_t BITS_PER_BYTE = 8; + const int32_t INVALIED_PAYLOAD_SIZE = 12; + + const char * const MSG_TYPE = "TYPE"; + const char * const MSG_VALUE = "VALUE"; + const char * const MSG_PEER_UDID = "PEER_UDID"; + const char * const MSG_ACCOUNTID = "ACCOUNTID"; + + // The need response mask offset, the 8th bit. + const int32_t NEED_RSP_MASK_OFFSET = 7; + /** + * @brief The userid cost 2 byte, the heigher part set on the 2th byte. + * The Max user id is just above 10000+, cost 15bits. We use the first bit + * to mark the user id foreground or background. + * 1 means foreground user, 0 means background user. + * @example foreground userid: 100 -> 0000 0000 0110 0100 + * we save it in payload: + * |----first byte----|----second byte----| + * ---------------------------------------- + * | 0110 0100 | 1000 0000 | + */ + const int32_t FRONT_OR_BACK_USER_FLAG_OFFSET = 7; + const uint8_t FRONT_OR_BACK_USER_FLAG_MASK = 0b01111111; + const uint8_t FRONT_OR_BACK_FLAG_MASK = 0b10000000; + // The total number of foreground and background userids offset, the 3th ~ 5th bits. + const uint16_t ALL_USERID_NUM_MASK_OFFSET = 3; + const uint16_t FOREGROUND_USERID_LEN_MASK = 0b00000111; + const uint16_t ALL_USERID_NUM_MASK = 0b00111000; + const uint32_t MAX_MEM_MALLOC_SIZE = 4 * 1024; +} + +RelationShipChangeMsg::RelationShipChangeMsg() : type(RelationShipChangeType::TYPE_MAX), + userId(UINT32_MAX), accountId(""), tokenId(UINT64_MAX), peerUdids({}), peerUdid(""), accountName(""), + syncUserIdFlag(false), userIdInfos({}) +{ +} + +bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) const +{ + if (!IsValid()) { + LOGE("invalid"); + return false; + } + + bool ret = false; + switch (type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + ToAccountLogoutPayLoad(msg, len); + ret = true; + break; + case RelationShipChangeType::DEVICE_UNBIND: + ToDeviceUnbindPayLoad(msg, len); + ret = true; + break; + case RelationShipChangeType::APP_UNBIND: + ToAppUnbindPayLoad(msg, len); + ret = true; + break; + case RelationShipChangeType::SYNC_USERID: + ret = ToSyncFrontOrBackUserIdPayLoad(msg, len); + break; + case RelationShipChangeType::DEL_USER: + ToDelUserPayLoad(msg, len); + ret = true; + break; + default: + LOGE("RelationShipChange type invalid"); + break; + } + return ret; +} + +bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, RelationShipChangeType type) +{ + LOGI("FromBroadcastPayLoad type %{public}d.", type); + if (type == RelationShipChangeType::TYPE_MAX) { + LOGE("ChangeType invalid, type: %{public}d", type); + return false; + } + bool ret = false; + switch (type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + ret = FromAccountLogoutPayLoad(payloadJson); + break; + case RelationShipChangeType::DEVICE_UNBIND: + ret = FromDeviceUnbindPayLoad(payloadJson); + break; + case RelationShipChangeType::APP_UNBIND: + ret = FromAppUnbindPayLoad(payloadJson); + break; + case RelationShipChangeType::SYNC_USERID: + ret = FromSyncFrontOrBackUserIdPayLoad(payloadJson); + break; + case RelationShipChangeType::DEL_USER: + ret = FromDelUserPayLoad(payloadJson); + break; + default: + LOGE("RelationShipChange type invalid"); + break; + } + return ret; +} + +bool RelationShipChangeMsg::IsValid() const +{ + bool ret = false; + switch (type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + ret = (userId != UINT32_MAX && accountId.length() >= ACCOUNTID_PAYLOAD_LEN); + break; + case RelationShipChangeType::DEVICE_UNBIND: + ret = (userId != UINT32_MAX); + break; + case RelationShipChangeType::APP_UNBIND: + ret = (userId != UINT32_MAX && tokenId != UINT64_MAX); + break; + case RelationShipChangeType::DEL_USER: + ret = (userId != UINT32_MAX); + break; + case RelationShipChangeType::SERVICE_UNBIND: + case RelationShipChangeType::APP_UNINSTALL: + // current NOT support + ret = false; + break; + case RelationShipChangeType::SYNC_USERID: + ret = (!userIdInfos.empty() && + (static_cast(userIdInfos.size()) <= MAX_USER_ID_NUM)); + break; + case RelationShipChangeType::TYPE_MAX: + ret = false; + break; + default: + ret = false; + break; + } + return ret; +} + +bool RelationShipChangeMsg::IsChangeTypeValid() +{ + return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || + (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_USERID) || + (type == RelationShipChangeType::DEL_USER); +} + +bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) +{ + return (type == (uint32_t)RelationShipChangeType::ACCOUNT_LOGOUT) || + (type == (uint32_t)RelationShipChangeType::DEVICE_UNBIND) || + (type == (uint32_t)RelationShipChangeType::APP_UNBIND) || + (type == (uint32_t)RelationShipChangeType::SYNC_USERID) || + (type == (uint32_t)RelationShipChangeType::DEL_USER); +} + +void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const +{ + msg = new uint8_t[ACCOUNT_LOGOUT_PAYLOAD_LEN](); + for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; + } + + for (int j = USERID_PAYLOAD_LEN; j < ACCOUNT_LOGOUT_PAYLOAD_LEN; j++) { + msg[j] = accountId[j - USERID_PAYLOAD_LEN]; + } + len = ACCOUNT_LOGOUT_PAYLOAD_LEN; +} + +void RelationShipChangeMsg::ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const +{ + msg = new uint8_t[DEVICE_UNBIND_PAYLOAD_LEN](); + for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; + } + len = DEVICE_UNBIND_PAYLOAD_LEN; +} + +void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const +{ + msg = new uint8_t[APP_UNBIND_PAYLOAD_LEN](); + for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; + } + + for (int i = USERID_PAYLOAD_LEN; i < APP_UNBIND_PAYLOAD_LEN; i++) { + msg[i] |= (tokenId >> ((i - USERID_PAYLOAD_LEN) * BITS_PER_BYTE)) & 0xFF; + } + + len = APP_UNBIND_PAYLOAD_LEN; +} + +bool RelationShipChangeMsg::ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const +{ + uint32_t userIdNum = static_cast(userIdInfos.size()); + if (userIdNum > MAX_USER_ID_NUM) { + LOGE("userIdNum too many, %{public}u", userIdNum); + return false; + } + + len = userIdNum * USERID_BYTES + 1; + + if (len > MAX_MEM_MALLOC_SIZE) { + LOGE("len too long"); + return false; + } + msg = new uint8_t[len](); + if (syncUserIdFlag) { + msg[0] |= 0x1 << NEED_RSP_MASK_OFFSET; + } else { + msg[0] |= 0x0 << NEED_RSP_MASK_OFFSET; + } + + msg[0] |= userIdNum; + int32_t userIdIdx = 0; + for (uint32_t idx = 1; idx <= (len - USERID_BYTES);) { + msg[idx] |= userIdInfos[userIdIdx].userId & 0xFF; + msg[idx + 1] |= (userIdInfos[userIdIdx].userId >> BITS_PER_BYTE) & 0xFF; + if (userIdInfos[userIdIdx].isForeground) { + msg[idx + 1] |= (0x1 << FRONT_OR_BACK_USER_FLAG_OFFSET); + } + idx += USERID_BYTES; + userIdIdx++; + } + return true; +} + +void RelationShipChangeMsg::ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const +{ + len = DEL_USER_PAYLOAD_LEN; + msg = new uint8_t[DEL_USER_PAYLOAD_LEN](); + for (int i = 0; i < DEL_USER_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; + } +} + +bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("Account logout payloadJson is null."); + return false; + } + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { + LOGE("Payload invalied,the size is %{public}d.", arraySize); + return false; + } + userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); + } + } + accountId = ""; + for (uint32_t j = USERID_PAYLOAD_LEN; j < ACCOUNT_LOGOUT_PAYLOAD_LEN; j++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, j); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + accountId += static_cast(payloadItem->valueint); + } + } + return true; +} + +bool RelationShipChangeMsg::FromDeviceUnbindPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("Device unbind payloadJson is null."); + return false; + } + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { + LOGE("Payload invalied,the size is %{public}d.", arraySize); + return false; + } + userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); + } + } + return true; +} + +bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("App unbind payloadJson is null."); + return false; + } + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { + LOGE("Payload invalied,the size is %{public}d.", arraySize); + return false; + } + userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); + } + } + tokenId = 0; + for (uint32_t j = USERID_PAYLOAD_LEN; j < APP_UNBIND_PAYLOAD_LEN; j++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, j); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + tokenId |= (static_cast(payloadItem->valueint)) << ((j - USERID_PAYLOAD_LEN) * BITS_PER_BYTE); + } + } + return true; +} + +bool RelationShipChangeMsg::FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("payloadJson is null."); + return false; + } + + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MIN_LEN || + arraySize > SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MAX_LEN) { + LOGE("Payload invalid, the size is %{public}d.", arraySize); + return false; + } + + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, 0); + CHECK_NULL_RETURN(payloadItem, false); + uint32_t userIdNum = 0; + if (cJSON_IsNumber(payloadItem)) { + uint8_t val = static_cast(payloadItem->valueint); + this->syncUserIdFlag = (((val >> NEED_RSP_MASK_OFFSET) & 0x1) == 0x1); + userIdNum = ((static_cast(payloadItem->valueint)) & FOREGROUND_USERID_LEN_MASK); + } + + int32_t effectiveLen = userIdNum * USERID_BYTES + 1; + if (effectiveLen > arraySize) { + LOGE("payload userIdNum invalid, userIdNum: %{public}u, arraySize: %{public}d", userIdNum, arraySize); + return false; + } + + uint16_t tempUserId = 0; + bool isForegroundUser = false; + for (int32_t idx = 1; idx < effectiveLen; idx++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, idx); + CHECK_NULL_RETURN(payloadItem, false); + if (!cJSON_IsNumber(payloadItem)) { + LOGE("Payload invalid, user id not integer"); + return false; + } + if ((idx - 1) % USERID_BYTES == 0) { + tempUserId |= (static_cast(payloadItem->valueint)); + } + if ((idx - 1) % USERID_BYTES == 1) { + tempUserId |= (static_cast(payloadItem->valueint) << BITS_PER_BYTE); + tempUserId &= FRONT_OR_BACK_USER_FLAG_MASK; + isForegroundUser = (((static_cast(payloadItem->valueint) & FRONT_OR_BACK_FLAG_MASK) >> + FRONT_OR_BACK_USER_FLAG_OFFSET) == 0b1); + UserIdInfo userIdInfo(isForegroundUser, tempUserId); + this->userIdInfos.push_back(userIdInfo); + tempUserId = 0; + isForegroundUser = false; + } + } + return true; +} + +bool RelationShipChangeMsg::FromDelUserPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("FromDelUserPayLoad payloadJson is null."); + return false; + } + + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < DEL_USER_PAYLOAD_LEN) { + LOGE("Payload invalid, the size is %{public}d.", arraySize); + return false; + } + this->userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + this->userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); + } + } + return true; +} + +cJSON *RelationShipChangeMsg::ToPayLoadJson() const +{ + uint8_t *payload = nullptr; + uint32_t len = 0; + if (!this->ToBroadcastPayLoad(payload, len)) { + LOGE("Get broadcast payload failed"); + return nullptr; + } + cJSON *arrayObj = cJSON_CreateArray(); + if (arrayObj == nullptr) { + LOGE("cJSON_CreateArray failed"); + if (payload != nullptr) { + delete[] payload; + } + return nullptr; + } + for (uint32_t index = 0; index < len; index++) { + cJSON_AddItemToArray(arrayObj, cJSON_CreateNumber(payload[index])); + } + if (payload != nullptr) { + delete[] payload; + } + return arrayObj; +} + +std::string RelationShipChangeMsg::ToJson() const +{ + cJSON *msg = cJSON_CreateObject(); + if (msg == NULL) { + LOGE("failed to create cjson object"); + return ""; + } + cJSON_AddNumberToObject(msg, MSG_TYPE, (uint32_t)type); + cJSON *arrayObj = ToPayLoadJson(); + if (arrayObj == nullptr) { + LOGE("ArrayObj is nullptr."); + cJSON_Delete(msg); + return ""; + } + cJSON_AddItemToObject(msg, MSG_VALUE, arrayObj); + + cJSON *udidArrayObj = cJSON_CreateArray(); + if (udidArrayObj == nullptr) { + LOGE("cJSON_CreateArray failed"); + cJSON_Delete(msg); + return ""; + } + for (uint32_t index = 0; index < peerUdids.size(); index++) { + cJSON_AddItemToArray(udidArrayObj, cJSON_CreateString(peerUdids[index].c_str())); + } + cJSON_AddItemToObject(msg, MSG_PEER_UDID, udidArrayObj); + cJSON_AddStringToObject(msg, MSG_ACCOUNTID, accountName.c_str()); + char *retStr = cJSON_PrintUnformatted(msg); + if (retStr == nullptr) { + LOGE("to json is nullptr."); + cJSON_Delete(msg); + return ""; + } + std::string ret = std::string(retStr); + cJSON_Delete(msg); + cJSON_free(retStr); + return ret; +} + +bool RelationShipChangeMsg::FromJson(const std::string &msgJson) +{ + cJSON *msgObj = cJSON_Parse(msgJson.c_str()); + if (msgObj == NULL) { + LOGE("parse msg failed"); + return false; + } + + cJSON *typeJson = cJSON_GetObjectItem(msgObj, MSG_TYPE); + if (typeJson == NULL || !cJSON_IsNumber(typeJson) || !IsChangeTypeValid(typeJson->valueint)) { + LOGE("parse type failed."); + cJSON_Delete(msgObj); + return false; + } + this->type = (RelationShipChangeType)typeJson->valueint; + + cJSON *payloadJson = cJSON_GetObjectItem(msgObj, MSG_VALUE); + if (payloadJson == NULL || !cJSON_IsArray(payloadJson)) { + LOGE("parse payload failed."); + cJSON_Delete(msgObj); + return false; + } + if (!this->FromBroadcastPayLoad(payloadJson, type)) { + LOGE("parse payload error."); + cJSON_Delete(msgObj); + return false; + } + + cJSON *peerUdidJson = cJSON_GetObjectItem(msgObj, MSG_PEER_UDID); + if (peerUdidJson == NULL || !cJSON_IsString(peerUdidJson)) { + LOGE("parse peer udid failed."); + cJSON_Delete(msgObj); + return false; + } + this->peerUdid = std::string(peerUdidJson->valuestring); + cJSON_Delete(msgObj); + return true; +} + +std::string ReleationShipSyncMgr::SyncTrustRelationShip(const RelationShipChangeMsg &msg) +{ + return msg.ToJson(); +} + +RelationShipChangeMsg ReleationShipSyncMgr::ParseTrustRelationShipChange(const std::string &msgJson) +{ + RelationShipChangeMsg msgObj; + if (!msgObj.FromJson(msgJson)) { + LOGE("Parse json failed"); + } + return msgObj; +} + +const std::string RelationShipChangeMsg::ToString() const +{ + std::string ret; + ret += "{ MsgType: " + std::to_string(static_cast(type)); + ret += ", userId: " + std::to_string(userId); + ret += ", accountId: " + GetAnonyString(accountId); + ret += ", tokenId: " + std::to_string(tokenId); + ret += ", peerUdids: " + GetAnonyStringList(peerUdids); + ret += ", peerUdid: " + GetAnonyString(peerUdid); + ret += ", accountName: " + GetAnonyString(accountName); + ret += ", syncUserIdFlag: " + std::to_string(syncUserIdFlag); + ret += ", userIds: " + GetUserIdInfoList(userIdInfos) + " }"; + return ret; +} + +const std::string UserIdInfo::ToString() const +{ + std::string ret; + ret += "{ " + std::to_string(this->isForeground); + ret += ", userId: " + std::to_string(this->userId) + " }"; + return ret; +} + +const std::string GetUserIdInfoList(const std::vector &list) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &userId : list) { + temp += userId.ToString() + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + +void GetFrontAndBackUserIdInfos(const std::vector &remoteUserIdInfos, + std::vector &foregroundUserIdInfos, std::vector &backgroundUserIdInfos) +{ + foregroundUserIdInfos.clear(); + backgroundUserIdInfos.clear(); + for (auto const &u : remoteUserIdInfos) { + if (u.isForeground) { + foregroundUserIdInfos.push_back(u); + } else { + backgroundUserIdInfos.push_back(u); + } + } +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/softbus/mine_softbus_listener.cpp b/services/service/src/softbus/mine_softbus_listener.cpp index 345d62217d81c332c1bfd936f4b6e35f0ee0ca0f..db86dab66d03c63ca5db8d465c7faba6b5057540 100644 --- a/services/service/src/softbus/mine_softbus_listener.cpp +++ b/services/service/src/softbus/mine_softbus_listener.cpp @@ -401,13 +401,13 @@ int32_t MineSoftbusListener::ParseScopeDeviceJsonArray(const vector -#include -#include "dm_log.h" -#include "softbus_bus_center.h" -#include "softbus_common.h" -#include "device_manager_service.h" -namespace OHOS { -namespace DistributedHardware { -namespace { -static QosTV g_qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, -}; -static uint32_t g_qosTVParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); -} -DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusAdapter); -static void DmOnSoftbusSessionBind(int32_t socket, PeerSocketInfo info) -{ - SoftbusAdapter::GetInstance().OnSoftbusSessionOpened(socket, info); -} - -static void DmOnSoftbusSessionClosed(int32_t socket, ShutdownReason reason) -{ - SoftbusAdapter::GetInstance().OnSoftbusSessionClosed(socket, reason); -} - -static void DmOnBytesReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - SoftbusAdapter::GetInstance().OnBytesReceived(socket, data, dataLen); -} - -static void DmOnStreamReceived(int32_t socket, const StreamData *data, const StreamData *ext, - const StreamFrameInfo *frameInfo) -{ - SoftbusAdapter::GetInstance().OnStreamReceived(socket, data, ext, frameInfo); -} - -static void DmOnMessageReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - SoftbusAdapter::GetInstance().OnMessageReceived(socket, data, dataLen); -} - -static void DmOnQosEvent(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) -{ - SoftbusAdapter::GetInstance().OnQosEvent(socket, eventId, qos, qosCount); -} - -SoftbusAdapter::SoftbusAdapter() -{ - LOGI("SoftbusAdapter"); - (void)memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)); - iSocketListener_.OnBind = DmOnSoftbusSessionBind; - iSocketListener_.OnShutdown = DmOnSoftbusSessionClosed; - iSocketListener_.OnBytes = DmOnBytesReceived; - iSocketListener_.OnMessage = DmOnMessageReceived; - iSocketListener_.OnStream = DmOnStreamReceived; - iSocketListener_.OnQos = DmOnQosEvent; - iSocketListener_.OnFile = nullptr; - iSocketListener_.OnError = nullptr; - iSocketListener_.OnNegotiate = nullptr; -} - -SoftbusAdapter::~SoftbusAdapter() -{ - LOGI("~SoftbusAdapter"); -} - -int32_t SoftbusAdapter::CreateSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName) -{ - LOGI("SoftbusAdapter::CreateSoftbusSessionServer."); - SocketInfo info = { - .name = const_cast(sessionName.c_str()), - .pkgName = const_cast(pkgname.c_str()), - .dataType = DATA_TYPE_BYTES - }; - int32_t socket = Socket(info); - if (socket <= 0) { - LOGE("[SOFTBUS]create socket failed, socket: %{public}d", socket); - return socket; - } - int32_t ret = Listen(socket, g_qosInfo, g_qosTVParamIndex, &iSocketListener_); - if (ret != DM_OK) { - LOGE("[SOFTBUS]Socket Listen failed, ret: %{public}d, socket: %{public}d.", ret, socket); - Shutdown(socket); - return ret; - } - LOGI("SoftbusAdapter::CreateSoftbusSessionServer success."); - return DM_OK; -} - -int32_t SoftbusAdapter::RemoveSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName) -{ - LOGI("SoftbusAdapter::RemoveSoftbusSessionServer"); - int32_t ret = RemoveSessionServer(pkgname.c_str(), sessionName.c_str()); - if (ret != DM_OK) { - LOGE("RemoveSoftbusSessionServer failed."); - return ret; - } - LOGI("SoftbusAdapter::RemoveSoftbusSessionServer success."); - return DM_OK; -} - -void SoftbusAdapter::OnSoftbusSessionOpened(int32_t socket, PeerSocketInfo info) -{ - LOGI("SoftbusAdapter::OnSoftbusSessionOpened socket: %{public}d", socket); - DeviceManagerService::GetInstance().OnUnbindSessionOpened(socket, info); -} - -void SoftbusAdapter::OnSoftbusSessionClosed(int32_t socket, ShutdownReason reason) -{ - (void)reason; - LOGI("SoftbusAdapter::OnSoftbusSessionClosed socket: %{public}d", socket); - DeviceManagerService::GetInstance().OnUnbindSessionCloseed(socket); -} - -void SoftbusAdapter::OnBytesReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - LOGI("SoftbusAdapter::OnBytesReceived socket: %{public}d", socket); - DeviceManagerService::GetInstance().OnUnbindBytesReceived(socket, data, dataLen); -} - -void SoftbusAdapter::OnStreamReceived(int32_t socket, const StreamData *data, const StreamData *ext, - const StreamFrameInfo *frameInfo) -{ - (void)data; - (void)ext; - (void)frameInfo; - LOGI("SoftbusAdapter::OnStreamReceived, socket: %{public}d", socket); -} - -void SoftbusAdapter::OnMessageReceived(int32_t socket, const void *data, unsigned int dataLen) const -{ - (void)data; - (void)dataLen; - LOGI("SoftbusAdapter::OnMessageReceived, socket: %{public}d", socket); -} - -void SoftbusAdapter::OnQosEvent(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) const -{ - (void)eventId; - (void)qos; - (void)qosCount; - LOGI("SoftbusAdapter::OnQosEvent, socket: %{public}d", socket); -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 937e8b832d6f80905aa11de7e70164f7991c59c6..d528c2494b693f82708cc1207eee9b13c40a5cb7 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -23,15 +23,17 @@ #include #include "device_manager_service.h" -#include "dm_anonymous.h" #include "dm_crypto.h" #include "dm_constants.h" #include "dm_device_info.h" #include "dm_log.h" #include "dm_softbus_cache.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_transport_msg.h" +#include "ffrt.h" +#endif #include "parameter.h" #include "system_ability_definition.h" -#include "softbus_adapter.cpp" namespace OHOS { namespace DistributedHardware { @@ -40,24 +42,33 @@ const int32_t SOFTBUS_CHECK_INTERVAL = 100000; // 100ms const int32_t SOFTBUS_SUBSCRIBE_ID_MASK = 0x0000FFFF; const int32_t MAX_CACHED_DISCOVERED_DEVICE_SIZE = 100; const int32_t MAX_SOFTBUS_MSG_LEN = 2000; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEVICE_ONLINE = "deviceOnLine"; constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; -constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; +constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; +constexpr const char* CREDENTIAL_AUTH_STATUS = "credentialAuthStatus"; +#endif +constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; constexpr static uint8_t BYTE_MASK = 0x0F; constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2; constexpr static uint16_t BIN_HIGH_FOUR_NUM = 4; +constexpr uint32_t SOFTBUS_MAX_RETRY_TIME = 10; static std::mutex g_deviceMapMutex; static std::mutex g_lnnCbkMapMutex; static std::mutex g_radarLoadLock; static std::mutex g_onlineDeviceNumLock; -static std::mutex g_lockDeviceNotTrust; +static std::mutex g_lockDeviceTrustedChange; +static std::mutex g_lockUserIdCheckSumChange; static std::mutex g_lockDeviceOnLine; static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; +static std::mutex g_lockDeviceIdSet; +static std::mutex g_lockDevScreenStatusChange; +static std::mutex g_credentialAuthStatus; static std::map>>> discoveredDeviceMap; static std::map> lnnOpsCbkMap; @@ -66,21 +77,10 @@ bool SoftbusListener::isRadarSoLoad_ = false; IDmRadarHelper* SoftbusListener::dmRadarHelper_ = nullptr; void* SoftbusListener::radarHandle_ = nullptr; std::string SoftbusListener::hostName_ = ""; -int32_t g_onlinDeviceNum = 0; +int32_t g_onlineDeviceNum = 0; static int OnSessionOpened(int sessionId, int result) { - struct RadarInfo info = { - .funcName = "OnSessionOpened", - .stageRes = static_cast(StageRes::STAGE_SUCC), - .isTrust = static_cast(TrustStatus::NOT_TRUST), - .channelId = sessionId, - }; - if (SoftbusListener::IsDmRadarHelperReady() && SoftbusListener::GetDmRadarHelperObj() != nullptr) { - if (!SoftbusListener::GetDmRadarHelperObj()->ReportAuthSessionOpenCb(info)) { - LOGE("ReportAuthSessionOpenCb failed"); - } - } return DeviceManagerService::GetInstance().OnSessionOpened(sessionId, result); } @@ -114,12 +114,15 @@ static IPublishCb softbusPublishCallback_ = { }; static INodeStateCb softbusNodeStateCb_ = { - .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED, + .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED | + EVENT_NODE_STATUS_CHANGED | EVENT_NODE_HICHAIN_PROOF_EXCEPTION, .onNodeOnline = SoftbusListener::OnSoftbusDeviceOnline, .onNodeOffline = SoftbusListener::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusListener::OnSoftbusDeviceInfoChanged, .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, - .onNodeDeviceNotTrusted = SoftbusListener::OnDeviceNotTrusted, + .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, + .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, + .onHichainProofException = SoftbusListener::OnCredentialAuthStatus, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -147,10 +150,92 @@ void SoftbusListener::DeviceNameChange(DmDeviceInfo deviceInfo) void SoftbusListener::DeviceNotTrust(const std::string &msg) { - std::lock_guard lock(g_lockDeviceNotTrust); + std::lock_guard lock(g_lockDeviceTrustedChange); DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); } +void SoftbusListener::DeviceTrustedChange(const std::string &msg) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::lock_guard lock(g_lockDeviceTrustedChange); + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); +#else + (void)msg; +#endif +} + +void SoftbusListener::DeviceUserIdCheckSumChange(const std::string &msg) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::lock_guard lock(g_lockUserIdCheckSumChange); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); +#else + (void)msg; +#endif +} + +void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) +{ + std::lock_guard lock(g_lockDevScreenStatusChange); + DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); +} + +void SoftbusListener::CredentialAuthStatusProcess(std::string deviceList, uint16_t deviceTypeId, int32_t errcode) +{ + std::lock_guard lock(g_credentialAuthStatus); + DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); +} + +void SoftbusListener::OnCredentialAuthStatus(const char *deviceList, uint32_t deviceListLen, + uint16_t deviceTypeId, int32_t errcode) +{ + LOGI("received credential auth status callback from softbus."); + if (deviceListLen > MAX_SOFTBUS_MSG_LEN) { + LOGE("[SOFTBUS]received invaild deviceList value."); + return; + } + std::string deviceListStr; + if (deviceList != nullptr) { + deviceListStr = std::string(deviceList, deviceListLen); + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { CredentialAuthStatusProcess(deviceListStr, deviceTypeId, errcode); }); +#else + std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceListStr, deviceTypeId, errcode); }); + if (pthread_setname_np(credentialAuthStatus.native_handle(), CREDENTIAL_AUTH_STATUS) != DM_OK) { + LOGE("credentialAuthStatus setname failed."); + } + credentialAuthStatus.detach(); +#endif +} + +void SoftbusListener::OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status) +{ + LOGI("received device screen status change callback from softbus."); + if (status == nullptr) { + LOGE("[SOFTBUS]status is nullptr, type = %{public}d", static_cast(type)); + return; + } + LOGI("screenStatusChanged networkId: %{public}s, screenStatus: %{public}d", + GetAnonyString(status->basicInfo.networkId).c_str(), static_cast(status->reserved[0])); + if (type != NodeStatusType::TYPE_SCREEN_STATUS) { + LOGE("type is not matching."); + return; + } + DmDeviceInfo dmDeviceInfo; + int32_t devScreenStatus = static_cast(status->reserved[0]); + ConvertScreenStatusToDmDevice(status->basicInfo, devScreenStatus, dmDeviceInfo); + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { DeviceScreenStatusChange(dmDeviceInfo); }); + #else + std::thread devScreenStatusChange([=]() { DeviceScreenStatusChange(dmDeviceInfo); }); + if (pthread_setname_np(devScreenStatusChange.native_handle(), DEVICE_SCREEN_STATUS_CHANGE) != DM_OK) { + LOGE("devScreenStatusChange setname failed."); + } + devScreenStatusChange.detach(); + #endif +} + void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) { LOGI("received device online callback from softbus."); @@ -166,17 +251,19 @@ void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) SoftbusCache::GetInstance().SaveLocalDeviceInfo(); { std::lock_guard lock(g_onlineDeviceNumLock); - g_onlinDeviceNum++; + g_onlineDeviceNum++; } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { DeviceOnLine(dmDeviceInfo); }); +#else std::thread deviceOnLine([=]() { DeviceOnLine(dmDeviceInfo); }); int32_t ret = pthread_setname_np(deviceOnLine.native_handle(), DEVICE_ONLINE); if (ret != DM_OK) { LOGE("deviceOnLine setname failed."); } deviceOnLine.detach(); +#endif { - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string peerUdid; GetUdidByNetworkId(info->networkId, peerUdid); struct RadarInfo radarInfo = { @@ -185,7 +272,6 @@ void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) .bizState = static_cast(BizState::BIZ_STATE_START), .isTrust = static_cast(TrustStatus::IS_TRUST), .peerNetId = info->networkId, - .localUdid = std::string(localDeviceId), .peerUdid = peerUdid, }; if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { @@ -209,21 +295,23 @@ void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info) SoftbusCache::GetInstance().DeleteDeviceSecurityLevel(dmDeviceInfo.networkId); { std::lock_guard lock(g_onlineDeviceNumLock); - g_onlinDeviceNum--; - if (g_onlinDeviceNum == 0) { + g_onlineDeviceNum--; + if (g_onlineDeviceNum == 0) { SoftbusCache::GetInstance().DeleteLocalDeviceInfo(); } } LOGI("device offline networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str()); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { DeviceOffLine(dmDeviceInfo); }); +#else std::thread deviceOffLine([=]() { DeviceOffLine(dmDeviceInfo); }); int32_t ret = pthread_setname_np(deviceOffLine.native_handle(), DEVICE_OFFLINE); if (ret != DM_OK) { LOGE("deviceOffLine setname failed."); } deviceOffLine.detach(); +#endif { - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string peerUdid; GetUdidByNetworkId(info->networkId, peerUdid); struct RadarInfo radarInfo = { @@ -231,7 +319,6 @@ void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info) .stageRes = static_cast(StageRes::STAGE_SUCC), .bizState = static_cast(BizState::BIZ_STATE_END), .peerNetId = info->networkId, - .localUdid = std::string(localDeviceId), .peerUdid = peerUdid, }; if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { @@ -265,11 +352,15 @@ void SoftbusListener::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBas LOGI("device changed networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str()); dmDeviceInfo.networkType = networkType; SoftbusCache::GetInstance().ChangeDeviceInfo(dmDeviceInfo); + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { DeviceNameChange(dmDeviceInfo); }); + #else std::thread deviceInfoChange([=]() { DeviceNameChange(dmDeviceInfo); }); if (pthread_setname_np(deviceInfoChange.native_handle(), DEVICE_NAME_CHANGE) != DM_OK) { LOGE("DeviceNameChange setname failed."); } deviceInfoChange.detach(); + #endif } } @@ -279,21 +370,50 @@ void SoftbusListener::OnLocalDevInfoChange() SoftbusCache::GetInstance().UpDataLocalDevInfo(); } -void SoftbusListener::OnDeviceNotTrusted(const char *msg) +void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen) { - LOGI("SoftbusListener::OnDeviceNotTrusted."); - - if (msg == nullptr || strlen(msg) > MAX_SOFTBUS_MSG_LEN) { - LOGE("OnDeviceNotTrusted msg invalied."); + LOGI("OnDeviceTrustedChange."); + if (msg == nullptr || msgLen > MAX_SOFTBUS_MSG_LEN || strlen(msg) != msgLen) { + LOGE("OnDeviceTrustedChange msg invalied."); return; } - std::string softbusMsg = std::string(msg); - std::thread deviceNotTrust([=]() { DeviceNotTrust(softbusMsg); }); - int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); - if (ret != DM_OK) { - LOGE("deviceNotTrust setname failed."); + std::string softbusMsg = std::string(msg, msgLen); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (type == TrustChangeType::DEVICE_NOT_TRUSTED) { + ffrt::submit([=]() { DeviceNotTrust(softbusMsg); }); + } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { + ffrt::submit([=]() { DeviceTrustedChange(softbusMsg); }); + } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { + ffrt::submit([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); + } else { + LOGE("Invalied trust change type."); + } +#else + if (type == TrustChangeType::DEVICE_NOT_TRUSTED) { + std::thread deviceNotTrust([=]() { DeviceNotTrust(softbusMsg); }); + int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); + if (ret != DM_OK) { + LOGE("deviceNotTrust setname failed."); + } + deviceNotTrust.detach(); + } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { + std::thread deviceTrustedChange([=]() { DeviceTrustedChange(softbusMsg); }); + int32_t ret = pthread_setname_np(deviceTrustedChange.native_handle(), DEVICE_NOT_TRUST); + if (ret != DM_OK) { + LOGE("deviceTrustedChange setname failed."); + } + deviceTrustedChange.detach(); + } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { + std::thread deviceUserIdCheckSumChange([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); + int32_t ret = pthread_setname_np(deviceUserIdCheckSumChange.native_handle(), DEVICE_NOT_TRUST); + if (ret != DM_OK) { + LOGE("deviceUserIdCheckSumChange setname failed."); + } + deviceUserIdCheckSumChange.detach(); + } else { + LOGE("Invalied trust change type."); } - deviceNotTrust.detach(); +#endif } void SoftbusListener::OnSoftbusDeviceFound(const DeviceInfo *device) @@ -304,21 +424,24 @@ void SoftbusListener::OnSoftbusDeviceFound(const DeviceInfo *device) } DmDeviceInfo dmDevInfo; ConvertDeviceInfoToDmDevice(*device, dmDevInfo); - if (deviceIdSet.find(std::string(dmDevInfo.deviceId)) == deviceIdSet.end()) { - deviceIdSet.insert(std::string(dmDevInfo.deviceId)); - struct RadarInfo info = { - .funcName = "OnSoftbusDeviceFound", - .stageRes = static_cast(StageRes::STAGE_SUCC), - .peerNetId = "", - .peerUdid = std::string(dmDevInfo.deviceId), - }; - if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { - if (!GetDmRadarHelperObj()->ReportDiscoverResCallback(info)) { - LOGE("ReportDiscoverResCallback failed"); + { + std::lock_guard lock(g_lockDeviceIdSet); + if (deviceIdSet.find(std::string(dmDevInfo.deviceId)) == deviceIdSet.end()) { + deviceIdSet.insert(std::string(dmDevInfo.deviceId)); + struct RadarInfo info = { + .funcName = "OnSoftbusDeviceFound", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .peerNetId = "", + .peerUdid = std::string(dmDevInfo.deviceId), + }; + if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { + if (!GetDmRadarHelperObj()->ReportDiscoverResCallback(info)) { + LOGE("ReportDiscoverResCallback failed"); + } } } } - LOGI("OnSoftbusDeviceFound: devId=%{public}s, devName=%{public}s, devType=%{public}d, range=%{public}d," + LOGI("DevId=%{public}s, devName=%{public}s, devType=%{public}d, range=%{public}d," "isOnline=%{public}d", GetAnonyString(dmDevInfo.deviceId).c_str(), GetAnonyString(dmDevInfo.deviceName).c_str(), dmDevInfo.deviceTypeId, dmDevInfo.range, device->isOnline); @@ -369,7 +492,6 @@ SoftbusListener::SoftbusListener() if (ret != DM_OK) { LOGE("[SOFTBUS]CreateSessionServer pin holder failed, ret: %{public}d.", ret); } - SoftbusAdapter::GetInstance().CreateSoftbusSessionServer(DM_PKG_NAME, DM_UNBIND_SESSION_NAME); #endif InitSoftbusListener(); ClearDiscoveredDevice(); @@ -380,7 +502,6 @@ SoftbusListener::~SoftbusListener() #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME); RemoveSessionServer(DM_PKG_NAME, DM_PIN_HOLDER_SESSION_NAME); - SoftbusAdapter::GetInstance().RemoveSoftbusSessionServer(DM_PKG_NAME, DM_UNBIND_SESSION_NAME); #endif LOGD("SoftbusListener destructor."); } @@ -388,16 +509,16 @@ SoftbusListener::~SoftbusListener() int32_t SoftbusListener::InitSoftbusListener() { int32_t ret; - int32_t retryTimes = 0; + uint32_t retryTimes = 0; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) do { ret = RegNodeDeviceStateCb(DM_PKG_NAME, &softbusNodeStateCb_); if (ret != DM_OK) { ++retryTimes; - LOGE("[SOFTBUS]RegNodeDeviceStateCb failed with ret: %{public}d, retryTimes: %{public}d.", ret, retryTimes); + LOGE("[SOFTBUS]RegNodeDeviceStateCb failed with ret: %{public}d, retryTimes: %{public}u.", ret, retryTimes); usleep(SOFTBUS_CHECK_INTERVAL); } - } while (ret != DM_OK); + } while (ret != DM_OK && retryTimes < SOFTBUS_MAX_RETRY_TIME); #endif return InitSoftPublishLNN(); } @@ -430,7 +551,11 @@ int32_t SoftbusListener::RefreshSoftbusLNN(const char *pkgName, const DmSubscrib { LOGI("RefreshSoftbusLNN begin, subscribeId: %{public}d.", dmSubInfo.subscribeId); SubscribeInfo subscribeInfo; - (void)memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + if (memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)) != DM_OK) { + LOGE("RefreshSoftbusLNN memset_s failed."); + return ERR_DM_FAILED; + } + subscribeInfo.subscribeId = dmSubInfo.subscribeId; subscribeInfo.mode = static_cast(dmSubInfo.mode); subscribeInfo.medium = static_cast(dmSubInfo.medium); @@ -471,7 +596,10 @@ int32_t SoftbusListener::RefreshSoftbusLNN(const char *pkgName, const DmSubscrib int32_t SoftbusListener::StopRefreshSoftbusLNN(uint16_t subscribeId) { LOGI("StopRefreshSoftbusLNN begin, subscribeId: %{public}d.", (int32_t)subscribeId); - deviceIdSet.clear(); + { + std::lock_guard lock(g_lockDeviceIdSet); + deviceIdSet.clear(); + } int32_t ret = ::StopRefreshLNN(DM_PKG_NAME, subscribeId); struct RadarInfo info = { .funcName = "StopRefreshSoftbusLNN", @@ -497,7 +625,7 @@ int32_t SoftbusListener::StopRefreshSoftbusLNN(uint16_t subscribeId) int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const std::string &capability, const std::string &customData) { - LOGI("PublishSoftbusLNN begin, publishId: %{public}d.", dmPubInfo.publishId); + LOGI("Begin, publishId: %{public}d.", dmPubInfo.publishId); PublishInfo publishInfo; publishInfo.publishId = dmPubInfo.publishId; publishInfo.mode = static_cast(dmPubInfo.mode); @@ -508,8 +636,8 @@ int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const publishInfo.dataLen = customData.length(); publishInfo.ranging = dmPubInfo.ranging; - LOGI("PublishSoftbusLNN begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:" - "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.publishId, publishInfo.mode, + LOGI("Begin, mode: 0x%{public}x, medium: %{public}d, capability:" + "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.mode, publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq); int32_t ret = ::PublishLNN(DM_PKG_NAME, &publishInfo, &softbusPublishCallback_); @@ -522,7 +650,7 @@ int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const int32_t SoftbusListener::StopPublishSoftbusLNN(int32_t publishId) { - LOGI("StopPublishSoftbusLNN begin, publishId: %{public}d.", publishId); + LOGI("Begin, publishId: %{public}d.", publishId); int32_t ret = ::StopPublishLNN(DM_PKG_NAME, publishId); if (ret != DM_OK) { LOGE("[SOFTBUS]StopPublishLNN failed, ret: %{public}d.", ret); @@ -554,23 +682,8 @@ int32_t SoftbusListener::UnRegisterSoftbusLnnOpsCbk(const std::string &pkgName) int32_t SoftbusListener::GetTrustedDeviceList(std::vector &deviceInfoList) { int32_t ret = SoftbusCache::GetInstance().GetDeviceInfoFromCache(deviceInfoList); - static size_t radarDeviceCount = 0; size_t deviceCount = deviceInfoList.size(); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - struct RadarInfo radarInfo = { - .localUdid = std::string(localDeviceId), - }; - radarInfo.stageRes = static_cast(StageRes::STAGE_SUCC); - if (radarDeviceCount != deviceCount && deviceCount > 0 - && IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { - radarDeviceCount = deviceCount; - radarInfo.discoverDevList = GetDmRadarHelperObj()->GetDeviceInfoList(deviceInfoList); - if (!GetDmRadarHelperObj()->ReportGetTrustDeviceList(radarInfo)) { - LOGE("ReportGetTrustDeviceList failed"); - } - } - LOGI("GetTrustedDeviceList success from cache deviceInfoList size is %{public}zu.", deviceCount); + LOGI("Success from cache deviceInfoList size is %{public}zu.", deviceCount); return ret; } @@ -594,14 +707,31 @@ int32_t SoftbusListener::GetUuidByNetworkId(const char *networkId, std::string & return SoftbusCache::GetInstance().GetUuidFromCache(networkId, uuid); } -int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp) +int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string &networkId) { + return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId); +} + +int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, + const std::string &localDisplayName) +{ + LOGI("SoftbusListener Start SetLocalDeviceName!"); + return DM_OK; +} + +int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId) +{ + if (callerId.empty()) { + LOGE("Invalid parameter, callerId is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGD("Begin for callerId = %{public}s", GetAnonyString(callerId).c_str()); GearMode mode = { .cycle = HIGH_FREQ_CYCLE, .duration = DEFAULT_DURATION, .wakeupFlag = isWakeUp, }; - int32_t ret = ::ShiftLNNGear(DM_PKG_NAME, DM_PKG_NAME, nullptr, &mode); + int32_t ret = ::ShiftLNNGear(DM_PKG_NAME, callerId.c_str(), nullptr, &mode); if (ret != DM_OK) { LOGE("[SOFTBUS]ShiftLNNGear error, failed ret: %{public}d", ret); return ret; @@ -609,17 +739,50 @@ int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp) return DM_OK; } -int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) +int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, + DmDeviceInfo &devInfo) { - (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); + return ERR_DM_FAILED; + } if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + return ERR_DM_FAILED; } if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + return ERR_DM_FAILED; + } + devInfo.deviceTypeId = nodeInfo.deviceTypeId; + nlohmann::json extraJson; + extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType; + extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN); + extraJson[DEVICE_SCREEN_STATUS] = devScreenStatus; + devInfo.extraData = to_string(extraJson); + return DM_OK; +} + +int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) +{ + LOGI("Begin, osType : %{public}d", nodeInfo.osType); + if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); + return ERR_DM_FAILED; + } + if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + return ERR_DM_FAILED; + } + + if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + return ERR_DM_FAILED; } devInfo.deviceTypeId = nodeInfo.deviceTypeId; nlohmann::json extraJson; @@ -631,16 +794,23 @@ int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nod int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceBasicInfo &devInfo) { - (void)memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); + return ERR_DM_FAILED; + } + if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + return ERR_DM_FAILED; } if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + return ERR_DM_FAILED; } + devInfo.deviceTypeId = nodeInfo.deviceTypeId; return DM_OK; } @@ -658,18 +828,33 @@ std::string SoftbusListener::ConvertBytesToUpperCaseHexString(const uint8_t arr[ return result; } -void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +int32_t SoftbusListener::FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice) { - (void)memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed."); + return ERR_DM_FAILED; + } if (memcpy_s(dmDevice.deviceId, sizeof(dmDevice.deviceId), device.devId, std::min(sizeof(dmDevice.deviceId), sizeof(device.devId))) != DM_OK) { LOGE("ConvertDeviceInfoToDmDevice: copy device id failed."); + return ERR_DM_FAILED; } if (memcpy_s(dmDevice.deviceName, sizeof(dmDevice.deviceName), device.devName, std::min(sizeof(dmDevice.deviceName), sizeof(device.devName))) != DM_OK) { LOGE("ConvertDeviceInfoToDmDevice: copy device name failed."); + return ERR_DM_FAILED; + } + + return DM_OK; +} + +void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +{ + if (FillDeviceInfo(device, dmDevice) != DM_OK) { + LOGE("FillDeviceInfo failed."); + return; } dmDevice.deviceTypeId = device.devType; @@ -682,10 +867,16 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe const ConnectionAddr *addrInfo = &(device.addr)[0]; if (addrInfo == nullptr) { LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); - dmDevice.extraData = jsonObj.dump(); + dmDevice.extraData = SafetyDump(jsonObj); return; } jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; + ParseConnAddrInfo(addrInfo, jsonObj); + dmDevice.extraData = SafetyDump(jsonObj); +} + +void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj) +{ if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { std::string wifiIp((addrInfo->info).ip.ip); jsonObj[PARAM_KEY_WIFI_IP] = wifiIp; @@ -707,10 +898,14 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe std::string udidHash(ConvertBytesToUpperCaseHexString((addrInfo->info).ble.udidHash, sizeof((addrInfo->info).ble.udidHash) / sizeof(*((addrInfo->info).ble.udidHash)))); jsonObj[PARAM_KEY_BLE_UDID_HASH] = udidHash; + } else if (addrInfo->type == CONNECTION_ADDR_USB) { + std::string usbIp((addrInfo->info).ip.ip); + jsonObj[PARAM_KEY_USB_IP] = usbIp; + jsonObj[PARAM_KEY_USB_PORT] = (addrInfo->info).ip.port; + jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_USB; } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } - dmDevice.extraData = jsonObj.dump(); } int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) @@ -805,18 +1000,15 @@ bool SoftbusListener::IsDmRadarHelperReady() { std::lock_guard lock(g_radarLoadLock); if (isRadarSoLoad_ && (dmRadarHelper_ != nullptr) && (radarHandle_ != nullptr)) { - LOGI("IsDmRadarHelperReady alReady."); + LOGD("IsDmRadarHelperReady alReady."); return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_RADAR_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; + radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW | RTLD_NOLOAD); + if (radarHandle_ == nullptr) { + radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW); } - radarHandle_ = dlopen(path, RTLD_NOW); if (radarHandle_ == nullptr) { - LOGE("load libdevicemanagerradar so %{public}s failed.", soName.c_str()); + LOGE("load libdevicemanagerradar so failed."); return false; } dlerror(); @@ -931,9 +1123,62 @@ std::string SoftbusListener::GetHostPkgName() return hostName_; } +void SoftbusListener::SendAclChangedBroadcast(const std::string &msg) +{ + LOGI("SendAclChangedBroadcast"); + if (SyncTrustedRelationShip(DM_PKG_NAME, msg.c_str(), msg.length()) != DM_OK) { + LOGE("SyncTrustedRelationShip failed."); + } +} + IRefreshCallback &SoftbusListener::GetSoftbusRefreshCb() { return softbusRefreshCallback_; } + +int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus) +{ + int32_t devScreenStatus = -1; + int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_DEVICE_SCREEN_STATUS, + reinterpret_cast(&devScreenStatus), LNN_COMMON_LEN); + if (ret != DM_OK) { + LOGE("[SOFTBUS]GetNodeKeyInfo screenStatus failed."); + return ret; + } + screenStatus = devScreenStatus; + LOGI("GetDeviceScreenStatus screenStatus: %{public}d.", devScreenStatus); + return DM_OK; +} + +int32_t SoftbusListener::SetForegroundUserIdsToDSoftBus(const std::string &remoteUdid, + const std::vector &userIds) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + NotifyUserIds notifyUserIds(remoteUdid, userIds); + std::string msg = notifyUserIds.ToString(); + LOGI("Notify remote userid to dsoftbus, msg: %{public}s", GetAnonyString(msg).c_str()); + return DM_OK; +#else + (void)remoteUdid; + (void)userIds; +#endif + return DM_OK; +} + +void SoftbusListener::DeleteCacheDeviceInfo() +{ + LOGI("DeleteCacheDeviceInfo start."); + std::vector onlineDevInfoVec; + SoftbusCache::GetInstance().GetDeviceInfoFromCache(onlineDevInfoVec); + if (onlineDevInfoVec.empty()) { + LOGE("onlineDevInfoVec is empty"); + return; + } + SoftbusCache::GetInstance().DeleteDeviceInfo(); + for (auto it : onlineDevInfoVec) { + LOGI("networkId: %{public}s", GetAnonyString(it.networkId).c_str()); + DeviceOffLine(it); + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_publish.cpp b/services/service/src/softbus/softbus_publish.cpp index 99967a8b593d73a7a1ce60a1e83c5b8821bcb66f..e717c639f3cfd0f7121da10f4b2bb9e9df97741e 100644 --- a/services/service/src/softbus/softbus_publish.cpp +++ b/services/service/src/softbus/softbus_publish.cpp @@ -99,7 +99,7 @@ void SoftbusPublish::OnSoftbusPublishResult(int publishId, PublishResult result) int32_t SoftbusPublish::PublishSoftbusLNN() { - LOGI("SoftbusPublish::PublishSoftbusLNN begin."); + LOGI("Begin."); PublishInfo publishInfo; publishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; publishInfo.mode = DiscoverMode::DISCOVER_MODE_PASSIVE; @@ -108,7 +108,7 @@ int32_t SoftbusPublish::PublishSoftbusLNN() publishInfo.capability = DM_CAPABILITY_OSD; publishInfo.ranging = false; - LOGI("PublishSoftbusLNN begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:" + LOGI("Begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:" "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.publishId, publishInfo.mode, publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq); @@ -122,7 +122,7 @@ int32_t SoftbusPublish::PublishSoftbusLNN() int32_t SoftbusPublish::StopPublishSoftbusLNN(int32_t publishId) { - LOGI("StopPublishSoftbusLNN begin, publishId: %{public}d.", publishId); + LOGI("Begin, publishId: %{public}d.", publishId); int32_t ret = StopPublishLNN(DM_PKG_NAME, publishId); if (ret != DM_OK) { LOGE("[SOFTBUS]StopPublishLNN failed, ret: %{public}d.", ret); diff --git a/services/softbuscache/BUILD.gn b/services/softbuscache/BUILD.gn index 4cdcad1db4a38c0b6a48baed98cb94fb3c44cdaa..e33a288ed53c54f2de3d5a3ff4da08fb0ac9f0e3 100644 --- a/services/softbuscache/BUILD.gn +++ b/services/softbuscache/BUILD.gn @@ -36,7 +36,7 @@ if (defined(ohos_lite)) { defines = [ "LITE_DEVICE", "DH_LOG_TAG=\"dmdevicecache\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004113", ] deps = [ @@ -72,7 +72,7 @@ if (defined(ohos_lite)) { defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"dmdevicecache\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004113", ] deps = [ "${utils_path}:devicemanagerutils" ] diff --git a/services/softbuscache/include/dm_softbus_cache.h b/services/softbuscache/include/dm_softbus_cache.h index b315a87d6199b41005f4d96c5abd34fdbac2ae5b..5a174234d46f38729c66964bcdd445e88b24d794 100644 --- a/services/softbuscache/include/dm_softbus_cache.h +++ b/services/softbuscache/include/dm_softbus_cache.h @@ -32,6 +32,7 @@ class SoftbusCache { public: void SaveDeviceInfo(DmDeviceInfo deviceInfo); void DeleteDeviceInfo(const DmDeviceInfo &nodeInfo); + void DeleteDeviceInfo(); void ChangeDeviceInfo(const DmDeviceInfo deviceInfo); void SaveDeviceSecurityLevel(const char *networkId); void DeleteDeviceSecurityLevel(const char *networkId); @@ -45,6 +46,10 @@ public: int32_t GetLocalDeviceInfo(DmDeviceInfo &nodeInfo); int32_t GetDevInfoByNetworkId(const std::string &networkId, DmDeviceInfo &nodeInfo); void UpDataLocalDevInfo(); + int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid); + int32_t GetUuidByUdid(const std::string &udid, std::string &uuid); + int32_t GetNetworkIdFromCache(const std::string &udid, std::string &networkId); + bool CheckIsOnline(const std::string &udidHash); private: int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index a7c9a7e39b3f6b195f61c7ed5c1679c138de92d8..02347e776502addff7a21367a5f157ff5dc53e96 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -19,11 +19,12 @@ #include "dm_constants.h" #include "dm_device_info.h" #include "dm_log.h" +#include namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusCache); -bool g_online = false; -bool g_getLocalDevInfo = false; +std::atomic g_online{false}; +std::atomic g_getLocalDevInfo{false}; DmDeviceInfo localDeviceInfo_; std::mutex localDevInfoMutex_; void SoftbusCache::SaveLocalDeviceInfo() @@ -62,7 +63,7 @@ int32_t SoftbusCache::GetLocalDeviceInfo(DmDeviceInfo &nodeInfo) std::lock_guard mutexLock(localDevInfoMutex_); if (g_getLocalDevInfo) { nodeInfo = localDeviceInfo_; - LOGI("SoftbusCache::GetLocalDeviceInfo from dm cache."); + LOGD("SoftbusCache::GetLocalDeviceInfo from dm cache."); return DM_OK; } NodeBasicInfo nodeBasicInfo; @@ -123,8 +124,16 @@ void SoftbusCache::SaveDeviceInfo(DmDeviceInfo deviceInfo) LOGI("SoftbusCache::SaveDeviceInfo"); std::string udid = ""; std::string uuid = ""; + if (deviceInfo.networkId[0] == '\0') { + LOGE("networkId is empty."); + return; + } GetUdidByNetworkId(deviceInfo.networkId, udid); GetUuidByNetworkId(deviceInfo.networkId, uuid); + if (udid.empty()) { + LOGE("udid is empty."); + return; + } char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(udid, reinterpret_cast(udidHash)) != DM_OK) { LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(udid).c_str()); @@ -155,6 +164,12 @@ void SoftbusCache::DeleteDeviceInfo(const DmDeviceInfo &nodeInfo) } } +void SoftbusCache::DeleteDeviceInfo() +{ + std::lock_guard mutexLock(deviceInfosMutex_); + deviceInfo_.clear(); +} + void SoftbusCache::ChangeDeviceInfo(const DmDeviceInfo deviceInfo) { LOGI("SoftbusCache::ChangeDeviceInfo"); @@ -255,16 +270,23 @@ int32_t SoftbusCache::GetUuidFromCache(const char *networkId, std::string &uuid) int32_t SoftbusCache::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { - (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); + return ERR_DM_FAILED; + } + if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + return ERR_DM_FAILED; } if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + return ERR_DM_FAILED; } + devInfo.deviceTypeId = nodeInfo.deviceTypeId; nlohmann::json extraJson; extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType; @@ -310,7 +332,12 @@ int32_t SoftbusCache::GetSecurityDeviceLevel(const char *networkId, int32_t &sec return DM_OK; } } - return GetDevLevelFromBus(networkId, securityLevel); + int32_t ret = GetDevLevelFromBus(networkId, securityLevel); + if (ret == DM_OK) { + LOGI("Get dev level from softbus success."); + return DM_OK; + } + return ret; } int32_t SoftbusCache::GetDevLevelFromBus(const char *networkId, int32_t &securityLevel) @@ -371,5 +398,65 @@ int32_t SoftbusCache::GetDevInfoFromBus(const std::string &networkId, DmDeviceIn GetAnonyString(devInfo.deviceName).c_str(), devInfo.deviceTypeId); return ret; } + +int32_t SoftbusCache::GetUdidByUdidHash(const std::string &udidHash, std::string &udid) +{ + LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + for (const auto &item : deviceInfo_) { + if (std::string(item.second.second.deviceId) == udidHash) { + udid = item.first; + LOGI("GetUdidByUdidHash success udid %{public}s.", GetAnonyString(udid).c_str()); + return DM_OK; + } + } + } + return ERR_DM_FAILED; +} + +int32_t SoftbusCache::GetUuidByUdid(const std::string &udid, std::string &uuid) +{ + LOGI("udid %{public}s.", GetAnonyString(udid).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + if (deviceInfo_.find(udid) != deviceInfo_.end()) { + uuid = deviceInfo_[udid].first; + LOGI("success uuid %{public}s.", GetAnonyString(uuid).c_str()); + return DM_OK; + } + } + return ERR_DM_FAILED; +} + +int32_t SoftbusCache::GetNetworkIdFromCache(const std::string &udid, std::string &networkId) +{ + LOGI("udid %{public}s.", GetAnonyString(udid).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + if (deviceInfo_.find(udid) != deviceInfo_.end()) { + networkId = deviceInfo_[udid].second.networkId; + LOGI("GetNetworkIdFromCache success networkId %{public}s, udid %{public}s.", + GetAnonyString(networkId).c_str(), GetAnonyString(udid).c_str()); + return DM_OK; + } + } + return ERR_DM_FAILED; +} + +bool SoftbusCache::CheckIsOnline(const std::string &deviceId) +{ + LOGI("deviceId %{public}s.", GetAnonyString(deviceId).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + for (const auto &item : deviceInfo_) { + if (std::string(item.second.second.deviceId) == deviceId) { + LOGI("CheckIsOnline is true."); + return true; + } + } + } + return false; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/benchmarktest/device_manager_fa_test/BUILD.gn b/test/benchmarktest/device_manager_fa_test/BUILD.gn index 4ac558754468d493ed02d9161660d09d84ef6bc3..fb237389eca1d3a7d15051fcbb61c858c95f90cf 100644 --- a/test/benchmarktest/device_manager_fa_test/BUILD.gn +++ b/test/benchmarktest/device_manager_fa_test/BUILD.gn @@ -34,7 +34,6 @@ ohos_benchmarktest("DeviceManagerFaTest") { deps = [ "${common_path}/include/show_confirm_dialog/dialog_ui/js:dialog_js_files_etc", "${innerkits_path}/native_cpp:devicemanagersdk", - "//third_party/benchmark:benchmark", ] external_deps = [ diff --git a/test/commonfuzztest/BUILD.gn b/test/commonfuzztest/BUILD.gn index 0757b91206af4c426cd637711c37e54c4faf4d28..83cb6a5e3f94db4e6caf6c7f5f63ae22b474a945 100644 --- a/test/commonfuzztest/BUILD.gn +++ b/test/commonfuzztest/BUILD.gn @@ -17,10 +17,14 @@ group("fuzztest") { deps = [ "authenticatedevice_fuzzer:fuzztest", "authenticatedeviceservice_fuzzer:fuzztest", + "authenticatedeviceserviceimpl_fuzzer:fuzztest", + "dmauthmanager_fuzzer:fuzztest", "dmcommoneventmanager_fuzzer:fuzztest", "dmcredentialimpl_fuzzer:fuzztest", + "dmdiscoverymanager_fuzzer:fuzztest", "generateencrypteduuid_fuzzer:fuzztest", "getdeviceinfo_fuzzer:fuzztest", + "hichainconnector_fuzzer:fuzztest", "ondatareceived_fuzzer:fuzztest", "onerror_fuzzer:fuzztest", "onfinish_fuzzer:fuzztest", diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index d8cb654bdad300b3cd7679770a05251534380529..a39823d681e1ffe52659d3d03e781dc2daa311e5 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -213,11 +213,13 @@ void AuthenticateDeviceFirstFuzzTest(const uint8_t* data, size_t size) DeviceManager::GetInstance().RegisterDevStateCallback(str, str, g_stateCallback); DeviceManager::GetInstance().RegisterDevStatusCallback(str, str, g_statusCallback); DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(str, g_Uicallback); - DeviceManager::GetInstance().AuthenticateDevice(str, g_authType, g_deviceInfo, str, g_callbackk); + std::string emptyStr = ""; + DeviceManager::GetInstance().AuthenticateDevice(str, g_authType, g_deviceInfo, emptyStr, g_callbackk); DeviceManager::GetInstance().UnAuthenticateDevice(str, g_deviceInfo); - DeviceManager::GetInstance().StartDeviceDiscovery(str, g_subscribeInfo, str, g_discoveryCallback); + std::string pkgName = "pkgName"; + DeviceManager::GetInstance().StartDeviceDiscovery(pkgName, g_subscribeInfo, pkgName, g_discoveryCallback); DeviceManager::GetInstance().StopDeviceDiscovery(str, g_subscribeInfo.subscribeId); - DeviceManager::GetInstance().StartDeviceDiscovery(str, g_tokenId, str, g_discoveryCallback); + DeviceManager::GetInstance().StartDeviceDiscovery(pkgName, g_tokenId, pkgName, g_discoveryCallback); DeviceManager::GetInstance().StopDeviceDiscovery(g_tokenId, str); DeviceManager::GetInstance().PublishDeviceDiscovery(str, g_publishInfo, g_publishCallback); DeviceManager::GetInstance().UnPublishDeviceDiscovery(str, g_publishInfo.publishId); @@ -269,12 +271,115 @@ void AuthenticateDeviceThirdFuzzTest(const uint8_t* data, size_t size) DeviceManager::GetInstance().ImportCredential(str, g_reqJsonStr, g_returnStr); DeviceManager::GetInstance().DeleteCredential(str, g_reqJsonStr, g_returnStr); DeviceManager::GetInstance().NotifyEvent(str, g_eventId, str); - DeviceManager::GetInstance().BindDevice(str, g_authType, str, str, g_callbackk); + std::string emptyStr = ""; + DeviceManager::GetInstance().BindDevice(str, g_authType, str, emptyStr, g_callbackk); DeviceManager::GetInstance().UnBindDevice(str, g_deviceInfo.deviceId); DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(str); DeviceManager::GetInstance().UnRegisterDevStateCallback(str); DeviceManager::GetInstance().UnRegisterDevStatusCallback(str); } + +void AuthenticateDeviceFourthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + AddPermission(); + std::string str(reinterpret_cast(data), size); + + DeviceManagerImpl::GetInstance().ipcClientProxy_ = + std::make_shared(std::make_shared()); + std::string emptyStr = ""; + DmDeviceInfo info; + DmDeviceBasicInfo deviceBasicInfo; + int32_t indexTwo = 2; + int32_t numOne = 1; + int32_t numOneTwoTimes = 11; + int32_t numOneThreeTimes = 111; + int32_t numOneSixTimes = 111111; + + DeviceManagerImpl::GetInstance().ConvertDeviceInfoToDeviceBasicInfo(info, deviceBasicInfo); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, emptyStr, g_deviceList); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, emptyStr, false, g_deviceList); + DeviceManagerImpl::GetInstance().GetDeviceInfo(str, emptyStr, info); + DeviceManagerImpl::GetInstance().RegisterDevStatusCallback(str, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(str); + DeviceManagerImpl::GetInstance().UnRegisterDevStatusCallback(emptyStr); + DeviceManagerImpl::GetInstance().StartDeviceDiscovery(str, g_subscribeInfo, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().StartDeviceDiscovery(str, numOneSixTimes, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().StopDeviceDiscovery(str, numOneTwoTimes); + DeviceManagerImpl::GetInstance().StopDeviceDiscovery(numOneThreeTimes, ""); + DeviceManagerImpl::GetInstance().PublishDeviceDiscovery(str, g_publishInfo, nullptr); + DeviceManagerImpl::GetInstance().UnPublishDeviceDiscovery(str, numOneTwoTimes); + DeviceManagerImpl::GetInstance().AuthenticateDevice(str, numOne, info, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().RegisterDeviceManagerFaCallback(str, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDeviceManagerFaCallback(str); + DeviceManagerImpl::GetInstance().VerifyAuthentication(str, emptyStr, nullptr); + PeerTargetId targetId; + std::map discoverParam; + DeviceManagerImpl::GetInstance().BindTarget(str, targetId, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().UnbindTarget(str, targetId, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, discoverParam, false, g_deviceList); + DeviceManagerImpl::GetInstance().RegisterDevStateCallback(str, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().AddDiscoveryCallback("test", discoverParam, nullptr); + DeviceManagerImpl::GetInstance().RemoveDiscoveryCallback("test"); + DeviceManagerImpl::GetInstance().AddPublishCallback("test"); + DeviceManagerImpl::GetInstance().RemovePublishCallback("test"); + DeviceManagerImpl::GetInstance().RegisterPinHolderCallback(str, nullptr); + DeviceManagerImpl::GetInstance().GetDeviceSecurityLevel(str, emptyStr, indexTwo); + DeviceManagerImpl::GetInstance().IsSameAccount(emptyStr); +} + +void AuthenticateDeviceFifthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + AddPermission(); + std::string str(reinterpret_cast(data), size); + + DeviceManagerImpl::GetInstance().ipcClientProxy_ = + std::make_shared(std::make_shared()); + std::string emptyStr = ""; + DmDeviceInfo info; + DmDeviceBasicInfo deviceBasicInfo; + int32_t indexTwo = 2; + DmAuthParam dmFaParam; + DeviceManagerImpl::GetInstance().GetFaParam(str, dmFaParam); + DeviceManagerImpl::GetInstance().SetUserOperation(str, 1, emptyStr); + DeviceManagerImpl::GetInstance().GetUdidByNetworkId(str, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().GetUuidByNetworkId(str, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().RegisterDevStateCallback(str, emptyStr); + DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(str, emptyStr); + DeviceManagerImpl::GetInstance().RegisterUiStateCallback(str); + DeviceManagerImpl::GetInstance().UnRegisterUiStateCallback(str); + DeviceManagerImpl::GetInstance().RequestCredential(str, g_reqJsonStr, g_returnStr); + DeviceManagerImpl::GetInstance().ImportCredential(str, emptyStr); + DeviceManagerImpl::GetInstance().DeleteCredential(str, emptyStr); + DeviceManagerImpl::GetInstance().RegisterCredentialCallback(str, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterCredentialCallback(str); + DeviceManagerImpl::GetInstance().NotifyEvent(str, 1, emptyStr); + DeviceManagerImpl::GetInstance().RequestCredential(str, g_returnStr); + DeviceManagerImpl::GetInstance().CheckCredential(str, g_reqJsonStr, g_returnStr); + DeviceManagerImpl::GetInstance().GetEncryptedUuidByNetworkId(str, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().GenerateEncryptedUuid(str, emptyStr, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().BindDevice(str, 1, emptyStr, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnBindDevice(str, emptyStr); + DeviceManagerImpl::GetInstance().GetNetworkTypeByNetworkId(str, emptyStr, indexTwo); + DeviceManagerImpl::GetInstance().ImportAuthCode(emptyStr, emptyStr); + DeviceManagerImpl::GetInstance().ExportAuthCode(g_returnStr); + std::map discoverParam; + DeviceManagerImpl::GetInstance().StartDiscovering(str, discoverParam, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().StopDiscovering(str, discoverParam); + DeviceManagerImpl::GetInstance().RegisterDiscoveryCallback(str, discoverParam, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDiscoveryCallback(str); + DeviceManagerImpl::GetInstance().StartAdvertising(str, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().StopAdvertising(str, discoverParam); + DeviceManagerImpl::GetInstance().SetDnPolicy(str, discoverParam); + DeviceManagerImpl::GetInstance().RegisterDeviceScreenStatusCallback(emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDeviceScreenStatusCallback(emptyStr); + DeviceManagerImpl::GetInstance().GetDeviceScreenStatus(emptyStr, emptyStr, indexTwo); +} } } @@ -285,5 +390,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) OHOS::DistributedHardware::AuthenticateDeviceFirstFuzzTest(data, size); OHOS::DistributedHardware::AuthenticateDeviceSecondFuzzTest(data, size); OHOS::DistributedHardware::AuthenticateDeviceThirdFuzzTest(data, size); + OHOS::DistributedHardware::AuthenticateDeviceFourthFuzzTest(data, size); + OHOS::DistributedHardware::AuthenticateDeviceFifthFuzzTest(data, size); return 0; } diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn index 64af696daf9d001ffb7c165179a76a0832ce81ba..0393235e1340443a708234ccef0234b77706b7f6 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn @@ -55,7 +55,10 @@ ohos_fuzztest("AuthenticateDeviceServiceFuzzTest") { ] sources = [ "authenticate_device_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] defines = [ "HI_LOG_ENABLE", @@ -68,9 +71,11 @@ ohos_fuzztest("AuthenticateDeviceServiceFuzzTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp b/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp index 5e9988c720b18ddf05a3e2b98b9eb6a0b2fb2f69..160fdf58b172a67b20959eefe028d2b6ba14e279 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp @@ -72,8 +72,8 @@ void AuthenticateDeviceServiceFuzzTest(const uint8_t* data, size_t size) DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, extra); DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); DeviceManagerService::GetInstance().SetUserOperation(pkgName, authType, network); - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, deviceId, udid); DeviceManagerService::GetInstance().CheckApiPermission(level); } diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn index 6a63d4b296c40daf687bb6069a7a9252eec4cccd..5c71e535b755cd098ae3b8185518142a1c54fd92 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { deps = [ "${devicemanager_path}/services/implementation:devicemanagerserviceimpl", "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", ] defines = [ @@ -67,12 +68,15 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { ] external_deps = [ + "ability_base:want", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp index 485f5a9a35d43cd86b6d508957bdbdecce86a620..32b0d79f985e53cb11b72f03985e54a46c98ec7d 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp @@ -109,11 +109,12 @@ void AddPermission() void AuthenticateDeviceServiceImplFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size == 0)) { + if ((data == nullptr) || (size == 0) || (size < sizeof(int32_t))) { return; } std::string str(reinterpret_cast(data), size); + int32_t bindLevel = *(reinterpret_cast(data)); AddPermission(); DmSubscribeInfo subscribeInfo = { .subscribeId = 0, @@ -138,10 +139,8 @@ void AuthenticateDeviceServiceImplFuzzTest(const uint8_t* data, size_t size) deviceManagerServiceImpl->StopDeviceDiscovery(str, g_subscribeId); deviceManagerServiceImpl->PublishDeviceDiscovery(str, publishInfo); deviceManagerServiceImpl->UnPublishDeviceDiscovery(str, publishInfo.publishId); - deviceManagerServiceImpl->AuthenticateDevice(str, g_authType, str, str); - deviceManagerServiceImpl->UnAuthenticateDevice(str, str); - deviceManagerServiceImpl->BindDevice(str, g_authType, str, str); - deviceManagerServiceImpl->UnBindDevice(str, str); + deviceManagerServiceImpl->UnAuthenticateDevice(str, str, bindLevel); + deviceManagerServiceImpl->UnBindDevice(str, str, bindLevel); deviceManagerServiceImpl->SetUserOperation(str, g_action, str); deviceManagerServiceImpl->RequestCredential(g_reqJsonStr, g_returnJsonStr); deviceManagerServiceImpl->ImportCredential(str, g_credentialInfo); diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn index 17166fbd38bf7f697b35946da1f89329c34880ea..211997de69b5fa97eaf9b0c3d6484627de2ac268 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn +++ b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("DmAuthManagerFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp index 48da003729bbf7ab6b26d426ec9f73aacf6158eb..160243871f7a714dbfd17eb3e3f282097609fbdc 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp +++ b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp @@ -62,6 +62,7 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) return; } std::string str(reinterpret_cast(data), size); + int32_t bindLevel = *(reinterpret_cast(data)); g_authManager->authMessageProcessor_ = std::make_shared(g_authManager); g_authManager->authMessageProcessor_->authResponseContext_ = std::make_shared(); g_authManager->authRequestContext_ = std::make_shared(); @@ -94,7 +95,6 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) g_authManager->StartRespAuthProcess(); g_authManager->CreateGroup(); g_authManager->ProcessPincode(g_pinCode); - g_authManager->UserSwitchEventCallback(g_userId); g_authManager->SetPageId(g_pageId); g_authManager->SetReasonAndFinish(g_reason, g_state); g_authManager->IsIdenticalAccount(); @@ -104,8 +104,8 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) g_authManager->HandleAuthenticateTimeout(str); g_authManager->RegisterUiStateCallback(str); g_authManager->UnRegisterUiStateCallback(str); - g_authManager->UnAuthenticateDevice(str, str); - g_authManager->UnBindDevice(str, str); + g_authManager->UnAuthenticateDevice(str, str, bindLevel); + g_authManager->UnBindDevice(str, str, bindLevel); } } } diff --git a/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn b/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn index 9684811db9dab9714a2c21bdccfe0e21af51a588..20d05de729741ba71e4baa4bd3f2467bf0ec17f3 100644 --- a/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn +++ b/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn @@ -46,6 +46,7 @@ ohos_fuzztest("DmDiscoveryManagerFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ @@ -56,6 +57,7 @@ ohos_fuzztest("DmDiscoveryManagerFuzzTest") { external_deps = [ "device_auth:deviceauth_sdk", + "ffrt:libffrt", "safwk:system_ability_fwk", ] } diff --git a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn index efd8e79c2b83b08f58b716611df987d078bf298b..ef286102d86ddc8d6b588d635e1e77177d242c6c 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn +++ b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn @@ -46,12 +46,14 @@ ohos_fuzztest("HichainConnectorFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 34fc06070f8467311cf8bc3d952b99f95c74bd1e..19c2f68e2f41d8f85463d330a08f6a1a6af6e437 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -16,9 +16,11 @@ #include #include #include +#include #include #include "device_manager_service_listener.h" +#include "dm_anonymous.h" #include "dm_auth_manager.h" #include "hichain_connector.h" @@ -53,6 +55,34 @@ public: } }; +void AddGroupInfo(std::vector &groupList) +{ + GroupInfo groupInfo1; + groupInfo1.groupId = "234"; + groupInfo1.groupType = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; + groupList.push_back(groupInfo1); + GroupInfo groupInfo2; + groupInfo2.groupId = "1485"; + groupInfo2.groupOwner = DM_PKG_NAME; + groupList.push_back(groupInfo2); +} + +void AddAclInfo(std::vector> &delACLInfoVec, std::vector &userIdVec) +{ + int32_t key = 12; + std::string value = "acl_info1"; + delACLInfoVec.push_back(std::make_pair(key, value)); + userIdVec.push_back(key); + int32_t key1 = 23; + value = "acl_info2"; + delACLInfoVec.push_back(std::make_pair(key1, value)); + userIdVec.push_back(key); + int32_t key2 = 25; + value = "acl_info3"; + delACLInfoVec.push_back(std::make_pair(key2, value)); + userIdVec.push_back(key); +} + void HiChainConnectorFuzzTest(const uint8_t* data, size_t size) { if ((data == nullptr) || (size < sizeof(int32_t))) { @@ -97,10 +127,220 @@ void HiChainConnectorFuzzTest(const uint8_t* data, size_t size) hichainConnector->GetTrustedDevices(deviceId); hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); hichainConnector->DeleteAllGroup(delUserid); - hichainConnector->DeleteP2PGroup(delUserid); hichainConnector->GetRelatedGroupsCommon(deviceId, pkgNameStr.data(), groupList); hichainConnector->UnRegisterHiChainCallback(); } + +void HiChainConnectorSecondFuzzTest(const uint8_t* data, size_t size) +{ + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + + std::vector groupList; + nlohmann::json jsonDeviceList; + GroupInfo groupInfo; + std::vector syncGroupList; + hichainConnector->GetSyncGroupList(groupList, syncGroupList); + hichainConnector->IsGroupInfoInvalid(groupInfo); + hichainConnector->UnRegisterHiChainGroupCallback(); + hichainConnector->GetJsonStr(jsonDeviceList, "key"); +} + +void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int64_t))) { + return; + } + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + int64_t requestId = *(reinterpret_cast(data)); + std::string groupName = "groupName"; + GroupInfo groupInfo; + std::string userId(reinterpret_cast(data), size); + int32_t authType = *(reinterpret_cast(data)); + std::vector groupList; + std::string queryParams(reinterpret_cast(data), size); + std::string pkgName(reinterpret_cast(data), size); + std::string groupId(reinterpret_cast(data), size); + std::string deviceId(reinterpret_cast(data), size); + std::string reqDeviceId(reinterpret_cast(data), size); + nlohmann::json jsonOutObj; + std::shared_ptr callback; + std::string jsonStr(reinterpret_cast(data), size); + int32_t groupType = *(reinterpret_cast(data)); + int32_t switchUserId = *(reinterpret_cast(data)); + std::string reqParams(reinterpret_cast(data), size); + std::string credentialInfo(reinterpret_cast(data), size); + int operationCode = GroupOperationCode::MEMBER_JOIN; + hichainConnector->deviceGroupManager_ = nullptr; + hichainConnector->AddMember(deviceId, queryParams); + hichainConnector->getRegisterInfo(queryParams, jsonStr); + hichainConnector->addMultiMembers(groupType, userId, jsonOutObj); + hichainConnector->addMultiMembersExt(credentialInfo); + hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); + hichainConnector->GetGroupInfoCommon(authType, queryParams, pkgName.c_str(), groupList); + hichainConnector->hiChainConnectorCallback_ = nullptr; + hichainConnector->GetConnectPara(deviceId, reqDeviceId); + hichainConnector->onRequest(requestId, operationCode, reqParams.c_str()); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + if (hichainConnector->deviceGroupManager_ == nullptr) { + hichainConnector->deviceGroupManager_ = GetGmInstance(); + } + hichainConnector->IsGroupCreated(groupName, groupInfo); + hichainConnector->GetGroupInfoExt(authType, queryParams, groupList); + hichainConnector->GetGroupInfoCommon(authType, queryParams, pkgName.c_str(), groupList); + hichainConnector->RegisterHiChainGroupCallback(callback); + hichainConnector->GetJsonInt(jsonOutObj, "key"); + hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); + hichainConnector->DeleteAllGroupByUdid(reqParams); +} + +void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int64_t))) { + return; + } + + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + + int64_t requestId = *(reinterpret_cast(data)); + std::string groupName(reinterpret_cast(data), size); + std::string groupId = "groupId_forth"; + std::string deviceId = "deviceId_forth"; + std::string returnData(reinterpret_cast(data), size); + std::string userId = "userId_forth"; + int32_t authType = *(reinterpret_cast(data)); + int operationCode = GroupOperationCode::MEMBER_JOIN; + int errCode = 102; + std::vector syncGroupList; + std::vector> delACLInfoVec; + std::vector userIdVec; + hichainConnector->DeleteGroupByACL(delACLInfoVec, userIdVec); + std::vector groupList; + AddGroupInfo(groupList); + AddAclInfo(delACLInfoVec, userIdVec); + hichainConnector->DeleteGroup(groupId); + hichainConnector->DeleteGroupExt(groupId); + hichainConnector->DeleteGroup(authType, groupId); + hichainConnector->DeleteGroup(requestId, userId, authType); + hichainConnector->DelMemberFromGroup(groupId, deviceId); + hichainConnector->DeleteRedundanceGroup(userId); + hichainConnector->DealRedundanceGroup(userId, authType); + hichainConnector->DeleteGroupByACL(delACLInfoVec, userIdVec); + hichainConnector->IsNeedDelete(groupName, authType, delACLInfoVec); + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + hichainConnector->onRequest(requestId, operationCode, returnData.c_str()); + operationCode = GroupOperationCode::GROUP_CREATE; + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + operationCode == GroupOperationCode::MEMBER_DELETE; + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + operationCode == GroupOperationCode::GROUP_DISBAND; + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + hichainConnector->GenRequestId(); + hichainConnector->GetRelatedGroups(deviceId, groupList); + hichainConnector->GetRelatedGroupsExt(deviceId, groupList); + hichainConnector->GetSyncGroupList(groupList, syncGroupList); + hichainConnector->GetGroupId(userId, authType, userId); +} + +void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int64_t))) { + return; + } + + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + int64_t requestId = *(reinterpret_cast(data)); + std::string groupName = "groupName_fifth"; + int32_t authType = *(reinterpret_cast(data)); + std::string params = "params"; + int32_t osAccountUserId = *(reinterpret_cast(data)); + nlohmann::json jsonDeviceList; + std::vector> delACLInfoVec; + std::vector userIdVec; + std::vector> delAclInfoVec1; + std::string jsonStr = R"({"content": {"deviceid": "123"}}, authId: "123456"))"; + std::vector udidList; + int32_t key = 12; + std::string value = "acl_info1"; + std::string credentialInfo = R"({"content": {"deviceid": "123"}}, authId: "123456"))"; + std::string groupOwner(reinterpret_cast(data), size); + delAclInfoVec1.push_back(std::make_pair(key, value)); + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = 1; + jsonObj[FIELD_USER_ID] = "123456"; + jsonObj[FIELD_CREDENTIAL_TYPE] = 1; + jsonObj[FIELD_OPERATION_CODE] = 1; + jsonObj[FIELD_TYPE] = "filed_type"; + jsonObj[FIELD_DEVICE_LIST] = "device_list"; + hichainConnector->deviceGroupManager_ = nullptr; + hichainConnector->CreateGroup(requestId, groupName); + hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); + if (hichainConnector->deviceGroupManager_ == nullptr) { + hichainConnector->deviceGroupManager_ = GetGmInstance(); + } + hichainConnector->CreateGroup(requestId, groupName); + hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); + hichainConnector->ParseRemoteCredential(authType, groupName, jsonDeviceList, params, osAccountUserId); + hichainConnector->ParseRemoteCredential(authType, "", jsonDeviceList, params, osAccountUserId); + hichainConnector->IsNeedDelete(groupName, authType, delACLInfoVec); + hichainConnector->DeleteGroupByACL(delAclInfoVec1, userIdVec); + hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); + jsonStr = R"({"content": {"deviceid": "123"}}, authId: "123456")"; + hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); + jsonStr = R"({"content": {"deviceid": "123"}}, localId: "123456")"; + hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); +} + +void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + std::string groupOwner(reinterpret_cast(data), size); + nlohmann::json jsonObj; + std::string deviceId = "deviceId"; + std::string key = "localDeviceId"; + jsonObj["deviceId"] = 1; + hichainConnector->GetJsonInt(jsonObj, key); + hichainConnector->GetJsonInt(jsonObj, key); + jsonObj[key] = 1; + jsonObj["deviceName"] = "devieName1"; + hichainConnector->GetJsonInt(jsonObj, "devieName"); + hichainConnector->AddMember(deviceId, SafetyDump(jsonObj)); + jsonObj[TAG_DEVICE_ID] = "deviceId_001"; + jsonObj[PIN_CODE_KEY] = 1; + jsonObj[TAG_GROUP_ID] = "groupId"; + jsonObj[TAG_REQUEST_ID] = 1; + jsonObj[TAG_GROUP_NAME] = "groupName"; + hichainConnector->AddMember(deviceId, SafetyDump(jsonObj)); + + nlohmann::json jsonObjCre; + std::string params; + jsonObjCre[AUTH_TYPE] = 1; + jsonObjCre["userId"] = "user_001"; + jsonObjCre[FIELD_CREDENTIAL_TYPE] = 1; + jsonObjCre[FIELD_OPERATION_CODE] = 1; + jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; + jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; + std::string credentialInfo = SafetyDump(jsonObjCre); + hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); + int32_t groupType = *(reinterpret_cast(data)); + nlohmann::json jsonDeviceList; + int32_t osAccountUserId = 0; + std::string userId = "user_002"; + jsonDeviceList[FIELD_DEVICE_LIST] = "deviceList"; + hichainConnector->ParseRemoteCredential(groupType, userId, jsonDeviceList, params, osAccountUserId); +} } } @@ -109,6 +349,10 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { /* Run your code on data */ OHOS::DistributedHardware::HiChainConnectorFuzzTest(data, size); - + OHOS::DistributedHardware::HiChainConnectorSecondFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorThirdFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorForthFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorFifthFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorSixthFuzzTest(data, size); return 0; } \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn index 123369f49a510668db015f426fc3d1c4b758af18..3c10d43a41753170a44f58417cc3e4e91b7fc87b 100644 --- a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn +++ b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn @@ -46,12 +46,14 @@ ohos_fuzztest("OnDataReceivedFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onerror_fuzzer/BUILD.gn b/test/commonfuzztest/onerror_fuzzer/BUILD.gn index 2752478a0cd964f05dd4a1c236d63c878f6ea948..51028c63b5af9921c8285a046b99ba33b88dd338 100644 --- a/test/commonfuzztest/onerror_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onerror_fuzzer/BUILD.gn @@ -45,12 +45,14 @@ ohos_fuzztest("OnErrorFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp index ea8c7f86a817e88339af2cd5f1a3e0d7dd1778dd..97e88fa08a0ee2468ad6ab99ba5d843a0d272636 100644 --- a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp +++ b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp @@ -63,8 +63,7 @@ void OnErrorFuzzTest(const uint8_t* data, size_t size) hichainConnector->RegisterHiChainCallback(std::make_shared()); int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); int errorCode = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); const char *returnData = str.data(); diff --git a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn index 17165e254f06d32c8e873323cc710a496a6082d5..9be7418d3f931ad3e267e0c14c8af5909428431a 100644 --- a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn @@ -45,12 +45,14 @@ ohos_fuzztest("OnFinishFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp index 196069accd5b4693f16e6385a3e18d19e9daaa76..3a852c03fc4171f758786b8239256bbf1f219792 100644 --- a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp +++ b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp @@ -63,8 +63,7 @@ void OnFinishFuzzTest(const uint8_t* data, size_t size) hichainConnector->RegisterHiChainCallback(std::make_shared()); int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); const char *returnData = str.data(); hichainConnector->onFinish(requestId, operationCode, returnData); diff --git a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn index be167ff0791d7d51b7702dde8d0aa8cd6b658098..0607ba06533b92de0379ceeff87a3cb2b1dcd561 100644 --- a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn @@ -46,12 +46,14 @@ ohos_fuzztest("OnRequestFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp index d3b7df0b7b32c73ed8a1f79537e0855d86093673..d27fd5e0e32acbf0d7e70822066ef77ad742710d 100644 --- a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp +++ b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp @@ -59,8 +59,7 @@ void OnRequestFuzzTest(const uint8_t* data, size_t size) } int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); const char *reqParams = reinterpret_cast(data); std::shared_ptr hichainConnector = std::make_shared(); diff --git a/test/commonfuzztest/pinauth_fuzzer/BUILD.gn b/test/commonfuzztest/pinauth_fuzzer/BUILD.gn index 441b782bc2b719eacf9d7e9c5b40953966695fc4..ff2b0b26c3c390f3d465e8ceae4f98b3aefc7a79 100644 --- a/test/commonfuzztest/pinauth_fuzzer/BUILD.gn +++ b/test/commonfuzztest/pinauth_fuzzer/BUILD.gn @@ -66,6 +66,7 @@ ohos_fuzztest("PinAuthFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn b/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn index 41c97120d0742dc8f1baf1194dfe68f0c76b8454..9b772dab92033adbb43ab883a60de24a9ed22a57 100644 --- a/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn +++ b/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn @@ -67,6 +67,7 @@ ohos_fuzztest("PinAuthUiFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonfuzztest/pinholder_fuzzer/BUILD.gn b/test/commonfuzztest/pinholder_fuzzer/BUILD.gn index 6fa7a10979f366c07e2a4a5a778c675359d1a1f9..9ac3303a83c345855c06d8cb63e7f75040b66fdb 100644 --- a/test/commonfuzztest/pinholder_fuzzer/BUILD.gn +++ b/test/commonfuzztest/pinholder_fuzzer/BUILD.gn @@ -67,6 +67,7 @@ ohos_fuzztest("PinHolderFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonunittest/UTTest_discovery_filter.cpp b/test/commonunittest/UTTest_discovery_filter.cpp index 092d38f228916d1c9f59ddbe9761e9250480aa59..1122727bb93529e06959e07ab0cc280a5465f5e1 100644 --- a/test/commonunittest/UTTest_discovery_filter.cpp +++ b/test/commonunittest/UTTest_discovery_filter.cpp @@ -45,7 +45,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Level0 { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -55,7 +55,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Level0 DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -66,7 +66,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Level0 nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -77,7 +77,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Level0 nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -89,7 +89,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -101,7 +101,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -116,7 +116,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -132,7 +132,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -148,7 +148,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Level myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -165,7 +165,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSize. { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -175,7 +175,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSize. DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -186,7 +186,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -198,7 +198,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSize. jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -211,7 +211,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -224,7 +224,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_discovery_manager.cpp b/test/commonunittest/UTTest_discovery_manager.cpp index 74f9f3efc5b66fc31d3a6dd3ff2dac8a9cd69f7e..95f3f90eb8d8cdaebfd9c26dcc8022486b8a4430 100644 --- a/test/commonunittest/UTTest_discovery_manager.cpp +++ b/test/commonunittest/UTTest_discovery_manager.cpp @@ -50,6 +50,11 @@ namespace { std::shared_ptr listener = std::make_shared(); std::shared_ptr manager = std::make_shared(softbusListener, listener); +bool checkSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR; +} + HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -67,7 +72,7 @@ HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_002, testing::ext::TestSi discoverParam.insert(std::pair("SUBSCRIBE_ID", "ohos.test")); std::map filterOptions; int32_t ret = manager->EnableDiscoveryListener(pkgName, discoverParam, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_003, testing::ext::TestSize.Level0) @@ -76,7 +81,7 @@ HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_003, testing::ext::TestSi std::map discoverParam; std::map filterOptions; int32_t ret = manager->EnableDiscoveryListener(pkgName, discoverParam, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_001, testing::ext::TestSize.Level0) @@ -94,7 +99,7 @@ HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_002, testing::ext::TestS extraParam.insert(std::pair("META_TYPE", "ohos.test")); extraParam.insert(std::pair("SUBSCRIBE_ID", "ohos.test")); int32_t ret = manager->DisableDiscoveryListener(pkgName, extraParam); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_003, testing::ext::TestSize.Level0) @@ -102,7 +107,7 @@ HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_003, testing::ext::TestS std::string pkgName = "pkgName"; std::map extraParam; int32_t ret = manager->DisableDiscoveryListener(pkgName, extraParam); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, StartDiscovering_001, testing::ext::TestSize.Level0) @@ -124,7 +129,7 @@ HWTEST_F(DiscoveryManagerTest, StartDiscovering_002, testing::ext::TestSize.Leve discoverParam.insert(std::pair("FILTER_OPTIONS", "ohos.test")); std::map filterOptions; int32_t ret = manager->StartDiscovering(pkgName, discoverParam, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, StartDiscovering_003, testing::ext::TestSize.Level0) @@ -240,7 +245,7 @@ HWTEST_F(DiscoveryManagerTest, StopDiscovering_002, testing::ext::TestSize.Level DiscoveryContext context; manager->discoveryContextMap_.emplace(pkgName, context); int32_t ret = manager->StopDiscovering(pkgName, subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, OnDeviceFound_001, testing::ext::TestSize.Level0) @@ -249,7 +254,7 @@ HWTEST_F(DiscoveryManagerTest, OnDeviceFound_001, testing::ext::TestSize.Level0) DmDeviceInfo info; bool isOnline = false; manager->OnDeviceFound(pkgName, info, isOnline); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) @@ -258,7 +263,7 @@ HWTEST_F(DiscoveryManagerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) DmDeviceInfo info; bool isOnline = true; manager->OnDeviceFound(pkgName, info, isOnline); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_001, testing::ext::TestSize.Level0) @@ -267,7 +272,7 @@ HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_001, testing::ext::TestSize.L int32_t subscribeId = 1; int32_t result = 0; manager->OnDiscoveringResult(pkgName, subscribeId, result); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_002, testing::ext::TestSize.Level0) @@ -277,7 +282,7 @@ HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_002, testing::ext::TestSize.L int32_t result = 0; manager->listener_ = nullptr; manager->OnDiscoveringResult(pkgName, subscribeId, result); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_003, testing::ext::TestSize.Level0) @@ -347,7 +352,7 @@ HWTEST_F(DiscoveryManagerTest, HandleDiscoveryTimeout_003, testing::ext::TestSiz DiscoveryContext context; manager->discoveryContextMap_.emplace(name, context); manager->HandleDiscoveryTimeout(name); - EXPECT_NE(manager->pkgNameSet_.empty(), false); + EXPECT_EQ(manager->pkgNameSet_.empty(), false); } HWTEST_F(DiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) @@ -356,7 +361,7 @@ HWTEST_F(DiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Lev std::string deviceId; bool isonline = true; int32_t authForm = 0; - int32_t ret = manager->GetDeviceAclParam(pkgName, deviceId, isonline, authForm); + int32_t ret = manager->GetDeviceAclParam(pkgName, 100, deviceId, isonline, authForm); EXPECT_EQ(ret, DM_OK); } diff --git a/test/commonunittest/UTTest_dm_anonymous.cpp b/test/commonunittest/UTTest_dm_anonymous.cpp index d26792a0e4da9d327593550f9d95c3d901964ca3..c4924fa83c43c4830b64b1d975c1987292bcd3cf 100644 --- a/test/commonunittest/UTTest_dm_anonymous.cpp +++ b/test/commonunittest/UTTest_dm_anonymous.cpp @@ -164,7 +164,7 @@ HWTEST_F(DmAnonymousTest, IsNumberString_003, testing::ext::TestSize.Level0) HWTEST_F(DmAnonymousTest, GetErrorString_001, testing::ext::TestSize.Level0) { int failedReason = 96929744; - std::string errorMessage = "dm process execution failed."; + std::string errorMessage = "dm process execution failed..."; std::string ret = GetErrorString(failedReason); EXPECT_EQ(ret, errorMessage); } @@ -241,6 +241,24 @@ HWTEST_F(DmAnonymousTest, IsInt32_002, testing::ext::TestSize.Level0) EXPECT_EQ(ret, false); } +/** + * @tc.name: IsUint32_001 + * @tc.desc: Return false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAnonymousTest, IsUint32_001, testing::ext::TestSize.Level0) +{ + std::string str = R"( + { + "AUTHTYPE" : "authtypeTest" + } + )"; + nlohmann::json jsonObj = nlohmann::json::parse(str, nullptr, false); + bool ret = IsUint32(jsonObj, TAG_AUTH_TYPE); + EXPECT_EQ(ret, false); +} + /** * @tc.name: IsInt64_001 * @tc.desc: Return true @@ -367,6 +385,120 @@ HWTEST_F(DmAnonymousTest, IsBool_002, testing::ext::TestSize.Level0) bool ret = IsBool(jsonObj, TAG_CRYPTO_SUPPORT); EXPECT_EQ(ret, false); } + +/** + * @tc.name: ConvertCharArray2String_001 + * @tc.desc: Return false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAnonymousTest, ConvertCharArray2String_001, testing::ext::TestSize.Level0) +{ + constexpr uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; + char *srcData = nullptr; + uint32_t srcLen = 0; + std::string ret = ConvertCharArray2String(srcData, srcLen); + EXPECT_EQ(ret, ""); + ret = ConvertCharArray2String(srcData, MAX_MESSAGE_LEN + 1); + EXPECT_EQ(ret, ""); + char srcData2[20] = {"1234"}; + ret = ConvertCharArray2String(srcData2, MAX_MESSAGE_LEN + 1); + EXPECT_EQ(ret, ""); + uint32_t srcLen2 = 20; + ret = ConvertCharArray2String(srcData2, srcLen); + EXPECT_EQ(ret, ""); + ret = ConvertCharArray2String(srcData, srcLen2); + EXPECT_EQ(ret, ""); + ret = ConvertCharArray2String(srcData2, srcLen2); + EXPECT_EQ(ret, "1234"); +} + +HWTEST_F(DmAnonymousTest, StringToInt_001, testing::ext::TestSize.Level0) +{ + std::string str = "12344"; + int32_t base = 10; + int32_t ret = StringToInt(str, base); + EXPECT_EQ(ret, 12344); +} + +HWTEST_F(DmAnonymousTest, StringToInt_002, testing::ext::TestSize.Level0) +{ + std::string str; + int32_t base = 10; + int32_t ret = StringToInt(str, base); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DmAnonymousTest, StringToInt64_001, testing::ext::TestSize.Level0) +{ + std::string str; + int32_t base = 10; + int64_t ret = StringToInt64(str, base); + EXPECT_EQ(ret, 0); +} + + +HWTEST_F(DmAnonymousTest, ParseMapFromJsonString_001, testing::ext::TestSize.Level0) +{ + std::string jsonStr = R"( + { + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "CRYPTOSUPPORT" : "cryptosupportTest", + "credentialType" : 1, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "hello", + "pkInfoSignature" : "world", + "pkInfo" : "pkginfo", + "peerDeviceId" : "3515656546" + } + ] + } + )"; + std::map paramMap; + nlohmann::json jsonObj = nlohmann::json::parse(jsonStr, nullptr, false); + ParseMapFromJsonString(jsonStr, paramMap); + EXPECT_GE(paramMap.size(), 0); +} + +HWTEST_F(DmAnonymousTest, ParseMapFromJsonString_002, testing::ext::TestSize.Level0) +{ + std::string jsonStr = R"( + { + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "CRYPTOSUPPORT" : "cryptosupportTest", + "credentialType" : 1, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "hello", + "pkInfoSignature" : "world", + "pkInfo" : "pkginfo", + "peerDeviceId" : "3515656546" + } + ] + )"; + std::map paramMap; + nlohmann::json jsonObj = nlohmann::json::parse(jsonStr, nullptr, false); + ParseMapFromJsonString(jsonStr, paramMap); + EXPECT_EQ(paramMap.size(), 0); +} + +HWTEST_F(DmAnonymousTest, ParseMapFromJsonString_003, testing::ext::TestSize.Level0) +{ + std::string jsonStr = ""; + std::map paramMap; + nlohmann::json jsonObj = nlohmann::json::parse(jsonStr, nullptr, false); + ParseMapFromJsonString(jsonStr, paramMap); + EXPECT_EQ(paramMap.size(), 0); +} } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 86619a9caf31956b954ba241fc2c734707fbb1c3..a219f1a5e637ad33425465419a0328787616f114 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -15,17 +15,39 @@ #include "UTTest_dm_auth_manager_first.h" -#include "nlohmann/json.hpp" - -#include "dm_log.h" -#include "dm_constants.h" -#include "dm_auth_manager.h" #include "auth_message_processor.h" +#include "common_event_support.h" #include "device_manager_service_listener.h" +#include "dm_auth_manager.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_radar_helper.h" +#include "nlohmann/json.hpp" #include "softbus_error_code.h" +static bool g_reportAuthOpenSessionReturnBoolValue = false; +static bool g_reportAuthConfirmBoxReturnBoolValue = false; + +constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5"; +constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; +constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; + +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; + +bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) +{ + return g_reportAuthOpenSessionReturnBoolValue; +} + +bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) +{ + return g_reportAuthConfirmBoxReturnBoolValue; +} class SoftbusStateCallbackTest : public ISoftbusStateCallback { public: @@ -33,87 +55,44 @@ public: virtual ~SoftbusStateCallbackTest() {} void OnDeviceOnline(std::string deviceId, int32_t authForm) {} void OnDeviceOffline(std::string deviceId) {} + void DeleteOffLineTimer(std::string udidHash) {} }; void DmAuthManagerTest::SetUp() { authManager_->authMessageProcessor_ = std::make_shared(authManager_); authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); + authManager_->authMessageProcessor_->authRequestContext_ = std::make_shared(); authManager_->authRequestContext_ = std::make_shared(); authManager_->authRequestState_ = std::make_shared(); authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseState_ = std::make_shared(); authManager_->hiChainAuthConnector_ = std::make_shared(); authManager_->softbusConnector_ = std::make_shared(); - authManager_->softbusConnector_->GetSoftbusSession()-> - RegisterSessionCallback(std::shared_ptr(authManager_)); + authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback( + std::shared_ptr(authManager_)); authManager_->timer_ = std::make_shared(); } -void DmAuthManagerTest::TearDown() -{ -} +void DmAuthManagerTest::TearDown() {} void DmAuthManagerTest::SetUpTestCase() { + softbusSessionMock_ = std::make_shared(); + DmSoftbusSession::dmSoftbusSession = softbusSessionMock_; + appManagerMock_ = std::make_shared(); + DmAppManager::dmAppManager = appManagerMock_; } void DmAuthManagerTest::TearDownTestCase() { + DmSoftbusSession::dmSoftbusSession = nullptr; + softbusSessionMock_ = nullptr; + DmAppManager::dmAppManager = nullptr; + appManagerMock_ = nullptr; } namespace { const int32_t MIN_PIN_CODE = 100000; const int32_t MAX_PIN_CODE = 999999; -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - std::string networkId = "222"; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "222"; - authManager_->authRequestState_ = nullptr; - authManager_->authResponseContext_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = false; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->authResponseContext_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = true; - authManager_->authRequestContext_ = std::make_shared(); - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = false; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "networkId"; - authManager_->authRequestState_ = nullptr; - authManager_->authResponseContext_ = nullptr; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, SOFTBUS_IPC_ERR); -} - HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_001, testing::ext::TestSize.Level0) { std::string name = "test"; @@ -134,38 +113,107 @@ HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_002, testing::ext::TestSiz ASSERT_TRUE(authManager_->authRequestState_ != nullptr); } +HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_003, testing::ext::TestSize.Level0) +{ + std::string name = "test"; + std::shared_ptr authRequestState = std::make_shared(); + authManager_->SetAuthRequestState(authRequestState); + authManager_->HandleAuthenticateTimeout(name); + std::shared_ptr authResponseState = std::make_shared(); + authManager_->SetAuthResponseState(authResponseState); + ASSERT_TRUE(authManager_->authRequestState_ != nullptr); +} + +HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_004, testing::ext::TestSize.Level0) +{ + std::string name = "test"; + authManager_->authRequestContext_->reason = DM_OK; + std::shared_ptr requestInitState = std::make_shared(); + EXPECT_CALL(*requestInitState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE)); + authManager_->authRequestState_ = requestInitState; + authManager_->HandleAuthenticateTimeout(name); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_TIME_OUT); + + std::shared_ptr authResponseInitState = std::make_shared(); + EXPECT_CALL(*authResponseInitState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); + authManager_->authResponseState_ = authResponseInitState; + authManager_->HandleAuthenticateTimeout(name); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_TIME_OUT); + + authManager_->authResponseState_ = nullptr; + authManager_->HandleAuthenticateTimeout(name); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_TIME_OUT); +} + HWTEST_F(DmAuthManagerTest, EstablishAuthChannel_001, testing::ext::TestSize.Level0) { - std::shared_ptr sessionSession = std::shared_ptr(); - std::shared_ptr authRequestContext = std::make_shared(); std::string deviceId1; + authManager_->AbilityNegotiate(); + g_reportAuthOpenSessionReturnBoolValue = false; int32_t ret = authManager_->EstablishAuthChannel(deviceId1); ASSERT_EQ(ret, DM_OK); } +HWTEST_F(DmAuthManagerTest, EstablishAuthChannel_002, testing::ext::TestSize.Level0) +{ + std::string deviceId; + authManager_->authResponseContext_ = nullptr; + authManager_->authRequestContext_ = nullptr; + authManager_->authRequestState_ = nullptr; + g_reportAuthOpenSessionReturnBoolValue = true; + int32_t ret = authManager_->EstablishAuthChannel(deviceId); + g_reportAuthOpenSessionReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + HWTEST_F(DmAuthManagerTest, StartAuthProcess_001, testing::ext::TestSize.Level0) { std::shared_ptr authResponseState = std::make_shared(); authManager_->SetAuthResponseState(authResponseState); int32_t action = 0; - authManager_->StartAuthProcess(action); - bool ret = authManager_->authRequestContext_->deviceName.empty(); - ASSERT_EQ(ret, true); + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = DEVICE; + int32_t ret = authManager_->StartAuthProcess(action); + ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, StartAuthProcess_002, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::make_shared(); - authManager_->authResponseState_ = std::make_shared(); + std::shared_ptr authResponseState = std::make_shared(); authManager_->SetAuthResponseState(authResponseState); - authManager_->authResponseContext_->sessionId = 111; - authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authManager_); - int32_t action = 1; + int32_t action = 0; + g_reportAuthConfirmBoxReturnBoolValue = true; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = APP + 1; int32_t ret = authManager_->StartAuthProcess(action); + g_reportAuthConfirmBoxReturnBoolValue = false; ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, StartAuthProcess_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = std::make_shared(); + authManager_->SetAuthResponseState(authResponseState); + int32_t action = 0; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; + int32_t ret = authManager_->StartAuthProcess(action); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, StartAuthProcess_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = std::make_shared(); + authManager_->SetAuthResponseState(authResponseState); + int32_t action = 0; + authManager_->remoteVersion_ = "4.1.5.0"; + int32_t ret = authManager_->StartAuthProcess(action); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, StartAuthProcess_005, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; int32_t action = 1; @@ -214,6 +262,9 @@ HWTEST_F(DmAuthManagerTest, AddMember_002, testing::ext::TestSize.Level0) authManager_->authResponseContext_ = nullptr; int32_t ret = authManager_->AddMember(pinCode); ASSERT_EQ(ret, ERR_DM_FAILED); + authManager_->isAddingMember_ = true; + ret = authManager_->AddMember(pinCode); + ASSERT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, JoinNetwork_001, testing::ext::TestSize.Level0) @@ -235,10 +286,7 @@ HWTEST_F(DmAuthManagerTest, JoinNetwork_001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, JoinNetwork_002, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; - int32_t userId = 1; - authManager_->UserSwitchEventCallback(userId); authManager_->AuthenticateFinish(); - authManager_->CancelDisplay(); int32_t ret = authManager_->JoinNetwork(); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -273,8 +321,8 @@ HWTEST_F(DmAuthManagerTest, GetPinCode_002, testing::ext::TestSize.Level0) authManager_->ShowAuthInfoDialog(); authManager_->ShowStartAuthDialog(); int32_t code = 0; - authManager_->GetPinCode(code); - ASSERT_EQ(code, ERR_DM_AUTH_NOT_START); + int32_t ret = authManager_->GetPinCode(code); + ASSERT_NE(code, ERR_DM_TIME_OUT); } HWTEST_F(DmAuthManagerTest, SetPageId_001, testing::ext::TestSize.Level0) @@ -295,8 +343,23 @@ HWTEST_F(DmAuthManagerTest, SetPageId_002, testing::ext::TestSize.Level0) int32_t status = 2; authManager_->OnMemberJoin(requestId, status); authManager_->OnDataReceived(sessionId, message); + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->OnDataReceived(sessionId, message); + authManager_->authRequestState_ = nullptr; + authManager_->authResponseState_ = std::make_shared(); + authManager_->OnDataReceived(sessionId, message); int32_t ret = authManager_->SetPageId(pageId); - ASSERT_EQ(ret, ERR_DM_AUTH_NOT_START); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, SetPageId_003, testing::ext::TestSize.Level0) +{ + int32_t pageId = 123; + authManager_->authResponseContext_ = nullptr; + int32_t ret = authManager_->SetPageId(pageId); + ASSERT_NE(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, SetReasonAndFinish_001, testing::ext::TestSize.Level0) @@ -454,6 +517,52 @@ HWTEST_F(DmAuthManagerTest, AuthenticateDevice_003, testing::ext::TestSize.Level ASSERT_EQ(ret, DM_OK); } +HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "UnAuthenticateDevice_001"; + int32_t bindLevel = DEVICE; + int32_t ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + pkgName = "com.ohos.test"; + authManager_->isAuthenticateDevice_ = false; + ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + authManager_->authRequestState_ = nullptr; + authManager_->authResponseContext_ = nullptr; + ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + bindLevel = 0; + ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, UnBindDevice_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "UnAuthenticateDevice_001"; + int32_t bindLevel = DEVICE; + int32_t ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + pkgName = "com.ohos.test"; + authManager_->isAuthenticateDevice_ = false; + ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + authManager_->authRequestState_ = nullptr; + authManager_->authResponseContext_ = nullptr; + ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + bindLevel = 0; + ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); +} + HWTEST_F(DmAuthManagerTest, GenerateGroupName_001, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; @@ -502,6 +611,38 @@ HWTEST_F(DmAuthManagerTest, GetIsCryptoSupport_003, testing::ext::TestSize.Level ASSERT_EQ(ret, false); } +HWTEST_F(DmAuthManagerTest, GetIsCryptoSupport_004, testing::ext::TestSize.Level0) +{ + authManager_->isCryptoSupport_ = true; + authManager_->authRequestState_ = nullptr; + std::shared_ptr authResponseInitState = std::make_shared(); + EXPECT_CALL(*authResponseInitState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); + authManager_->authResponseState_ = authResponseInitState; + bool ret = authManager_->GetIsCryptoSupport(); + ASSERT_TRUE(ret); + + EXPECT_CALL(*authResponseInitState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE_DONE)); + ret = authManager_->GetIsCryptoSupport(); + ASSERT_FALSE(ret); + + std::shared_ptr requestFinishState = std::make_shared(); + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE)); + authManager_->authRequestState_ = requestFinishState; + ret = authManager_->GetIsCryptoSupport(); + ASSERT_FALSE(ret); + + EXPECT_CALL(*requestFinishState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE_DONE)); + ret = authManager_->GetIsCryptoSupport(); + ASSERT_FALSE(ret); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_INIT)); + ret = authManager_->GetIsCryptoSupport(); + ASSERT_TRUE(ret); +} + HWTEST_F(DmAuthManagerTest, OnUserOperation_001, testing::ext::TestSize.Level0) { int32_t action = 0; @@ -559,44 +700,6 @@ HWTEST_F(DmAuthManagerTest, OnUserOperation_007, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -HWTEST_F(DmAuthManagerTest, UnBindDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string udidHash = "udidHash"; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnBindDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string udidHash = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = true; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, UnBindDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string udidHash = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = false; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnBindDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string udidHash = "networkId"; - authManager_->authRequestState_ = nullptr; - authManager_->authResponseContext_ = nullptr; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - HWTEST_F(DmAuthManagerTest, RequestCredential001, testing::ext::TestSize.Level0) { authManager_->hiChainAuthConnector_ = std::make_shared(); @@ -635,67 +738,12 @@ HWTEST_F(DmAuthManagerTest, ImportCredential001, testing::ext::TestSize.Level0) ASSERT_NE(ret, DM_OK); } -HWTEST_F(DmAuthManagerTest, EstablishUnbindChannel001, testing::ext::TestSize.Level0) -{ - std::string deviceIdHash = "deviceIdHash"; - int32_t ret = authManager_->EstablishUnbindChannel(deviceIdHash); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, RequestSyncDeleteAcl001, testing::ext::TestSize.Level0) -{ - authManager_->RequestSyncDeleteAcl(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, RequestSyncDeleteAcl002, testing::ext::TestSize.Level0) -{ - authManager_->timer_ = nullptr; - authManager_->RequestSyncDeleteAcl(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SrcSyncDeleteAclDonel001, testing::ext::TestSize.Level0) -{ - authManager_->isFinishOfLocal_ = true; - authManager_->authResponseContext_->reply = 0; - authManager_->SrcSyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SinkSyncDeleteAclDone001, testing::ext::TestSize.Level0) -{ - authManager_->isFinishOfLocal_ = true; - authManager_->authResponseContext_->reply = 0; - authManager_->SinkSyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SyncDeleteAclDone001, testing::ext::TestSize.Level0) -{ - authManager_->SyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SyncDeleteAclDone002, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = nullptr; - authManager_->SyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, ResponseCredential001, testing::ext::TestSize.Level0) { authManager_->ResponseCredential(); ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, ResponseSyncDeleteAcl001, testing::ext::TestSize.Level0) -{ - authManager_->ResponseSyncDeleteAcl(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, AuthDeviceTransmit001, testing::ext::TestSize.Level0) { int64_t requestId = 0; @@ -739,68 +787,68 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceTransmit004, testing::ext::TestSize.Level0 HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish001, testing::ext::TestSize.Level0) { - authManager_->authRequestState_ = std::make_shared(); - authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish002, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); + authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->confirmOperation = 0; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH; authManager_->authResponseContext_->haveCredential = true; - authManager_->authResponseContext_->bindLevel = 3; + authManager_->authResponseContext_->bindLevel = APP; authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish003, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->confirmOperation = 6; - authManager_->authResponseContext_->haveCredential = true; - authManager_->authResponseContext_->bindLevel = 3; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + authManager_->authResponseContext_->hostPkgName = ""; authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); + + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); + + authManager_->authResponseContext_->bindLevel = SERVICE; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish004, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->confirmOperation = 6; authManager_->authResponseContext_->haveCredential = false; - authManager_->authResponseContext_->bindLevel = 3; + authManager_->authResponseContext_->bindLevel = APP; authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); + + authManager_->authResponseContext_->hostPkgName = ""; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); + + authManager_->authResponseContext_->bindLevel = SERVICE; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); + + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); } -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish005, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish002, testing::ext::TestSize.Level0) { - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authUiStateMgr_ = std::make_shared(listener); + authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH; authManager_->authResponseContext_->haveCredential = true; + authManager_->authResponseContext_->bindLevel = APP; + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + EXPECT_EQ(authManager_->authRequestContext_->reason, DM_OK); -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish006, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authResponseContext_->isOnline = false; + authManager_->authRequestContext_->reason = ERR_DM_FAILED; authManager_->authResponseContext_->haveCredential = false; authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, SinkAuthDeviceFinish001, testing::ext::TestSize.Level0) @@ -847,7 +895,6 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceFinish003, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, AuthDeviceError001, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = nullptr; - authManager_->authResponseState_ = std::make_shared(); int64_t requestId = 0; int32_t errorCode = -1; authManager_->AuthDeviceError(requestId, errorCode); @@ -857,7 +904,7 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceError001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, AuthDeviceError002, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = std::make_shared(); - authManager_->authResponseState_ = nullptr; + authManager_->authResponseState_ = std::make_shared(); authManager_->authResponseContext_->authType = 5; int64_t requestId = 0; int32_t errorCode = -1; @@ -869,7 +916,7 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceError003, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = std::make_shared(); authManager_->authResponseState_ = nullptr; - authManager_->authResponseContext_->authType = 6; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->authResponseContext_->requestId = 2; int64_t requestId = 0; int32_t errorCode = -1; @@ -877,6 +924,47 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceError003, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isAuthDevice_, false); } +HWTEST_F(DmAuthManagerTest, AuthDeviceError004, testing::ext::TestSize.Level0) +{ + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->requestId = 3; + authManager_->authTimes_ = 3; + int64_t requestId = 0; + int32_t errorCode = ERR_DM_FAILED; + authManager_->AuthDeviceError(requestId, errorCode); + ASSERT_EQ(authManager_->authResponseContext_->state, AuthState::AUTH_REQUEST_JOIN); +} + +HWTEST_F(DmAuthManagerTest, AuthDeviceError005, testing::ext::TestSize.Level0) +{ + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->requestId = 3; + authManager_->authTimes_ = 0; + int64_t requestId = authManager_->authResponseContext_->requestId + 1; + int32_t errorCode = DM_OK; + uint32_t sessionKeyLen = 0; + authManager_->AuthDeviceError(requestId, errorCode); + authManager_->AuthDeviceSessionKey(requestId, nullptr, sessionKeyLen); + ASSERT_EQ(authManager_->isAuthDevice_, false); +} + +HWTEST_F(DmAuthManagerTest, AuthDeviceError006, testing::ext::TestSize.Level0) +{ + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->requestId = 3; + authManager_->authTimes_ = 0; + int64_t requestId = authManager_->authResponseContext_->requestId; + int32_t errorCode = DM_OK; + authManager_->AuthDeviceError(requestId, errorCode); + ASSERT_EQ(authManager_->isAuthDevice_, false); +} + HWTEST_F(DmAuthManagerTest, AuthDeviceSessionKey001, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = std::make_shared(); @@ -901,68 +989,78 @@ HWTEST_F(DmAuthManagerTest, CompatiblePutAcl001, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, CommonEventCallback001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, CompatiblePutAcl002, testing::ext::TestSize.Level0) { - authManager_->authRequestState_ = std::make_shared(); - int32_t userId = 0; - authManager_->CommonEventCallback(userId, ""); + authManager_->action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + authManager_->CompatiblePutAcl(); ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, AccountIdLogoutEventCallback001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, CompatiblePutAcl003, testing::ext::TestSize.Level0) { - int32_t userId = 0; - authManager_->AccountIdLogoutEventCallback(userId); + authManager_->action_ = USER_OPERATION_TYPE_ALLOW_AUTH; + authManager_->CompatiblePutAcl(); ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, UserSwitchEventCallback001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt001, testing::ext::TestSize.Level0) { - int32_t userId = 0; - authManager_->UserSwitchEventCallback(userId); + int32_t sessionId = 0; + authManager_->ProcRespNegotiateExt(sessionId); ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, UserChangeEventCallback001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, GenerateBindResultContent001, testing::ext::TestSize.Level0) { - int32_t userId = 0; - authManager_->UserChangeEventCallback(userId); - ASSERT_EQ(authManager_->isAuthDevice_, false); + auto ret = authManager_->GenerateBindResultContent(); + ASSERT_EQ(ret.empty(), false); } -HWTEST_F(DmAuthManagerTest, HandleSyncDeleteTimeout001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, GenerateBindResultContent002, testing::ext::TestSize.Level0) { - std::string name; - authManager_->HandleSyncDeleteTimeout(name); - ASSERT_EQ(authManager_->isAuthDevice_, false); + authManager_->remoteDeviceId_ = "test"; + auto ret = authManager_->GenerateBindResultContent(); + ASSERT_FALSE(ret.empty()); } -HWTEST_F(DmAuthManagerTest, DeleteAcl001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string deviceId; - int32_t ret = authManager_->DeleteAcl(pkgName, deviceId); - ASSERT_NE(ret, DM_OK); -} -HWTEST_F(DmAuthManagerTest, ProRespNegotiateExt001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, OnScreenLocked001, testing::ext::TestSize.Level0) { - int32_t sessionId = 0; - authManager_->ProRespNegotiateExt(sessionId); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + authManager_->authResponseContext_ = nullptr; + authManager_->authRequestState_ = nullptr; + authManager_->OnScreenLocked(); -HWTEST_F(DmAuthManagerTest, ProRespNegotiate001, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 0; - authManager_->ProRespNegotiate(sessionId); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authRequestState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; + authManager_->OnScreenLocked(); -HWTEST_F(DmAuthManagerTest, GenerateBindResultContent001, testing::ext::TestSize.Level0) -{ - auto ret = authManager_->GenerateBindResultContent(); - ASSERT_EQ(ret.empty(), false); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->OnScreenLocked(); + + authManager_->authResponseContext_->authType = AUTH_REQUEST_INIT; + std::shared_ptr requestFinishState = std::make_shared(); + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE)); + authManager_->authRequestState_ = requestFinishState; + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_INIT)); + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_JOIN)); + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_JOIN)); + authManager_->authUiStateMgr_ = nullptr; + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE_DONE)); + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); + authManager_->OnScreenLocked(); + EXPECT_EQ(authManager_->authResponseContext_->state, STATUS_DM_AUTH_DEFAULT); } HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived001, testing::ext::TestSize.Level0) @@ -978,7 +1076,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived002, testing::ext::TestSize. int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_DATA] = 123; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -989,7 +1087,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived003, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = "123"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1001,7 +1099,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived004, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = "123"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1013,47 +1111,11 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived005, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = 123; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, OnUnbindSessionOpened001, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 1; - std::string name = "nameTest"; - std::string networkId = "159753681387291"; - std::string pkgName = "com.ohos.test"; - PeerSocketInfo info = { - .name = const_cast(name.c_str()), - .pkgName = const_cast(pkgName.c_str()), - .networkId = const_cast(networkId.c_str()), - }; - authManager_->authResponseState_ = nullptr; - authManager_->authRequestState_ = nullptr; - authManager_->timer_ = nullptr; - authManager_->OnUnbindSessionOpened(sessionId, info); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, OnUnbindSessionOpened002, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 1; - std::string name = "nameTest"; - std::string networkId = "159753681387291"; - std::string pkgName = "com.ohos.test"; - PeerSocketInfo info = { - .name = const_cast(name.c_str()), - .pkgName = const_cast(pkgName.c_str()), - .networkId = const_cast(networkId.c_str()), - }; - authManager_->authResponseState_ = std::make_shared(); - authManager_->authRequestState_ = std::make_shared(); - authManager_->timer_ = nullptr; - authManager_->OnUnbindSessionOpened(sessionId, info); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, DeleteGroup001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -1067,45 +1129,24 @@ HWTEST_F(DmAuthManagerTest, DeleteGroup002, testing::ext::TestSize.Level0) std::string pkgName = "pkgName"; std::string deviceId; int32_t ret = authManager_->DeleteGroup(pkgName, deviceId); - ASSERT_NE(ret, DM_OK); + ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, PutAccessControlList001, testing::ext::TestSize.Level0) { authManager_->PutAccessControlList(); ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, BindSocketFail_001, testing::ext::TestSize.Level0) -{ - authManager_->BindSocketFail(); - ASSERT_EQ(authManager_->isFinishOfLocal_, false); -} - -HWTEST_F(DmAuthManagerTest, BindSocketSuccess_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - authManager_->authResponseState_ = nullptr; - authManager_->authRequestState_ = std::make_shared(); - authManager_->BindSocketSuccess(socket); - ASSERT_EQ(authManager_->authRequestContext_->sessionId, socket); -} - -HWTEST_F(DmAuthManagerTest, BindSocketSuccess_002, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - authManager_->authResponseState_ = std::make_shared(); - authManager_->authRequestState_ = nullptr; - authManager_->BindSocketSuccess(socket); - ASSERT_NE(authManager_->authRequestContext_->sessionId, socket); -} - -HWTEST_F(DmAuthManagerTest, SyncDeleteAcl_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::string deviceId = "deviceId"; - authManager_->SyncDeleteAcl(pkgName, deviceId); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->PutAccessControlList(); + ASSERT_EQ(authManager_->isAuthDevice_, false); + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->PutAccessControlList(); + ASSERT_EQ(authManager_->isAuthDevice_, false); + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->localAccountId = "ohosAnonymousUid"; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + authManager_->PutAccessControlList(); + ASSERT_EQ(authManager_->authResponseContext_->isIdenticalAccount, false); } HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_001, testing::ext::TestSize.Level0) @@ -1188,14 +1229,6 @@ HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_010, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } -HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_0011, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_->msgType = 505; - authManager_->authRequestState_ = std::make_shared(); - authManager_->ProcessSourceMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, false); -} - HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_0012, testing::ext::TestSize.Level0) { authManager_->authResponseContext_->msgType = 505; @@ -1204,14 +1237,6 @@ HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_0012, testing::ext::TestSize.Level0 ASSERT_EQ(authManager_->isFinishOfLocal_, true); } -HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_013, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_->msgType = 1000; - authManager_->authRequestState_ = std::make_shared(); - authManager_->ProcessSourceMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_001, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = std::make_shared(); @@ -1275,22 +1300,201 @@ HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_007, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } -HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_008, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, ConvertSrcVersion_001, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_ = std::make_shared(); - authManager_->authResponseContext_->msgType = 505; - authManager_->authResponseState_ = std::make_shared(); - authManager_->ProcessSinkMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); + std::string version = ""; + std::string edition = "test"; + EXPECT_EQ(authManager_->ConvertSrcVersion(version, edition), "test"); + + edition = ""; + EXPECT_NE(authManager_->ConvertSrcVersion(version, edition), "test"); + + version = "test"; + EXPECT_EQ(authManager_->ConvertSrcVersion(version, edition), "test"); +} + +HWTEST_F(DmAuthManagerTest, GetTaskTimeout_001, testing::ext::TestSize.Level0) +{ + int32_t taskTimeOut = 0; + authManager_->SetAuthType(AUTH_TYPE_CRE); + EXPECT_EQ(authManager_->GetTaskTimeout("test", taskTimeOut), taskTimeOut); + + taskTimeOut = 1000; + + authManager_->SetAuthType(AUTH_TYPE_IMPORT_AUTH_CODE); + EXPECT_EQ(authManager_->GetTaskTimeout("test", taskTimeOut), taskTimeOut); + + authManager_->SetAuthType(AUTH_TYPE_IMPORT_AUTH_CODE); + EXPECT_EQ(authManager_->GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, taskTimeOut), 20); +} + +HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize.Level0) +{ + std::string extra = R"({"extra": {"bindLevel": "123"}})"; + nlohmann::json jsonObject; + jsonObject["bindLevel"] = 1; + int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, DM_OK); + + extra = SafetyDump(jsonObject); + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); + ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); + ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, DM_OK); + + jsonObject["bindLevel"] = 15; + extra = SafetyDump(jsonObject); + ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_004, testing::ext::TestSize.Level0) +{ + int32_t authType = 0; + std::string extra = R"({"extra": {"bindLevel": 789}})"; + std::string pkgName = "ohos_test_004"; + std::string deviceId = "512156"; + authManager_->importPkgName_ = "ohos_test_004"; + authManager_->importAuthCode_ = "156161"; + authManager_->authRequestState_ = nullptr; + authManager_->authResponseState_ = nullptr; + std::shared_ptr listener = std::make_shared(); + authManager_->authUiStateMgr_ = std::make_shared(listener); + authManager_->authenticationMap_.insert(std::pair>(authType, nullptr)); + int32_t ret = authManager_->AuthenticateDevice(pkgName, authType, deviceId, extra); + ASSERT_EQ(ret, DM_OK); } -HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_009, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, StopAuthenticateDevice_001, testing::ext::TestSize.Level0) { + std::string pkgName; + int32_t ret = authManager_->StopAuthenticateDevice(pkgName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + pkgName = "pkgName_001"; + int64_t requestId = 12; + int32_t status = 0; + int32_t sessionId = 1; + std::string peerUdidHash; + if (authManager_->timer_ == nullptr) { + authManager_->timer_ = std::make_shared(); + } + authManager_->authRequestState_ = std::make_shared(); authManager_->authResponseContext_ = std::make_shared(); - authManager_->authResponseContext_->msgType = 1000; - authManager_->authResponseState_ = std::make_shared(); - authManager_->ProcessSinkMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); + authManager_->authRequestContext_ = std::make_shared(); + authManager_->authRequestContext_->hostPkgName = pkgName; + authManager_->authResponseContext_->hostPkgName = pkgName; + authManager_->isAuthenticateDevice_ = true; + + authManager_->authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->MemberJoinAuthRequest(requestId, status); + authManager_->authResponseContext_->authType == AUTH_TYPE_NFC; + authManager_->authResponseContext_->requestId = requestId; + status = 1; + authManager_->authTimes_ = 3; + authManager_->MemberJoinAuthRequest(requestId, status); + status = 0; + authManager_->authTimes_ = 2; + authManager_->MemberJoinAuthRequest(requestId, status); + status = 0; + authManager_->HandleMemberJoinImportAuthCode(requestId, status); + authManager_->NegotiateRespMsg(DM_VERSION_5_0_1); + authManager_->NegotiateRespMsg(DM_VERSION_4_1_5_1); + authManager_->NegotiateRespMsg(DM_VERSION_5_0_2); + EXPECT_CALL(*softbusSessionMock_, GetPeerDeviceId(_, _)).WillOnce(Return(DM_OK)); + authManager_->GetPeerUdidHash(sessionId, peerUdidHash); + ret = authManager_->StopAuthenticateDevice(pkgName); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, GetBindLevel_001, testing::ext::TestSize.Level0) +{ + int32_t bindLevel = INVALIED_TYPE; + std::string udid; + authManager_->HandleDeviceNotTrust(udid); + udid = "988989"; + authManager_->HandleDeviceNotTrust(udid); + int32_t sessionId = 32166; + authManager_->ProcIncompatible(sessionId); + + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); + int32_t ret = authManager_->GetBindLevel(bindLevel); + ASSERT_EQ(ret, DEVICE); + + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); + ret = authManager_->GetBindLevel(bindLevel); + ASSERT_EQ(ret, APP); + + authManager_->authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->importAuthCode_ = "importAuthCode"; + authManager_->ProcessAuthRequest(sessionId); + + authManager_->authResponseContext_->authType == AUTH_TYPE_NFC; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = 0; + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->isAuthCodeReady = true; + authManager_->ProcessAuthRequest(sessionId); + + authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->isAuthCodeReady == false; + authManager_->ProcessAuthRequest(sessionId); + + bindLevel = SERVICE; + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); + ret = authManager_->GetBindLevel(bindLevel); + ASSERT_EQ(ret, SERVICE); +} + +HWTEST_F(DmAuthManagerTest, IsAuthFinish_001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + bool ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->reply = ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authed = true; + ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->authed = false; + ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->isAuthCodeReady = false; + ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->isAuthCodeReady = true; + ret = authManager_->IsAuthFinish(); + EXPECT_FALSE(ret); + + int32_t sessionId = 1; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->importAuthCode_= "importAuthCode"; + authManager_->ProcessAuthRequestExt(sessionId); + + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authed = true; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->reply = ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->isAuthCodeReady = true; + authManager_->ProcessAuthRequestExt(sessionId); } } // namespace } // namespace DistributedHardware diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.h b/test/commonunittest/UTTest_dm_auth_manager_first.h index d59bc805ddff35df78f4a60838dc250f42574e82..65ecabeed1e3f055dcecaaf3cd1fba87bc2c2db0 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.h +++ b/test/commonunittest/UTTest_dm_auth_manager_first.h @@ -16,9 +16,10 @@ #ifndef OHOS_DM_AUTH_MANAGER_FIRST_TEST_H #define OHOS_DM_AUTH_MANAGER_FIRST_TEST_H +#include +#include #include #include -#include #include "authentication.h" #include "softbus_session.h" @@ -32,6 +33,8 @@ #include "auth_message_processor.h" #include "dm_timer.h" #include "dm_auth_manager.h" +#include "softbus_session_mock.h" +#include "app_manager_mock.h" namespace OHOS { namespace DistributedHardware { @@ -49,6 +52,23 @@ public: std::shared_ptr authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); + static inline std::shared_ptr softbusSessionMock_ = nullptr; + static inline std::shared_ptr appManagerMock_ = nullptr; +}; + +class AuthRequestFinishStateMock : public AuthRequestFinishState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); +}; + +class AuthRequestInitStateMock : public AuthRequestInitState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); +}; + +class AuthResponseInitStateMock : public AuthResponseInitState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 3fec91f627810af23cef62d7ecabab27de4341a7..6263dd703d1949fc28f3e0add3c26432c25aeff3 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -15,19 +15,28 @@ #include "UTTest_dm_auth_manager_second.h" -#include "nlohmann/json.hpp" - -#include "dm_log.h" -#include "dm_constants.h" -#include "dm_auth_manager.h" #include "auth_message_processor.h" #include "device_manager_service_listener.h" +#include "dm_auth_manager.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" #include "softbus_error_code.h" +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { void DmAuthManagerTest::SetUp() { + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); authManager_->authMessageProcessor_ = std::make_shared(authManager_); authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); authManager_->authRequestContext_ = std::make_shared(); @@ -36,18 +45,35 @@ void DmAuthManagerTest::SetUp() authManager_->authResponseState_ = std::make_shared(); authManager_->hiChainAuthConnector_ = std::make_shared(); authManager_->softbusConnector_ = std::make_shared(); - authManager_->softbusConnector_->GetSoftbusSession()-> - RegisterSessionCallback(std::shared_ptr(authManager_)); + authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback( + std::shared_ptr(authManager_)); authManager_->timer_ = std::make_shared(); } void DmAuthManagerTest::TearDown() { + authManager_ = nullptr; } void DmAuthManagerTest::SetUpTestCase() { + hiChainConnectorMock_ = std::make_shared(); + DmHiChainConnector::dmHiChainConnector = hiChainConnectorMock_; + multipleUserConnectorMock_ = std::make_shared(); + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; + softbusConnectorMock_ = std::make_shared(); + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock_; + hiChainAuthConnectorMock_ = std::make_shared(); + DmHiChainAuthConnector::dmHiChainAuthConnector = hiChainAuthConnectorMock_; } void DmAuthManagerTest::TearDownTestCase() { + DmHiChainConnector::dmHiChainConnector = nullptr; + hiChainConnectorMock_ = nullptr; + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; + multipleUserConnectorMock_ = nullptr; + DmSoftbusConnector::dmSoftbusConnector = nullptr; + softbusConnectorMock_ = nullptr; + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; + hiChainAuthConnectorMock_ = nullptr; } namespace { @@ -78,36 +104,12 @@ HWTEST_F(DmAuthManagerTest, OnDataReceived_003, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } -HWTEST_F(DmAuthManagerTest, OnDataReceived_004, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 0; - nlohmann::json jsonObject; - jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(); - authManager_->OnDataReceived(sessionId, message); - authManager_->authRequestState_ = std::make_shared(); - authManager_->authResponseState_ = nullptr; - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - -HWTEST_F(DmAuthManagerTest, OnDataReceived_005, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 0; - nlohmann::json jsonObject; - jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(); - authManager_->OnDataReceived(sessionId, message); - authManager_->authRequestState_ = nullptr; - authManager_->authResponseState_ = std::make_shared(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - HWTEST_F(DmAuthManagerTest, OnDataReceived_007, testing::ext::TestSize.Level0) { int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnDataReceived(sessionId, message); authManager_->authRequestState_ = nullptr; authManager_->authResponseState_ = nullptr; @@ -233,6 +235,33 @@ HWTEST_F(DmAuthManagerTest, OnMemberJoin_008, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } +HWTEST_F(DmAuthManagerTest, OnMemberJoin_009, testing::ext::TestSize.Level0) +{ + int64_t requestId = 0; + int32_t status = DM_OK; + authManager_->authRequestState_ = nullptr; + authManager_->authTimes_ = 1; + std::shared_ptr authResponseInitStateMock = + std::make_shared(); + EXPECT_CALL(*authResponseInitStateMock, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_CREDENTIAL)); + authManager_->authResponseState_ = authResponseInitStateMock; + authManager_->authResponseContext_->isFinish = true; + authManager_->authResponseContext_->requestId = 0; + authManager_->OnMemberJoin(requestId, status); + ASSERT_TRUE(authManager_->authResponseContext_->isFinish); + + authManager_->authResponseContext_->isFinish = true; + authManager_->authResponseContext_->requestId = 1; + authManager_->OnMemberJoin(requestId, status); + ASSERT_FALSE(authManager_->authResponseContext_->isFinish); + + authManager_->authResponseContext_->isFinish = true; + status = ERR_DM_FAILED; + authManager_->OnMemberJoin(requestId, status); + ASSERT_FALSE(authManager_->authResponseContext_->isFinish); +} + HWTEST_F(DmAuthManagerTest, HandleMemberJoinImportAuthCode_001, testing::ext::TestSize.Level0) { int64_t requestId = 1; @@ -260,6 +289,15 @@ HWTEST_F(DmAuthManagerTest, HandleMemberJoinImportAuthCode_003, testing::ext::Te ASSERT_EQ(authManager_->isFinishOfLocal_, true); } +HWTEST_F(DmAuthManagerTest, HandleMemberJoinImportAuthCode_004, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + int32_t status = 0; + authManager_->authResponseContext_->requestId = 0; + authManager_->HandleMemberJoinImportAuthCode(requestId, status); + ASSERT_EQ(authManager_->isFinishOfLocal_, true); +} + HWTEST_F(DmAuthManagerTest, RespNegotiate_001, testing::ext::TestSize.Level0) { int64_t requestId = 1; @@ -295,6 +333,19 @@ HWTEST_F(DmAuthManagerTest, RespNegotiate_004, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } +HWTEST_F(DmAuthManagerTest, RespNegotiate_005, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseContext_->dmVersion = "4.1.5.1"; + authManager_->authResponseContext_->bindLevel = 0; + authManager_->RespNegotiate(requestId); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->RespNegotiate(requestId); + ASSERT_EQ(authManager_->isFinishOfLocal_, true); +} + HWTEST_F(DmAuthManagerTest, SendAuthRequest_001, testing::ext::TestSize.Level0) { int64_t sessionId = 1; @@ -329,6 +380,15 @@ HWTEST_F(DmAuthManagerTest, SendAuthRequest_003, testing::ext::TestSize.Level0) authManager_->authResponseContext_->deviceId = "deviceId"; authManager_->authResponseContext_->reply = -20018; authManager_->SendAuthRequest(sessionId); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 0; + authManager_->SendAuthRequest(sessionId); + authManager_->authResponseContext_->dmVersion = ""; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->SendAuthRequest(sessionId); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->SendAuthRequest(sessionId); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } @@ -341,6 +401,11 @@ HWTEST_F(DmAuthManagerTest, GetAuthRequestContext_001, testing::ext::TestSize.Le authManager_->authRequestContext_->localAccountId = "123456789"; authManager_->authResponseContext_->localUserId = 123456789; authManager_->GetAuthRequestContext(); + authManager_->authResponseContext_->isOnline = false; + authManager_->GetAuthRequestContext(); + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->haveCredential = true; + authManager_->GetAuthRequestContext(); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } @@ -371,6 +436,19 @@ HWTEST_F(DmAuthManagerTest, ProcessAuthRequestExt_004, testing::ext::TestSize.Le authManager_->authResponseContext_->isIdenticalAccount = false; authManager_->authResponseContext_->isAuthCodeReady = false; authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authed = true; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->authed = false; + authManager_->authResponseContext_->isOnline = false; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->authed = true; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isOnline = true; + authManager_->ProcessAuthRequestExt(sessionId); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } @@ -478,8 +556,8 @@ HWTEST_F(DmAuthManagerTest, GetConnectAddr_002, testing::ext::TestSize.Level0) std::string deviceId = "deviceId"; std::shared_ptr infoPtr = std::make_shared(); infoPtr->addrNum = 1; - authManager_->softbusConnector_->discoveryDeviceInfoMap_.insert(std::pair>(deviceId, infoPtr)); + authManager_->softbusConnector_->discoveryDeviceInfoMap_.insert( + std::pair>(deviceId, infoPtr)); auto ret = authManager_->GetConnectAddr(deviceId); ASSERT_EQ(ret.empty(), false); } @@ -649,7 +727,7 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_001, testing::ext::TestSize.Leve HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_002, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->authType = 5; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->importAuthCode_ = ""; authManager_->importPkgName_ = ""; authManager_->ShowStartAuthDialog(); @@ -658,7 +736,7 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_002, testing::ext::TestSize.Leve HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_003, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->authType = 5; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->importAuthCode_ = "123456"; authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; @@ -670,14 +748,29 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_003, testing::ext::TestSize.Leve HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_004, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->authType = 5; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->importAuthCode_ = "123456"; authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; - authManager_->authResponseContext_->dmVersion = ""; - authManager_->authResponseContext_->bindLevel = 0; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; + authManager_->ShowStartAuthDialog(); + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = APP + 1; + authManager_->ShowStartAuthDialog(); + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; + authManager_->ShowStartAuthDialog(); + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); + + authManager_->remoteVersion_ = "4.1.5.0"; authManager_->ShowStartAuthDialog(); - ASSERT_EQ(authManager_->authResponseContext_->bindLevel, 0); + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); } HWTEST_F(DmAuthManagerTest, ProcessPincode_001, testing::ext::TestSize.Level0) @@ -700,12 +793,31 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_002, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level0) { - int32_t pinCode = 123456; - authManager_->authResponseContext_->dmVersion = ""; - authManager_->authResponseContext_->bindLevel = 0; + int32_t pinCode = -1; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->authUiStateMgr_ = nullptr; + authManager_->importAuthCode_ = "123456"; + authManager_->importPkgName_ = "hostPkgName"; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; int32_t ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, ERR_DM_FAILED); + EXPECT_NE(ret, DM_OK); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = APP + 1; + ret = authManager_->ProcessPincode(pinCode); + EXPECT_NE(ret, DM_OK); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; + ret = authManager_->ProcessPincode(pinCode); + EXPECT_NE(ret, DM_OK); + + authManager_->remoteVersion_ = "4.1.5.0"; + ret = authManager_->ProcessPincode(pinCode); + EXPECT_NE(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level0) @@ -1211,7 +1323,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; jsonObject["targetPkgName"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1224,7 +1336,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_003, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1238,7 +1350,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_004, testing::ext::TestSize.Level0) jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1253,7 +1365,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_005, testing::ext::TestSize.Level0) jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1269,7 +1381,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_006, testing::ext::TestSize.Level0) jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = "1234"; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1286,7 +1398,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_007, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = "1234"; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1303,7 +1415,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_008, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1320,6 +1432,9 @@ HWTEST_F(DmAuthManagerTest, InitAuthState_001, testing::ext::TestSize.Level0) authManager_->timer_ = nullptr; authManager_->InitAuthState(pkgName, authType, deviceId, extra); ASSERT_EQ(authManager_->isFinishOfLocal_, true); + authManager_->timer_ = std::make_shared(); + authManager_->InitAuthState(pkgName, authType, deviceId, extra); + ASSERT_EQ(authManager_->isFinishOfLocal_, true); } HWTEST_F(DmAuthManagerTest, HandleSessionHeartbeat_001, testing::ext::TestSize.Level0) @@ -1333,62 +1448,95 @@ HWTEST_F(DmAuthManagerTest, HandleSessionHeartbeat_001, testing::ext::TestSize.L HWTEST_F(DmAuthManagerTest, CheckTrustState_001, testing::ext::TestSize.Level0) { authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->authType = 5; - authManager_->authResponseContext_->importAuthCode = ""; - authManager_->importAuthCode_ = ""; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_->importAuthCode = Crypto::Sha256(authManager_->importAuthCode_); int32_t ret = authManager_->CheckTrustState(); ASSERT_NE(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, CheckTrustState_002, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_->importAuthCode = "test"; int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); + ASSERT_NE(ret, DM_OK); } -HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = false; - authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; - int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(-1)); + bool ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); + + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(false)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); + + authManager_->authRequestContext_ = nullptr; + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); + + authManager_->authRequestContext_ = std::make_shared(); + authManager_->authResponseContext_->accountGroupIdHash = OLD_VERSION_ACCOUNT; + EXPECT_CALL(*multipleUserConnectorMock_, + GetCurrentAccountUserID()).WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_TRUE(ret); + + EXPECT_CALL(*hiChainConnectorMock_, IsDevicesInP2PGroup(_, _)).WillOnce(Return(true)); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->importAuthCode_= "importAuthCode"; + authManager_->importPkgName_ = "importPkgName"; + authManager_->authResponseContext_->hostPkgName = "importPkgName"; + authManager_->AbilityNegotiate(); + + EXPECT_CALL(*hiChainConnectorMock_, IsDevicesInP2PGroup(_, _)).WillOnce(Return(true)); + authManager_->importAuthCode_= ""; + authManager_->authResponseContext_->authType = AUTH_TYPE_NFC; + authManager_->AbilityNegotiate(); + + authManager_->authResponseContext_->isOnline = true; + EXPECT_CALL(*softbusConnectorMock_, CheckIsOnline(_)).WillOnce(Return(true)); + EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _)).WillOnce(Return(true)); + authManager_->GetAuthRequestContext(); + + nlohmann::json jsonPeerGroupIdObj; + jsonPeerGroupIdObj["groupId"] = "123456"; + authManager_->authResponseContext_->accountGroupIdHash = SafetyDump(jsonPeerGroupIdObj); + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); } -HWTEST_F(DmAuthManagerTest, CheckTrustState_004, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, GetAccountGroupIdHash_201, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = false; - authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; - authManager_->authResponseContext_->authType = 5; - authManager_->authResponseContext_->isAuthCodeReady = false; - int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(-1)); + auto ret = authManager_->GetAccountGroupIdHash(); + ASSERT_TRUE(ret.empty()); + + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + ret = authManager_->GetAccountGroupIdHash(); + ASSERT_FALSE(ret.empty()); } -HWTEST_F(DmAuthManagerTest, CheckTrustState_005, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = false; - authManager_->authResponseContext_->reply = 1; - authManager_->authResponseContext_->authType = 1; - authManager_->authResponseContext_->isAuthCodeReady = true; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->accountGroupIdHash = OLD_VERSION_ACCOUNT; + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); + ASSERT_EQ(ret, 1); } } // namespace } // namespace DistributedHardware diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.h b/test/commonunittest/UTTest_dm_auth_manager_second.h index d74d493377e14602f88051e133e7c3eedf6e45e9..0010746533a71643af03bf83bc93483a68c576ef 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.h +++ b/test/commonunittest/UTTest_dm_auth_manager_second.h @@ -16,22 +16,27 @@ #ifndef OHOS_DM_AUTH_MANAGER_SECOND_TEST_H #define OHOS_DM_AUTH_MANAGER_SECOND_TEST_H +#include +#include #include #include -#include +#include "auth_message_processor.h" +#include "auth_request_state.h" +#include "auth_response_state.h" #include "authentication.h" -#include "softbus_session.h" #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" +#include "dm_auth_manager.h" #include "dm_constants.h" -#include "softbus_connector.h" -#include "hichain_connector.h" -#include "auth_request_state.h" -#include "auth_response_state.h" -#include "auth_message_processor.h" #include "dm_timer.h" -#include "dm_auth_manager.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" +#include "hichain_connector_mock.h" +#include "multiple_user_connector_mock.h" +#include "softbus_connector_mock.h" +#include "hichain_auth_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -42,13 +47,16 @@ public: void SetUp(); void TearDown(); - std::shared_ptr softbusConnector = std::make_shared(); - std::shared_ptr listener = std::make_shared(); - std::shared_ptr hiChainConnector = std::make_shared(); - std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager_; + static inline std::shared_ptr hiChainConnectorMock_ = nullptr; + static inline std::shared_ptr multipleUserConnectorMock_ = nullptr; + static inline std::shared_ptr softbusConnectorMock_ = nullptr; + static inline std::shared_ptr hiChainAuthConnectorMock_ = nullptr; +}; - std::shared_ptr authManager_ = - std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); +class AuthResponseInitStateMock : public AuthResponseInitState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4c1150f5dc245dbca8fa0065594057ea4643d31 --- /dev/null +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -0,0 +1,497 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_auth_manager_third.h" + +#include "auth_message_processor.h" +#include "device_manager_service_listener.h" +#include "deviceprofile_connector.h" +#include "dm_auth_manager.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "dm_radar_helper.h" +#include "multiple_user_connector.h" +#include "nlohmann/json.hpp" +#include "softbus_error_code.h" + +static bool g_checkIsOnlineReturnBoolValue = false; +static bool g_checkSrcDevIdInAclForDevBindReturnBoolValue = false; +static bool g_isDevicesInP2PGroupReturnBoolValue = false; +static bool g_isIdenticalAccountReturnBoolValue = false; +static bool g_isLocked = false; +static bool g_reportAuthConfirmBoxReturnBoolValue = false; +static bool g_reportAuthInputPinBoxReturnBoolValue = false; +static int32_t g_bindType = INVALIED_TYPE; +static int32_t g_leftAclNumber = 0; +static int32_t g_trustNumber = 0; +static std::string g_accountId = ""; +static std::string g_createSimpleMessageReturnDataStr = "{}"; +static std::string g_peerUdidHash = ""; + +namespace OHOS { +namespace DistributedHardware { +std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) +{ + return g_createSimpleMessageReturnDataStr; +} + +bool DmAuthManager::IsIdenticalAccount() +{ + return g_isIdenticalAccountReturnBoolValue; +} + +void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash) +{ + peerUdidHash = g_peerUdidHash; +} + +bool DmAuthManager::IsScreenLocked() +{ + return g_isLocked; +} + +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +{ + return g_checkIsOnlineReturnBoolValue; +} + +DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string &pkgName, + const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel) +{ + DmOfflineParam offlineParam; + offlineParam.bindType = g_bindType; + offlineParam.leftAclNumber = g_leftAclNumber; + return offlineParam; +} + +bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) +{ + return g_reportAuthConfirmBoxReturnBoolValue; +} + +bool DmRadarHelper::ReportAuthInputPinBox(struct RadarInfo &info) +{ + return g_reportAuthInputPinBoxReturnBoolValue; +} + +int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) +{ + return g_trustNumber; +} + +std::string MultipleUserConnector::GetOhosAccountId(void) +{ + return g_accountId; +} + +bool HiChainConnector::IsDevicesInP2PGroup(const std::string &hostDevice, const std::string &peerDevice) +{ + return g_isDevicesInP2PGroupReturnBoolValue; +} + +bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) +{ + return g_checkSrcDevIdInAclForDevBindReturnBoolValue; +} + +void DmAuthManagerTest::SetUp() +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); + + authManager_->authMessageProcessor_ = std::make_shared(authManager_); + authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); + authManager_->authRequestContext_ = std::make_shared(); + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseState_ = std::make_shared(); + authManager_->hiChainAuthConnector_ = std::make_shared(); + authManager_->softbusConnector_ = std::make_shared(); + authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback( + std::shared_ptr(authManager_)); + authManager_->timer_ = std::make_shared(); +} +void DmAuthManagerTest::TearDown() +{ + g_bindType = INVALIED_TYPE; + g_createSimpleMessageReturnDataStr = "{}"; + g_isIdenticalAccountReturnBoolValue = false; + g_leftAclNumber = 0; + g_peerUdidHash = ""; +} +void DmAuthManagerTest::SetUpTestCase() {} +void DmAuthManagerTest::TearDownTestCase() {} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + int32_t sessionId = 0; + authManager_->remoteDeviceId_ = "ProcRespNegotiate001"; + authManager_->ProcRespNegotiate(sessionId); + + jsonObject[TAG_CRYPTO_SUPPORT] = false; + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; + authManager_->ProcRespNegotiate(sessionId); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_SUPPORT] = true; + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->importAuthCode_ = ""; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = false; + authManager_->ProcRespNegotiate(sessionId); + + authManager_->authResponseState_->context_ = std::make_shared(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->ProcRespNegotiate(sessionId); + + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_NAME] = "test"; + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->ProcRespNegotiate(sessionId); + EXPECT_FALSE(authManager_->authResponseContext_->isOnline); +} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + int32_t sessionId = 0; + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_SUPPORT] = true; + jsonObject[TAG_CRYPTO_NAME] = "test"; + jsonObject[TAG_CRYPTO_VERSION] = "test"; + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + g_isIdenticalAccountReturnBoolValue = false; + authManager_->remoteDeviceId_ = "ProcRespNegotiate002"; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->authResponseState_->context_->cryptoName = jsonObject[TAG_CRYPTO_NAME]; + authManager_->ProcRespNegotiate(sessionId); + EXPECT_FALSE(authManager_->authResponseContext_->isOnline); + + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_SUPPORT] = true; + jsonObject[TAG_CRYPTO_NAME] = "test"; + jsonObject[TAG_CRYPTO_VERSION] = "test"; + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); + g_isIdenticalAccountReturnBoolValue = false; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->authResponseState_->context_->cryptoName = jsonObject[TAG_CRYPTO_NAME]; + authManager_->authResponseState_->context_->cryptoVer = jsonObject[TAG_CRYPTO_VERSION]; + authManager_->ProcRespNegotiate(sessionId); + EXPECT_FALSE(authManager_->authResponseContext_->isOnline); +} + +HWTEST_F(DmAuthManagerTest, DeleteAcl001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string localUdid = "localUdid"; + std::string remoteUdid = "remoteUdid"; + int32_t sessionId = 0; + int32_t bindLevel = APP; + g_bindType = INVALIED_TYPE; + int32_t ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, ERR_DM_FAILED); + + bindLevel = APP; + g_bindType = APP_PEER_TO_PEER_TYPE; + g_leftAclNumber = 1; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + g_leftAclNumber = 0; + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + bindLevel = DEVICE; + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + g_leftAclNumber = 1; + g_peerUdidHash = "test"; + authManager_->DeleteOffLineTimer(sessionId); + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + authManager_->softbusConnector_ = nullptr; + authManager_->DeleteOffLineTimer(sessionId); + bindLevel = 0; + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DmAuthManagerTest, AuthenticateFinish001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_ = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + authManager_->authUiStateMgr_ = std::make_shared(listener); + authManager_->authResponseState_ = nullptr; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; + authManager_->authResponseContext_->isFinish = true; + authManager_->authRequestState_ = std::make_shared(); + g_checkIsOnlineReturnBoolValue = true; + g_trustNumber = 1; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->isFinish = false; + g_trustNumber = 1; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + g_checkIsOnlineReturnBoolValue = false; + g_trustNumber = 1; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->bindLevel = APP_PEER_TO_PEER_TYPE; + g_trustNumber = 1; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->remoteVersion_ = "4.1.5.0"; + g_trustNumber = 2; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + g_trustNumber = 0; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); +} + +HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authRequestState_ = nullptr; + authManager_->authResponseState_ = nullptr; + g_isLocked = true; + authManager_->ShowStartAuthDialog(); + ASSERT_EQ(authManager_->authResponseContext_->state, STATUS_DM_AUTH_DEFAULT); + + g_isLocked = false; + authManager_->authResponseContext_->targetDeviceName = "test"; + authManager_->ShowStartAuthDialog(); + ASSERT_EQ(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation001, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation002, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation003, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation004, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt001, testing::ext::TestSize.Level0) +{ + int32_t sessionId = 0; + g_accountId = "test"; + authManager_->authResponseContext_->localAccountId = "test"; + authManager_->authenticationMap_.clear(); + authManager_->authResponseContext_->hostPkgName = "test"; + authManager_->importPkgName_ = "test"; + authManager_->importAuthCode_ = "12345"; + authManager_->ProcRespNegotiateExt(sessionId); + ASSERT_EQ(authManager_->authResponseContext_->reply, ERR_DM_UNSUPPORTED_AUTH_TYPE); + g_accountId = ""; +} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt002, testing::ext::TestSize.Level0) +{ + authManager_->authenticationMap_.clear(); + authManager_->authResponseContext_->hostPkgName = "test"; + authManager_->authResponseContext_->localAccountId = "test"; + authManager_->importAuthCode_ = "12345"; + authManager_->importPkgName_ = "test"; + g_accountId = "ohosAnonymousUid"; + int32_t sessionId = 0; + authManager_->ProcRespNegotiateExt(sessionId); + ASSERT_EQ(authManager_->authResponseContext_->reply, ERR_DM_UNSUPPORTED_AUTH_TYPE); + g_accountId = ""; +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->importAuthCode_ = ""; + g_isIdenticalAccountReturnBoolValue = true; + int32_t ret = authManager_->CheckTrustState(); + g_isIdenticalAccountReturnBoolValue = false; + ASSERT_EQ(ret, 1); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_002, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + g_checkSrcDevIdInAclForDevBindReturnBoolValue = false; + g_isDevicesInP2PGroupReturnBoolValue = true; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + g_isDevicesInP2PGroupReturnBoolValue = false; + ASSERT_EQ(ret, 1); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + g_checkSrcDevIdInAclForDevBindReturnBoolValue = true; + g_isDevicesInP2PGroupReturnBoolValue = true; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + g_isDevicesInP2PGroupReturnBoolValue = false; + ASSERT_EQ(ret, 1); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_004, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_005, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_006, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = AUTH_TYPE_IMPORT_AUTH_CODE; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_007, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = AUTH_TYPE_IMPORT_AUTH_CODE; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, DM_OK); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.h b/test/commonunittest/UTTest_dm_auth_manager_third.h new file mode 100644 index 0000000000000000000000000000000000000000..e2875d6d8df48d7780a033eea56a1b8a183b7e18 --- /dev/null +++ b/test/commonunittest/UTTest_dm_auth_manager_third.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_AUTH_MANAGER_THIRD_TEST_H +#define OHOS_DM_AUTH_MANAGER_THIRD_TEST_H + +#include +#include +#include + +#include "authentication.h" +#include "softbus_session.h" +#include "device_manager_service_listener.h" +#include "dm_adapter_manager.h" +#include "dm_constants.h" +#include "softbus_connector.h" +#include "hichain_connector.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "auth_message_processor.h" +#include "dm_timer.h" +#include "dm_auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + std::shared_ptr authManager_; +}; + +class SoftbusStateCallbackMock : public ISoftbusStateCallback { +public: + SoftbusStateCallbackMock() {} + virtual ~SoftbusStateCallbackMock() {} + void OnDeviceOnline(std::string deviceId, int32_t authForm) {} + void OnDeviceOffline(std::string deviceId) {} + void DeleteOffLineTimer(std::string udidHash) {} +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index 04c49f6c660840a34b82c7b5eedf45ffcca8f63d..c2da8eabba059b9aa3eda4d56184252dc62988f1 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -17,11 +17,12 @@ #include "accesstoken_kit.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_credential_manager.cpp" #include "dm_random.h" -#include "parameter.h" #include "nativetoken_kit.h" -#include "token_setproc.h" +#include "parameter.h" #include "softbus_common.h" +#include "token_setproc.h" using namespace OHOS::Security::AccessToken; namespace OHOS { @@ -48,10 +49,16 @@ void DmCredentialManagerTest::SetUp() tokenId = GetAccessTokenId(&infoInstance); SetSelfTokenID(tokenId); OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); + hiChainConnector_ = std::make_shared(); + listener_ = std::make_shared(); + dmCreMgr_ = std::make_shared(hiChainConnector_, listener_); } void DmCredentialManagerTest::TearDown() { + dmCreMgr_ = nullptr; + hiChainConnector_ = nullptr; + listener_ = nullptr; } void DmCredentialManagerTest::SetUpTestCase() @@ -62,10 +69,6 @@ void DmCredentialManagerTest::TearDownTestCase() { } -namespace { -std::shared_ptr listener_ = std::make_shared(); -std::shared_ptr hiChainConnector_ = std::make_shared(); - /** * @tc.name: DmCredentialManager_001 * @tc.desc: Test whether the DmCredentialManager function can generate a new pointer @@ -147,6 +150,42 @@ HWTEST_F(DmCredentialManagerTest, UnRegisterCredentialCallback_002, testing::ext EXPECT_EQ(ret, ERR_DM_FAILED); } +/** + * @tc.name:UnRegisterCredentialCallback_003 + * @tc.desc: return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, UnRegisterCredentialCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + int32_t ret = dmCreMgr_->RegisterCredentialCallback(pkgName); + EXPECT_EQ(ret, DM_OK); + ret = dmCreMgr_->UnRegisterCredentialCallback(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name:RequestCredential_001 + * @tc.desc: get credential info and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, RequestCredential_001, testing::ext::TestSize.Level0) +{ + std::string reqJsonStr = "invalid json string"; + std::string returnJsonStr; + int32_t ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_FAILED); + + nlohmann::json jsonObject; + jsonObject["userId"] = "test"; + jsonObject["version"] = "test"; + reqJsonStr = SafetyDump(jsonObject); + ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_FAILED); +} + /** * @tc.name:RequestCredential_002 * @tc.desc: get credential info and return ERR_DM_FAILED @@ -205,18 +244,18 @@ HWTEST_F(DmCredentialManagerTest, RequestCredential_004, testing::ext::TestSize. } /** - * @tc.name: ImportCredential_002 + * @tc.name: ImportCredential_001 * @tc.desc: import local credential and return ERR_DM_FAILED * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DmCredentialManagerTest, ImportCredential_002, testing::ext::TestSize.Level0) +HWTEST_F(DmCredentialManagerTest, ImportCredential_001, testing::ext::TestSize.Level0) { - std::string pkgName = ""; + std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { "processType" : 1, - "authType" : 1, + "authType" : "test", "userId" : "123", "credentialData" : [ @@ -232,9 +271,45 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_002, testing::ext::TestSize.L ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - dmCreMgr->credentialVec_.push_back(pkgName); - int32_t ret = dmCreMgr->ImportCredential(pkgName, credentialInfo); + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + dmCreMgr_->credentialVec_.push_back(pkgName); + int32_t ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); + jsonObject["TType"] = 1; + jsonObject["processType"] = 1; + credentialInfo = SafetyDump(jsonObject); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject["processType"] = -1; + credentialInfo = SafetyDump(jsonObject); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject["processType"] = 2; + credentialInfo = SafetyDump(jsonObject); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject["TType"] = "test"; + credentialInfo = SafetyDump(jsonObject); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportCredential_002 + * @tc.desc: import local credential and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportCredential_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + std::string credentialInfo; + int32_t ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -269,12 +344,24 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_004, testing::ext::TestSize.L std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { - "userId" , "123" + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 1, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - dmCreMgr->credentialVec_.push_back(pkgName); - int32_t ret = dmCreMgr->ImportCredential(pkgName, credentialInfo); + dmCreMgr_->credentialVec_.push_back(pkgName); + int32_t ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -289,6 +376,7 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_005, testing::ext::TestSize.L std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { + "processType" : 0, "authType" : 1, "userId" : "123", "credentialData" : @@ -312,25 +400,47 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_005, testing::ext::TestSize.L } /** - * @tc.name: ImportCredential_006 - * @tc.desc: import local credential and return ERR_DM_FAILED + * @tc.name: ImportRemoteCredentialExt_001 + * @tc.desc: test ImportRemoteCredentialExt * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DmCredentialManagerTest, ImportCredential_006, testing::ext::TestSize.Level0) +HWTEST_F(DmCredentialManagerTest, ImportRemoteCredentialExt_001, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = ""; + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportRemoteCredentialExt(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportLocalCredential_001 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_001, testing::ext::TestSize.Level0) { - std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { - "processType" : 0, - "authType" : 1, + "processType" : 1, + "authType" : 2, "userId" : "123", "credentialData" : [ { - "credentialType" : 1, + "credentialType" : 0, "credentialId" : "104", - "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "authCode" : "12345", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + }, + { + "credentialType" : 0, + "credentialId" : "105", + "authCode" : "12345", "serverPk" : "", "pkInfoSignature" : "", "pkInfo" : "", @@ -339,9 +449,7 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_006, testing::ext::TestSize.L ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - dmCreMgr->credentialVec_.push_back(pkgName); - int32_t ret = dmCreMgr->ImportCredential(pkgName, credentialInfo); + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -487,6 +595,139 @@ HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_006, testing::ext::TestS EXPECT_EQ(ret, ERR_DM_FAILED); } +/** + * @tc.name: ImportLocalCredential_007 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_007, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 1, + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 0, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] + } + )"; + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportLocalCredential_008 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_008, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 1, + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 2, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] + } + )"; + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportLocalCredential_009 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_009, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 1, + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 2, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] + } + )"; + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportRemoteCredential_001 + * @tc.desc: import remote symmetry credential and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_001, testing::ext::TestSize.Level0) +{ + CredentialDataInfo credentialDataInfo; + credentialDataInfo.credentialType = SAME_ACCOUNT_TYPE; + credentialDataInfo.credentailId = "credential_id"; + credentialDataInfo.serverPk = "server_pk"; + credentialDataInfo.pkInfoSignature = "pk_info_signature"; + credentialDataInfo.pkInfo = "pk_info"; + credentialDataInfo.authCode = "auth_code"; + credentialDataInfo.peerDeviceId = "peer_device_id"; + credentialDataInfo.userId = "user_id"; + credentialDataInfo.credentialType = SAME_ACCOUNT_TYPE; + nlohmann::json jsonObject1 = nlohmann::json(credentialDataInfo); + nlohmann::json credentialJson = nlohmann::json::array(); + credentialJson.push_back(jsonObject1); + nlohmann::json jsonObject; + jsonObject[FIELD_CREDENTIAL_DATA] = credentialJson; + jsonObject[FIELD_AUTH_TYPE] = CROSS_ACCOUNT_TYPE; + jsonObject[FIELD_USER_ID] = 0; + jsonObject[FIELD_PEER_USER_ID] = "peerUserId"; + + std::string credentialInfo = SafetyDump(jsonObject); + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject[FIELD_CREDENTIAL_DATA] = 0; + credentialInfo = SafetyDump(jsonObject); + ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + /** * @tc.name: ImportRemoteCredential_002 * @tc.desc: import remote symmetry credential and return ERR_DM_FAILED @@ -662,8 +903,27 @@ HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_008, testing::ext::Test ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - int32_t ret = dmCreMgr->ImportRemoteCredential(credentialInfo); + int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: DeleteRemoteCredential_001 + * @tc.desc: delete remote credential and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, DeleteRemoteCredential_001, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 2, + "authType" : 2, + "peerUserId": "123", + "peerCredentialInfo" : 0 + } + )"; + int32_t ret = dmCreMgr_->DeleteRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -896,6 +1156,32 @@ HWTEST_F(DmCredentialManagerTest, DeleteRemoteCredential_0011, testing::ext::Tes EXPECT_EQ(ret, ERR_DM_FAILED); } +/** + * @tc.name: DeleteCredential_001 + * @tc.desc: test DeleteCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, DeleteCredential_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + std::string resultInfo; + std::string credentialInfo = R"( + { + "processType" : 2, + "authType" : 2, + "userId" : "123" + } + )"; + dmCreMgr_->requestId_ = 1; + dmCreMgr_->OnGroupResult(0, 0, resultInfo); + dmCreMgr_->requestId_ = 0; + dmCreMgr_->OnGroupResult(0, 0, resultInfo); + dmCreMgr_->credentialVec_.push_back(pkgName); + int32_t ret = dmCreMgr_->DeleteCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + /** * @tc.name: DeleteCredential_002 * @tc.desc: delete local credential and return ERR_DM_FAILED @@ -1343,6 +1629,101 @@ HWTEST_F(DmCredentialManagerTest, GetCredentialData_008, testing::ext::TestSize. int32_t ret = dmCreMgr->GetCredentialData(credentialInfo, credentialData, jsonOutObj); EXPECT_EQ(ret, DM_OK); } -} // namespace + +/** + * @tc.name: from_json_001 + * @tc.desc: test from_json + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, from_json_001, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonOutObj; + CredentialDataInfo credentialDataInfo; + jsonOutObj[FIELD_CREDENTIAL_TYPE] = "test"; + from_json(jsonOutObj, credentialDataInfo); + + jsonOutObj[FIELD_CREDENTIAL_TYPE] = NONSYMMETRY_CREDENTIAL_TYPE; + jsonOutObj[FIELD_SERVER_PK] = 0; + jsonOutObj[FIELD_PKINFO_SIGNATURE] = 0; + jsonOutObj[FIELD_PKINFO] = 0; + jsonOutObj[FIELD_PEER_DEVICE_ID] = 0; + credentialDataInfo.serverPk = ""; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_TRUE(credentialDataInfo.serverPk.empty()); + + nlohmann::json jsonPkInfo; + jsonOutObj[FIELD_SERVER_PK] = "serverPk"; + jsonOutObj[FIELD_PKINFO_SIGNATURE] = "pkInfoSignature"; + jsonOutObj[FIELD_PKINFO] = SafetyDump(jsonPkInfo); + jsonOutObj[FIELD_PEER_DEVICE_ID] = "peerDeviceId"; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_FALSE(credentialDataInfo.serverPk.empty()); + + jsonOutObj[FIELD_CREDENTIAL_TYPE] = SYMMETRY_CREDENTIAL_TYPE; + jsonOutObj[FIELD_AUTH_CODE] = 0; + credentialDataInfo.authCode = ""; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_TRUE(credentialDataInfo.authCode.empty()); + + jsonOutObj[FIELD_AUTH_CODE] = "authCode"; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_FALSE(credentialDataInfo.authCode.empty()); + + jsonOutObj[FIELD_CREDENTIAL_TYPE] = 0; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_FALSE(credentialDataInfo.authCode.empty()); +} + +/** + * @tc.name: from_json_002 + * @tc.desc: test from_json + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, from_json_002, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + PeerCredentialInfo peerCredentialInfo; + jsonObject[FIELD_PEER_USER_ID] = "peerDeviceId"; + from_json(jsonObject, peerCredentialInfo); + EXPECT_EQ(peerCredentialInfo.peerDeviceId, "peerDeviceId"); + + std::string deviceList = "deviceList"; + uint16_t deviceTypeId = 0; + int32_t errcode = 0; + std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); + dmCreMgr->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); +} + +/** + * @tc.name: to_json_001 + * @tc.desc: test to_json + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, to_json_001, testing::ext::TestSize.Level0) +{ + CredentialDataInfo credentialDataInfo; + credentialDataInfo.peerDeviceId = "test"; + credentialDataInfo.userId = "test"; + credentialDataInfo.credentailId = "test"; + credentialDataInfo.credentialType = NONSYMMETRY_CREDENTIAL_TYPE; + credentialDataInfo.serverPk = "test"; + credentialDataInfo.pkInfoSignature = "test"; + credentialDataInfo.pkInfo = "test"; + credentialDataInfo.authCode = "test"; + nlohmann::json jsonObject; + to_json(jsonObject, credentialDataInfo); + EXPECT_EQ(jsonObject[FIELD_SERVER_PK].get(), "test"); + + credentialDataInfo.credentialType = SYMMETRY_CREDENTIAL_TYPE; + to_json(jsonObject, credentialDataInfo); + EXPECT_EQ(jsonObject[FIELD_AUTH_CODE].get(), "test"); + + credentialDataInfo.credentialType = UNKNOWN_CREDENTIAL_TYPE; + to_json(jsonObject, credentialDataInfo); + EXPECT_EQ(jsonObject[FIELD_AUTH_CODE].get(), "test"); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_credential_manager.h b/test/commonunittest/UTTest_dm_credential_manager.h index 9b3db1e42c469c4c9b688aa35d47a9d716e821aa..50ac9b4500495c084c267a55f66e531d9bd7ec94 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.h +++ b/test/commonunittest/UTTest_dm_credential_manager.h @@ -16,6 +16,7 @@ #ifndef OHOS_UTTEST_DM_CREDENTIAL_MANAGER_H #define OHOS_UTTEST_DM_CREDENTIAL_MANAGER_H +#include #include #include "device_auth.h" #include "dm_credential_manager.h" @@ -31,6 +32,17 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + + std::shared_ptr listener_; + std::shared_ptr hiChainConnector_; + std::shared_ptr dmCreMgr_; +}; + +class MockDeviceManagerServiceListener : public DeviceManagerServiceListener { +public: + MockDeviceManagerServiceListener() = default; + ~MockDeviceManagerServiceListener() = default; + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index ecf3f49c2d9f335418db542f108fefce4d645113..5473b3f7ac9155f43dce27bec5f7e35462a12c76 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -16,8 +16,12 @@ #include "UTTest_dm_deviceprofile_connector.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "deviceprofile_connector.h" +#include "dp_inited_callback_stub.h" +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { void DeviceProfileConnectorTest::SetUp() @@ -30,12 +34,500 @@ void DeviceProfileConnectorTest::TearDown() void DeviceProfileConnectorTest::SetUpTestCase() { + multipleUserConnectorMock_ = std::make_shared(); + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; + cryptoMock_ = std::make_shared(); + DmCrypto::dmCrypto = cryptoMock_; } void DeviceProfileConnectorTest::TearDownTestCase() { + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; + multipleUserConnectorMock_ = nullptr; + DmCrypto::dmCrypto = nullptr; + cryptoMock_ = nullptr; } +class MockDpInitedCallback : public DistributedDeviceProfile::DpInitedCallbackStub { +public: + MockDpInitedCallback() {} + ~MockDpInitedCallback() {} + int32_t OnDpInited() + { + return DM_OK; + } +}; + +void AddAccessControlProfileFirst(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileFirst(DistributedDeviceProfile::AccessControlProfile& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + accessControlProfiles.SetAccessControlId(accesserId); + accessControlProfiles.SetAccesserId(accesserId); + accessControlProfiles.SetAccesseeId(accesserId); + accessControlProfiles.SetTrustDeviceId(trustDeviceId); + accessControlProfiles.SetBindType(bindType); + accessControlProfiles.SetAuthenticationType(authenticationType); + accessControlProfiles.SetDeviceIdType(deviceIdType); + accessControlProfiles.SetStatus(status); + accessControlProfiles.SetBindLevel(bindLevel); + accessControlProfiles.SetAccesser(accesser); + accessControlProfiles.SetAccessee(accessee); +} + +void AddAccessControlProfileSecond(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileThird(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileForth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileFifth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileSix(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileSeven(DistributedDeviceProfile::AccessControlProfile& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + accessControlProfiles.SetAccessControlId(accesserId); + accessControlProfiles.SetAccesserId(accesserId); + accessControlProfiles.SetAccesseeId(accesserId); + accessControlProfiles.SetTrustDeviceId(trustDeviceId); + accessControlProfiles.SetBindType(bindType); + accessControlProfiles.SetAuthenticationType(authenticationType); + accessControlProfiles.SetDeviceIdType(deviceIdType); + accessControlProfiles.SetStatus(status); + accessControlProfiles.SetBindLevel(bindLevel); + accessControlProfiles.SetAccesser(accesser); + accessControlProfiles.SetAccessee(accessee); +} + +void AddAccessControlProfileEight(DistributedDeviceProfile::AccessControlProfile& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(0); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + accessControlProfiles.SetAccessControlId(accesserId); + accessControlProfiles.SetAccesserId(accesserId); + accessControlProfiles.SetAccesseeId(accesserId); + accessControlProfiles.SetTrustDeviceId(trustDeviceId); + accessControlProfiles.SetBindType(bindType); + accessControlProfiles.SetAuthenticationType(authenticationType); + accessControlProfiles.SetDeviceIdType(deviceIdType); + accessControlProfiles.SetStatus(status); + accessControlProfiles.SetBindLevel(bindLevel); + accessControlProfiles.SetAccesser(accesser); + accessControlProfiles.SetAccessee(accessee); +} + +void GetAccessControlProfiles(std::vector& accessControlProfiles) +{ + AddAccessControlProfileFirst(accessControlProfiles); + AddAccessControlProfileSecond(accessControlProfiles); + AddAccessControlProfileThird(accessControlProfiles); + AddAccessControlProfileForth(accessControlProfiles); + AddAccessControlProfileFifth(accessControlProfiles); +} HWTEST_F(DeviceProfileConnectorTest, GetAccessControlProfile_001, testing::ext::TestSize.Level0) { auto ret = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); @@ -58,11 +550,20 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::Te EXPECT_EQ(ret.empty(), true); } +HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "deviceId_003"; + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + EXPECT_EQ(ret.empty(), true); +} + HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) { DmDiscoveryInfo discoveryInfo; bool isonline = true; int32_t authForm = 0; + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30)).WillOnce(Return(DM_OK)); int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); } @@ -175,7 +676,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckBindType_002, testing::ext::TestSize.L std::string trustDeviceId = "deviceId"; std::string requestDeviceId = "requestDeviceId"; uint32_t ret = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); + EXPECT_NE(ret, IDENTICAL_ACCOUNT_TYPE); } HWTEST_F(DeviceProfileConnectorTest, CheckBindType_003, testing::ext::TestSize.Level0) @@ -183,7 +684,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckBindType_003, testing::ext::TestSize.L std::string trustDeviceId = "deviceId"; std::string requestDeviceId = "deviceId"; uint32_t ret = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); + EXPECT_NE(ret, IDENTICAL_ACCOUNT_TYPE); } HWTEST_F(DeviceProfileConnectorTest, GetBindTypeByPkgName_001, testing::ext::TestSize.Level0) @@ -195,6 +696,15 @@ HWTEST_F(DeviceProfileConnectorTest, GetBindTypeByPkgName_001, testing::ext::Tes EXPECT_EQ(ret.empty(), true); } +HWTEST_F(DeviceProfileConnectorTest, GetBindTypeByPkgName_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string requestDeviceId; + std::string trustUdid = "123456"; + auto ret = DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); + EXPECT_EQ(ret.empty(), false); +} + HWTEST_F(DeviceProfileConnectorTest, GetParamBindTypeVec_001, testing::ext::TestSize.Level0) { DistributedDeviceProfile::AccessControlProfile profiles; @@ -451,52 +961,67 @@ HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_001, testing::ext::TestSi EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_002, testing::ext::TestSize.Level0) { - std::string localDeviceId = "localDeviceId"; - std::string targetDeviceId = "targetDeviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); - EXPECT_EQ(ret.empty(), true); + std::string pkgName; + std::vector bindTypeVec; + std::string localDeviceId; + std::string targetDeviceId = "123456"; + bindTypeVec.push_back(IDENTICAL_ACCOUNT_TYPE); + bindTypeVec.push_back(DEVICE_PEER_TO_PEER_TYPE); + auto ret = DeviceProfileConnector::GetInstance().SyncAclByBindType(pkgName, bindTypeVec, localDeviceId, + targetDeviceId); + EXPECT_EQ(ret.empty(), false); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_003, testing::ext::TestSize.Level0) { - std::string localDeviceId = "123456"; - std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); - EXPECT_EQ(ret.empty(), true); + std::string pkgName = "bundleName"; + std::vector bindTypeVec; + std::string localDeviceId = "deviceId"; + std::string targetDeviceId = "remoteDeviceId"; + bindTypeVec.push_back(DEVICE_ACROSS_ACCOUNT_TYPE); + bindTypeVec.push_back(APP_ACROSS_ACCOUNT_TYPE); + auto ret = DeviceProfileConnector::GetInstance().SyncAclByBindType(pkgName, bindTypeVec, localDeviceId, + targetDeviceId); + EXPECT_EQ(ret.empty(), false); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_004, testing::ext::TestSize.Level0) { + std::string pkgName = "bundleName"; + std::vector bindTypeVec; std::string localDeviceId = "deviceId"; - std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); - EXPECT_EQ(ret.empty(), false); + std::string targetDeviceId = "remoteDeviceId"; + bindTypeVec.push_back(DEVICE_PEER_TO_PEER_TYPE); + bindTypeVec.push_back(IDENTICAL_ACCOUNT_TYPE); + auto ret = DeviceProfileConnector::GetInstance().SyncAclByBindType(pkgName, bindTypeVec, localDeviceId, + targetDeviceId); + EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_001, testing::ext::TestSize.Level0) { - std::string trustDeviceId = "trustDeviceId"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); + std::string localDeviceId = "localDeviceId"; + std::string targetDeviceId = "targetDeviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); + EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_002, testing::ext::TestSize.Level0) { - std::string trustDeviceId = "123456"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); + std::string localDeviceId = "123456"; + std::string targetDeviceId = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); + EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_003, testing::ext::TestSize.Level0) { - std::string trustDeviceId = "deviceId"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, IDENTICAL_ACCOUNT_TYPE); + std::string localDeviceId = "deviceId"; + std::string targetDeviceId = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); + EXPECT_EQ(ret.empty(), true); } HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::TestSize.Level0) @@ -504,54 +1029,13 @@ HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::Tes DmAclInfo aclInfo; DmAccesser dmAccesser; DmAccessee dmAccessee; + int32_t userId = 123456; + std::string localDeviceId = "deviceId"; + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localDeviceId, userId); int32_t ret = DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - std::string accountId; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string localDeviceId; - std::string remoteDeviceId; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "localDeviceId"; - std::string remoteDeviceId = "remoteDeviceId"; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "123456"; - std::string remoteDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "deviceId"; - std::string remoteDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - HWTEST_F(DeviceProfileConnectorTest, UpdateAccessControlList_001, testing::ext::TestSize.Level0) { int32_t userId = 0; @@ -596,83 +1080,59 @@ HWTEST_F(DeviceProfileConnectorTest, CheckIdenticalAccount_001, testing::ext::Te EXPECT_EQ(ret, true); } -HWTEST_F(DeviceProfileConnectorTest, DeleteP2PAccessControlList_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - std::string accountId; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteP2PAccessControlList_002, testing::ext::TestSize.Level0) -{ - int32_t userId = 123456; - std::string accountId = "newAccountId"; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteP2PAccessControlList_003, testing::ext::TestSize.Level0) -{ - int32_t userId = 123456; - std::string accountId = "accountId"; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceProfileConnectorTest, CheckSrcDeviceIdInAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_001, testing::ext::TestSize.Level0) { std::string pkgName; std::string deviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSrcDeviceIdInAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_002, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "123456"; - bool ret = DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSrcDeviceIdInAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_003, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSinkDeviceIdInAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_001, testing::ext::TestSize.Level0) { std::string pkgName; std::string deviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSinkDeviceIdInAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_002, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "123456"; - bool ret = DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSinkDeviceIdInAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_003, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckDeviceIdInAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckDevIdInAclForDevBind_001, testing::ext::TestSize.Level0) { std::string pkgName; std::string deviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } @@ -690,54 +1150,783 @@ HWTEST_F(DeviceProfileConnectorTest, GetTrustNumber_001, testing::ext::TestSize. EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_001, testing::ext::TestSize.Level0) { - std::string pkgName; - std::string localDeviceId; - std::string remoteDeviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, false); + std::string udid = "udid"; + int32_t ret = DeviceProfileConnector::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_002, testing::ext::TestSize.Level0) +{ + std::string udid = "deviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAuthForm_001, testing::ext::TestSize.Level0) +{ + DistributedDeviceProfile::AccessControlProfile profile; + std::string trustDev = ""; + std::string reqDev = ""; + int32_t ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, INVALIED_TYPE); + profile.SetBindType(DM_IDENTICAL_ACCOUNT); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); + profile.SetBindType(DM_POINT_TO_POINT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, DEVICE_PEER_TO_PEER_TYPE); + profile.SetBindType(DM_ACROSS_ACCOUNT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, DEVICE_ACROSS_ACCOUNT_TYPE); + profile.SetBindLevel(APP); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, APP_ACROSS_ACCOUNT_TYPE); + profile.SetBindType(INVALIED_TYPE); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, INVALIED_TYPE); } -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_001, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string localDeviceId = "localDeviceId"; std::string remoteDeviceId = "remoteDeviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, false); + int32_t bindLevel = INVALIED_TYPE; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, INVALIED_TYPE); } -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_002, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; - std::string localDeviceId = "deviceId"; + std::string localDeviceId = "localDeviceId"; std::string remoteDeviceId = "remoteDeviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, false); + int32_t bindLevel = APP; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, APP); } -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_004, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_003, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; - std::string localDeviceId = "deviceId"; - std::string remoteDeviceId = "deviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); + std::string localDeviceId = "localDeviceId"; + std::string remoteDeviceId = "remoteDeviceId"; + int32_t bindLevel = SERVICE; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, SERVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string localDeviceId = "localDeviceId"; + std::string remoteDeviceId = "remoteDeviceId"; + int32_t bindLevel = DEVICE; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, GetBindLevel_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string localUdid = "localDeviceId"; + std::string udid = "remoteDeviceId"; + uint64_t tokenId = 0; + int32_t bindLevel = INVALIED_TYPE; + + bindLevel = DeviceProfileConnector::GetInstance() + .GetBindLevel(pkgName, localUdid, udid, tokenId); + + EXPECT_EQ(bindLevel, DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_001, testing::ext::TestSize.Level0) +{ + std::string udid = "deviceId"; + int32_t bindType = DEVICE; + std::map deviceMap; + deviceMap[udid] = APP; + DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); + EXPECT_EQ(deviceMap[udid], DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_002, testing::ext::TestSize.Level0) +{ + std::string udid = "deviceId"; + int32_t bindType = DEVICE; + std::map deviceMap; + DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); + EXPECT_EQ(deviceMap[udid], DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_001, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + int32_t bindType = DM_INVALIED_BINDTYPE; + std::string remoteAccountHash = "remoteAccountHash"; + std::string remoteUdid = "1"; + std::string localUdid = "localDeviceId"; + + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_001, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + std::string remoteUdid = "remoteDeviceId"; + std::string localUdid = "localDeviceId"; + int32_t bindType = DM_INVALIED_BINDTYPE; + + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + EXPECT_EQ(bindType, SERVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + int32_t tokenId = 0; + std::string remoteUdid = "remoteDeviceId"; + std::string localUdid = "localDeviceId"; + std::string pkgName = ""; + ProcessInfo res; + + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ(pkgName, res.pkgName); +} + +HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSize.Level0) +{ + DistributedDeviceProfile::AccessControlProfile profile; + DmAccessCaller caller; + DmAccessCallee callee; + int32_t ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, false); + profile.SetBindType(DM_IDENTICAL_ACCOUNT); + profile.accessee_.SetAccesseeBundleName("pkgName"); + profile.accessee_.SetAccesseeDeviceId("localDeviceId"); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindType(DM_POINT_TO_POINT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); + profile.SetBindLevel(APP); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindLevel(SERVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindType(DM_ACROSS_ACCOUNT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindLevel(APP); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindLevel(SERVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindType(INVALIED_TYPE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetAccessControlProfileByUserId_001, testing::ext::TestSize.Level0) { - std::string udid = "udid"; + int32_t userId = DEVICE; + std::vector profiles; + profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); + EXPECT_GE(profiles.size(), 0); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAppBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::string pkgName = "bundleName1"; + std::vector profiles; + std::string localUdid = "remoteDeviceId"; + std::string remoteUdid="localDeviceId"; + GetAccessControlProfiles(profiles); + DeviceProfileConnector::GetInstance().DeleteAppBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, APP); + + pkgName = "bundleName2"; + localUdid = "localDeviceId"; + remoteUdid="remoteDeviceId"; + DeviceProfileConnector::GetInstance().DeleteAppBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, APP); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteDeviceBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::vector profiles; + std::string localUdid = "remoteDeviceId"; + std::string remoteUdid="localDeviceId"; + GetAccessControlProfiles(profiles); + DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, DEVICE); + + localUdid = "localDeviceId"; + remoteUdid="remoteDeviceId"; + DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteServiceBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::string pkgName = "bundleName1"; + std::vector profiles; + std::string localUdid = "remoteDeviceId"; + std::string remoteUdid="localDeviceId"; + GetAccessControlProfiles(profiles); + DeviceProfileConnector::GetInstance().DeleteServiceBindLevel(offlineParam, pkgName, profiles, + localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, SERVICE); + + pkgName = "bundleName2"; + localUdid = "localDeviceId"; + remoteUdid="remoteDeviceId"; + DeviceProfileConnector::GetInstance().DeleteServiceBindLevel(offlineParam, pkgName, profiles, + localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, SERVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "remoteDeviceId"; + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteTimeOutAcl_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "remoteDeviceId"; + uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DeviceProfileConnectorTest, GetTrustNumber_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "remoteDeviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().GetTrustNumber(deviceId); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_003, testing::ext::TestSize.Level0) +{ + std::string udid = "123456"; int32_t ret = DeviceProfileConnector::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + std::string srcUdid; + DmAccessCallee callee; + std::string sinkUdid; + int32_t ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, ERR_DM_FAILED); + + srcUdid = "123456"; + sinkUdid = "123456"; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_NE(ret, DM_OK); } -HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) { - std::string udid = "deviceId"; - int32_t ret = DeviceProfileConnector::GetInstance().IsSameAccount(udid); + DmAccessCaller caller; + std::string srcUdid; + DmAccessCallee callee; + std::string sinkUdid; + int32_t ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, ERR_DM_FAILED); + + srcUdid = "123456"; + sinkUdid = "123456"; + ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_002, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + int32_t bindType = DM_INVALIED_BINDTYPE; + std::string remoteAccountHash = "remoteAccountHash"; + std::string remoteUdid = "123456"; + std::string localUdid = "localDeviceId"; + + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_NE(bindType, DM_IDENTICAL_ACCOUNT); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); + + int32_t remoteId = 456; + remoteUserId = remoteId; + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + std::string remoteUdid; + std::string localUdid = "localDeviceId"; + int32_t bindType = DM_INVALIED_BINDTYPE; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); + + remoteUdid = "123456"; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAllAccessControlProfile_001, testing::ext::TestSize.Level0) +{ + int64_t accessControlId = 1; + DeviceProfileConnector::GetInstance().DeleteAccessControlById(accessControlId); + auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAclProfileByDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId"; + int32_t userId = 123456; + auto ret = DeviceProfileConnector::GetInstance().GetAclProfileByDeviceIdAndUserId(deviceId, userId + ); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAclForAccountLogOut_001, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t localUserId = 444; + std::string peerUdid = "deviceId"; + int32_t peerUserId = 555; + bool ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); + EXPECT_FALSE(ret); + + localUdid = "deviceId"; + localUserId = 123456; + peerUdid = "deviceId"; + peerUserId = 456; + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + EXPECT_FALSE(ret); + + localUdid = "deviceId"; + localUserId = 123456; + peerUdid = "deviceId"; + peerUserId = 123456; + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + EXPECT_TRUE(ret); + + localUdid = "localDeviceId"; + localUserId = 123456; + peerUdid = "remoteDeviceId"; + peerUserId = 123456; + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_005, testing::ext::TestSize.Level0) +{ + std::string localDeviceId = "deviceId"; + std::string targetDeviceId = "deviceId"; + int32_t userId = 123456; + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, + targetDeviceId, userId); + EXPECT_FALSE(ret.empty()); + + localDeviceId = "remoteDeviceId"; + targetDeviceId = "localDeviceId"; + userId = 456; + ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, + targetDeviceId, userId); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::vector userIds; + int32_t userId = 123456; + int32_t localId = 456; + userIds.push_back(userId); + userIds.push_back(localId); + std::string localUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); + EXPECT_FALSE(ret.empty()); + + localUdid = "localDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 123456; + std::string accountId; + std::string localUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); + EXPECT_FALSE(ret.empty()); + + localUdid = "localDeviceId"; + userId = 456; + ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestSize.Level0) +{ + int32_t currentUserId = 0; + std::string localUdid = "deviceId"; + int32_t beforeUserId = 123456; + int32_t ret = DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); + EXPECT_EQ(ret, DM_OK); + + beforeUserId = 1234; + currentUserId = 123456; + ret = DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); + EXPECT_EQ(ret, DM_OK); + + std::vector remoteUserIds; + remoteUserIds.push_back(currentUserId); + std::string remoteUdid = "deviceId"; + std::vector localUserIds; + localUserIds.push_back(currentUserId); + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid, + localUserIds, localUdid); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + int32_t localdeviceId = 456; + remoteUserIds.push_back(localdeviceId); + localUserIds.push_back(localdeviceId); + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid, + localUserIds, localUdid); +} + +HWTEST_F(DeviceProfileConnectorTest, GetOfflineProcessInfo_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + std::vector localUserIds; + std::string remoteUdid = "deviceId"; + std::vector remoteUserIds; + int32_t userId = 123456; + remoteUserIds.push_back(userId); + localUserIds.push_back(userId); + auto ret = DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, + remoteUserIds); + EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + int32_t localdeviceId = 456; + remoteUserIds.push_back(localdeviceId); + localUserIds.push_back(localdeviceId); + ret = DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, + remoteUserIds); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetUserIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + std::string peerUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(localUdid, peerUdid); + EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + peerUdid = "localDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(localUdid, peerUdid); + EXPECT_FALSE(ret.empty()); + + int32_t userId = 123456; + std::vector localUserIds; + localUserIds.push_back(userId); + std::string remoteUdid = "deviceId"; + std::vector remoteFrontUserIds; + remoteFrontUserIds.push_back(userId); + std::vector remoteBackUserIds; + remoteBackUserIds.push_back(userId); + DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, remoteFrontUserIds, + remoteBackUserIds); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + userId = 456; + std::vector remoteUserIds; + remoteUserIds.push_back(userId); + localUserIds.push_back(userId); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, + localUdid); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + int32_t localUserId = 123456; + auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); + EXPECT_FALSE(ret.empty()); + + localUdid = "localDeviceId"; + localUserId = 456; + ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); + EXPECT_FALSE(ret.empty()); + + std::vector remoteUserIds; + remoteUserIds.push_back(localUserId); + std::string remoteUdid = "deviceId"; + std::vector localUserIds; + localUserIds.push_back(localUserId); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, + localUdid); + + ProcessInfo process; + process.userId = 1; + process.pkgName = "pkgName"; + ProcessInfo process1; + process1.userId = 1; + process1.pkgName = "pkgName"; + EXPECT_TRUE(process == process1); + + process.userId = 0; + EXPECT_TRUE(process < process1); + + DmNotifyKey dmNotifyKey; + dmNotifyKey.processUserId = 1; + dmNotifyKey.processPkgName = "proName"; + dmNotifyKey.notifyUserId = 0; + dmNotifyKey.udid = "udid"; + + DmNotifyKey dmNotifyKey1; + dmNotifyKey1.processUserId = 1; + dmNotifyKey1.processPkgName = "proName"; + dmNotifyKey1.notifyUserId = 0; + dmNotifyKey1.udid = "udid"; + EXPECT_TRUE(dmNotifyKey == dmNotifyKey1); + + dmNotifyKey1.processUserId = 2; + EXPECT_TRUE(dmNotifyKey < dmNotifyKey1); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "deviceId"; + + EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + EXPECT_EQ(ret.empty(), false); + + deviceId = "deviceIder001"; + EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); + ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + EXPECT_EQ(ret.empty(), true); + + std::string udid; + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); + + udid = "deviceId"; + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + std::string peerUdid = "deviceId"; + int32_t peerUserId = 123456; + std::string peerAccountHash = ""; + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_TRUE(ret.empty()); + + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_TRUE(ret.empty()); + + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).Times(::testing::AtLeast(40)).WillOnce(Return(DM_OK)); + ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + peerUdid = "localDeviceId"; + peerUserId = 456; + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).Times(::testing::AtLeast(40)).WillOnce(Return(DM_OK)); + ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_002, testing::ext::TestSize.Level0) +{ + DmDiscoveryInfo discoveryInfo; + discoveryInfo.remoteDeviceIdHash = ""; + discoveryInfo.localDeviceId = "deviceId"; + discoveryInfo.userId = 123456; + discoveryInfo.pkgname = ""; + bool isonline = true; + int32_t authForm = 0; + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); + EXPECT_EQ(ret, DM_OK); + + discoveryInfo.pkgname = "bundleName"; + discoveryInfo.localDeviceId = "deviceId"; + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30)).WillOnce(Return(DM_OK)); + ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "123456"; + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); + EXPECT_EQ(ret, false); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "123456"; + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); + EXPECT_FALSE(ret); + + DistributedDeviceProfile::AccessControlProfile profiles; + std::string remoteUdid = "remoteDeviceId"; + std::vector remoteFrontUserIds; + std::vector remoteBackUserIds; + AddAccessControlProfileFirst(profiles); + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profiles, remoteUdid, + remoteFrontUserIds, remoteBackUserIds); + + remoteUdid = "localDeviceId"; + AddAccessControlProfileSeven(profiles); + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profiles, remoteUdid, + remoteFrontUserIds, remoteBackUserIds); + + AddAccessControlProfileEight(profiles); + std::string localUdid = "localDeviceId"; + std::vector localUserIds; + int32_t userId = 123456; + localUserIds.push_back(userId); + remoteUdid = "remoteDeviceId"; + remoteFrontUserIds.push_back(0); + remoteFrontUserIds.push_back(userId); + DeviceProfileConnector::GetInstance().UpdatePeerUserId(profiles, localUdid, localUserIds, remoteUdid, + remoteFrontUserIds); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_002, testing::ext::TestSize.Level0) +{ + int32_t userId = 123456; + DmAccessCaller caller; + caller.userId = userId; + std::string srcUdid = "deviceId"; + DmAccessCallee callee; + callee.userId = userId; + std::string sinkUdid = "deviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); + + srcUdid = "remoteDeviceId"; + sinkUdid = "localDeviceId"; + caller.userId = 456; + callee.userId = 456; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); + + callee.userId = 0; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_002, testing::ext::TestSize.Level0) +{ + int32_t userId = 456; + DmAccessCaller caller; + caller.userId = userId; + std::string srcUdid = "localDeviceId"; + DmAccessCallee callee; + callee.userId = userId; + std::string sinkUdid = "remoteDeviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); + + callee.userId = 0; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_002, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 456; + int32_t tokenId = 1001; + std::string remoteUdid = "localDeviceId"; + std::string localUdid = "remoteDeviceId"; + std::string pkgName = ""; + ProcessInfo res; + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ("bundleName", res.pkgName); + + tokenId = 1002; + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ("bundleName", res.pkgName); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAclProfileByUserId_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + int32_t userId = 123456; + std::string remoteUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetAclProfileByUserId(localUdid, userId, remoteUdid); + EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + userId = 456; + ret = DeviceProfileConnector::GetInstance().GetAclProfileByUserId(localUdid, userId, remoteUdid); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, PutAllTrustedDevices_001, testing::ext::TestSize.Level0) +{ + std::vector deviceInfos; + int32_t ret = DeviceProfileConnector::GetInstance().PutAllTrustedDevices(deviceInfos); + EXPECT_NE(ret, DM_OK); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.h b/test/commonunittest/UTTest_dm_deviceprofile_connector.h index 22fa7543c68170aec43da03f8086fa6e23e9dc72..9ef4fffa53443fffe1c007d7eec65987e5860a3e 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.h +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.h @@ -20,6 +20,8 @@ #include #include "deviceprofile_connector.h" +#include "multiple_user_connector_mock.h" +#include "dm_crypto_mock.h" namespace OHOS { namespace DistributedHardware { @@ -29,6 +31,8 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + static inline std::shared_ptr multipleUserConnectorMock_ = nullptr; + static inline std::shared_ptr cryptoMock_ = nullptr; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a49629d07d3aa21546412043f673786e1a8aa9ad --- /dev/null +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -0,0 +1,407 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_deviceprofile_connector_second.h" + +#include "dm_constants.h" +#include "deviceprofile_connector.h" +#include + +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void DeviceProfileConnectorSecondTest::SetUp() +{ +} + +void DeviceProfileConnectorSecondTest::TearDown() +{ +} + +void DeviceProfileConnectorSecondTest::SetUpTestCase() +{ + DistributedDeviceProfile::DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient = + distributedDeviceProfileClientMock_; +} + +void DeviceProfileConnectorSecondTest::TearDownTestCase() +{ + DistributedDeviceProfile::DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient = nullptr; + distributedDeviceProfileClientMock_ = nullptr; +} + +void AddAccessControlProfile(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfile_201, testing::ext::TestSize.Level0) +{ + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + EXPECT_TRUE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfileByUserId_201, testing::ext::TestSize.Level0) +{ + int32_t userId = DEVICE; + std::vector profiles; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); + EXPECT_TRUE(profiles.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, CheckAuthForm_201, testing::ext::TestSize.Level0) +{ + DmAuthForm form = DmAuthForm::ACROSS_ACCOUNT; + DistributedDeviceProfile::AccessControlProfile profiles; + profiles.SetBindType(DM_ACROSS_ACCOUNT); + profiles.SetBindLevel(APP); + profiles.accessee_.SetAccesseeBundleName("pkgName"); + profiles.accessee_.SetAccesseeDeviceId("localDeviceId"); + DmDiscoveryInfo discoveryInfo; + discoveryInfo.pkgname = "pkgName"; + discoveryInfo.localDeviceId = "localDeviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); + + profiles.accesser_.SetAccesserBundleName("pkgName"); + profiles.accesser_.SetAccesserDeviceId("localDeviceId"); + ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); + + profiles.SetBindLevel(SERVICE); + ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::INVALID_TYPE); + + profiles.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, PutAccessControlList_201, testing::ext::TestSize.Level0) +{ + DmAclInfo aclInfo; + DmAccesser dmAccesser; + DmAccessee dmAccessee; + EXPECT_CALL(*distributedDeviceProfileClientMock_, PutAccessControlProfile(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, CheckIdenticalAccount_201, testing::ext::TestSize.Level0) +{ + int32_t userId = 0; + std::string accountId; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + bool ret = DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); + EXPECT_FALSE(ret); + + userId = 1; + int32_t bindType = 1; + std::string deviceIdEr = "deviceId"; + std::string deviceIdEe = "deviceIdEe"; + uint32_t accesserId = 1; + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + DistributedDeviceProfile::AccessControlProfile profile; + profile.SetAccessControlId(accesserId); + profile.SetBindType(bindType); + profile.SetAccesser(accesser); + profile.SetAccessee(accessee); + + int userIds = 12356; + std::string remoteUdid = "deviceId"; + std::vector remoteFrontUserIds; + remoteFrontUserIds.push_back(userIds); + std::vector remoteBackUserIds; + remoteBackUserIds.push_back(userIds); + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profile, remoteUdid, remoteFrontUserIds, remoteBackUserIds); + + remoteUdid = "deviceIdEe"; + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profile, remoteUdid, remoteFrontUserIds, remoteBackUserIds); + + int32_t userIdee = 0; + accessee.SetAccesseeUserId(userIdee); + DistributedDeviceProfile::AccessControlProfile profilesecond; + profilesecond.SetAccessControlId(accesserId); + profilesecond.SetBindType(bindType); + profilesecond.SetAccesser(accesser); + profilesecond.SetAccessee(accessee); + std::string localUdid = "deviceId"; + std::vector localUserIds; + int32_t localUserId = 1; + localUserIds.push_back(localUserId); + DeviceProfileConnector::GetInstance().UpdatePeerUserId(profilesecond, localUdid, localUserIds, + remoteUdid, remoteFrontUserIds); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAllAccessControlProfile_201, testing::ext::TestSize.Level0) +{ + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + EXPECT_TRUE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByDeviceIdAndUserId_201, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId"; + int32_t userId = 123456; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetAclProfileByDeviceIdAndUserId(deviceId, userId); + EXPECT_TRUE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, DeleteAclForAccountLogOut_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_device_id"; + int32_t localUserId = 1; + std::string peerUdid = "peer_device_id"; + int32_t peerUserId = 2; + int32_t result = connector.DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + + EXPECT_EQ(result, false); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, DeleteAppBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::string pkgName = "com.example.app"; + std::vector profiles = {}; + std::string localUdid = "local_udid"; + std::string remoteUdid = "remote_udid"; + connector.DeleteAppBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + + EXPECT_EQ(offlineParam.processVec.size(), 0); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + caller.pkgName = "test_pkg"; + std::string srcUdid = "src_udid"; + DmAccessCallee callee; + std::string sinkUdid = "non_identical_udid"; + + EXPECT_EQ(connector.CheckIsSameAccount(caller, srcUdid, callee, sinkUdid), ERR_DM_FAILED); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDeviceIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::vector userIds = {4, 5, 6}; + std::string localUdid = "local_udid"; + auto result = connector.GetDeviceIdAndBindLevel(userIds, localUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByUserId_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "localDevice"; + int32_t userId = -1; + std::string remoteUdid = "remoteDevice"; + auto result = connector.GetAclProfileByUserId(localUdid, userId, remoteUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByUserId_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "localDevice"; + int32_t userId = 1; + std::string remoteUdid = "nonExistentDevice"; + auto result = connector.GetAclProfileByUserId(localUdid, userId, remoteUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByUserId_003, testing::ext::TestSize.Level0) +{ + std::string localUdid = ""; + int32_t userId = 0; + std::string remoteUdid = ""; + auto result = connector.GetAclProfileByUserId(localUdid, userId, remoteUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetOfflineProcessInfo_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "invalid_device"; + std::vector localUserIds = {1, 2}; + std::string remoteUdid = "remote_device"; + std::vector remoteUserIds = {3, 4}; + std::vector result = + connector.GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, remoteUserIds); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetOfflineProcessInfo_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_device"; + std::vector localUserIds = {1, 2}; + std::string remoteUdid = "remote_device"; + std::vector remoteUserIds = {99, 100}; + std::vector result = + connector.GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, remoteUserIds); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetOfflineProcessInfo_003, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_device"; + std::vector localUserIds = {}; + std::string remoteUdid = "remote_device"; + std::vector remoteUserIds = {3, 4}; + std::vector result = + connector.GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, remoteUserIds); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetUserIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid"; + std::string peerUdid = "peer_udid"; + std::map result = connector.GetUserIdAndBindLevel(localUdid, peerUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetUserIdAndBindLevel_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid"; + std::string peerUdid = "peer_udid"; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(DM_OK)); + std::map result = connector.GetUserIdAndBindLevel(localUdid, peerUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid_123"; + std::string peerUdid = "peer_udid_456"; + int32_t peerUserId = 789; + std::string peerAccountHash = "invalid_hash"; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid_123"; + std::string peerUdid = "non_matching_udid"; + int32_t peerUserId = 789; + std::string peerAccountHash = "valid_hash"; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_003, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid_123"; + std::string peerUdid = "peer_udid_456"; + int32_t peerUserId = -1; + std::string peerAccountHash = "valid_hash"; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_004, testing::ext::TestSize.Level0) +{ + std::string localUdid = ""; + std::string peerUdid = ""; + int32_t peerUserId = 0; + std::string peerAccountHash = ""; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + auto result = connector.GetDeviceIdAndUserId("device4", 4); + EXPECT_EQ(result.size(), 0); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDeviceIdAndUserId_002, testing::ext::TestSize.Level0) +{ + auto result = connector.GetDeviceIdAndUserId("", 0); + EXPECT_EQ(result.size(), 0); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/common/include/ipc/model/ipc_start_discover_req.h b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h similarity index 35% rename from common/include/ipc/model/ipc_start_discover_req.h rename to test/commonunittest/UTTest_dm_deviceprofile_connector_second.h index 863951ceae69342d6ddeef4f999c3f407753eeeb..e7539e32128004aaf566b881aa57db5f5b9b8ffa 100644 --- a/common/include/ipc/model/ipc_start_discover_req.h +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h @@ -13,61 +13,31 @@ * limitations under the License. */ -#ifndef OHOS_DM_IPC_START_DISCOVER_REQ_H -#define OHOS_DM_IPC_START_DISCOVER_REQ_H +#ifndef OHOS_UTTEST_DM_DEVICEPROFILE_CONNECTOR_SECOND_H +#define OHOS_UTTEST_DM_DEVICEPROFILE_CONNECTOR_SECOND_H -#include "ipc_req.h" +#include +#include + +#include "access_control_profile.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_client_mock.h" +#include "deviceprofile_connector_mock.h" namespace OHOS { namespace DistributedHardware { -class IpcStartDevDiscoveryByIdReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStartDevDiscoveryByIdReq); - +class DeviceProfileConnectorSecondTest : public testing::Test { public: - /** - * @tc.name: IpcStartDiscoveryReq::GetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Get SubscribeInfo - * @tc.type: FUNC - */ - const uint16_t &GetSubscribeId() const - { - return subscribeId_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Set SubscribeInfo - * @tc.type: FUNC - */ - void SetSubscribeId(const uint16_t &subscribeId) - { - subscribeId_ = subscribeId; - } - - /** - * @tc.name: IpcStartDiscoveryReq::GetExtra - * @tc.desc: Ipc Start Discovery Request Get Extra - * @tc.type: FUNC - */ - const std::string &GetFilterOption() const - { - return filterOptions_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetExtra - * @tc.desc: Ipc Start Discovery Request Set Extra - * @tc.type: FUNC - */ - void SetFilterOption(const std::string &filterOptions) - { - filterOptions_ = filterOptions; - } - -private: - std::string filterOptions_; - uint16_t subscribeId_ { 0 }; + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + DeviceProfileConnector connector; + + static inline std::shared_ptr + distributedDeviceProfileClientMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IPC_START_DISCOVER_REQ_H +#endif // OHOS_UTTEST_DM_DEVICEPROFILE_CONNECTOR_SECOND_H diff --git a/test/commonunittest/UTTest_dm_discovery_filter.cpp b/test/commonunittest/UTTest_dm_discovery_filter.cpp index 42e305d8f2bd7c7de1b4282163196e245afc4d74..07e3f591cf17b475d687a69c5ba34c6bdf21a517 100644 --- a/test/commonunittest/UTTest_dm_discovery_filter.cpp +++ b/test/commonunittest/UTTest_dm_discovery_filter.cpp @@ -58,7 +58,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Leve { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -74,7 +74,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Leve DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -91,7 +91,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Leve nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -108,7 +108,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Leve nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -126,7 +126,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -144,7 +144,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -165,7 +165,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -187,7 +187,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -209,7 +209,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Lev myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -238,7 +238,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSiz { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -254,7 +254,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSiz DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -271,7 +271,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSiz nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -289,7 +289,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSiz jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -308,7 +308,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -327,7 +327,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_dm_discovery_manager.cpp b/test/commonunittest/UTTest_dm_discovery_manager.cpp index 0f52e28edf968d24809d219b38605b1515f5b198..0026854a03141d8532c6394767cf6f257722909a 100644 --- a/test/commonunittest/UTTest_dm_discovery_manager.cpp +++ b/test/commonunittest/UTTest_dm_discovery_manager.cpp @@ -53,6 +53,12 @@ std::shared_ptr hiChainConnector_ = std::make_shared discoveryMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || + ret == SOFTBUS_IPC_ERR; +} + /** * @tc.name: DmDiscoveryManager_001 * @tc.desc: Test whether the DmDiscoveryManager function can generate a new pointer @@ -135,7 +141,7 @@ HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_003, testing::ext::TestSiz std::queue emptyQueue; discoveryMgr_->discoveryQueue_ = emptyQueue; int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - ASSERT_EQ(ret, SOFTBUS_INVALID_PARAM); + ASSERT_TRUE(CheckSoftbusRes(ret)); discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeInfo.subscribeId); } @@ -174,7 +180,7 @@ HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_005, testing::ext::TestSiz std::queue emptyQueue; discoveryMgr_->discoveryQueue_ = emptyQueue; int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - ASSERT_EQ(ret, SOFTBUS_IPC_ERR); + ASSERT_TRUE(CheckSoftbusRes(ret)); discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); } @@ -203,7 +209,7 @@ HWTEST_F(DmDiscoveryManagerTest, StopDeviceDiscovery_002, testing::ext::TestSize std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; int32_t ret = discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** diff --git a/test/commonunittest/UTTest_dm_publish_manager.cpp b/test/commonunittest/UTTest_dm_publish_manager.cpp index 1eef1fff1a406491abf074be027d61c48e91c82e..5043ec557d3912d86779bc61ffa3cd9d1635729a 100644 --- a/test/commonunittest/UTTest_dm_publish_manager.cpp +++ b/test/commonunittest/UTTest_dm_publish_manager.cpp @@ -47,6 +47,10 @@ std::shared_ptr softbusConnector_ = std::make_shared listener_ = std::make_shared(); std::shared_ptr publishMgr_ = std::make_shared(softbusConnector_, listener_); +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || ret == SOFTBUS_IPC_ERR; +} /** * @tc.name: DmPublishManager_001 * @tc.desc: Test whether the DmPublishManager function can generate a new pointer @@ -111,12 +115,13 @@ HWTEST_F(DmPublishManagerTest, PublishDeviceDiscovery_002, testing::ext::TestSiz publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); pkgName = "com.ohos.helloworld.new"; int32_t ret = publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); - ASSERT_EQ(ret, SOFTBUS_INVALID_PARAM); + ASSERT_TRUE(CheckSoftbusRes(ret)); publishMgr_->UnPublishDeviceDiscovery(pkgName, publishInfo.publishId); } /** * @tc.name: OnPublishResult_001 + * * @tc.desc: The OnPublishFailed function takes the wrong case and emptying pkgName * @tc.type: FUNC * @tc.require: I5N1K3 diff --git a/test/commonunittest/UTTest_dm_timer.cpp b/test/commonunittest/UTTest_dm_timer.cpp index f883a68afcdc906b4ae1ff8b369c1ed521649350..bcb9066b5d1ccca95f62d7595794bead312ef0fb 100644 --- a/test/commonunittest/UTTest_dm_timer.cpp +++ b/test/commonunittest/UTTest_dm_timer.cpp @@ -101,7 +101,7 @@ HWTEST_F(TimeHeapTest, DeleteTimer_001, testing::ext::TestSize.Level0) EXPECT_EQ(ERR_DM_INPUT_PARA_INVALID, ret); ret = timer->DeleteTimer(name); - EXPECT_EQ(DM_OK, ret); + EXPECT_EQ(ERR_DM_FAILED, ret); } /** diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 2a9142c63756ede7033efd8175565e7fcfa59c2e..538aceac931795ceddd6edf7c1854cd0ecb76632 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -12,16 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include "UTTest_hichain_auth_connector.h" - +#include "dm_anonymous.h" #include "dm_constants.h" #include "hichain_auth_connector.h" +static int32_t g_processCredentialResultCode = -1; +static std::string g_processCredentialReturnDataStr = ""; + namespace OHOS { namespace DistributedHardware { void HiChainAuthConnectorTest::SetUp() { + g_processCredentialResultCode = -1; + g_processCredentialReturnDataStr = ""; } void HiChainAuthConnectorTest::TearDown() @@ -157,6 +162,20 @@ HWTEST_F(HiChainAuthConnectorTest, onRequest_003, testing::ext::TestSize.Level0) EXPECT_NE(hiChain_->dmDeviceAuthCallback_, nullptr); } +HWTEST_F(HiChainAuthConnectorTest, onRequest_004, testing::ext::TestSize.Level0) +{ + int64_t requestId = 0; + int operationCode = 0; + char *reqParams = nullptr; + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr mockCallback = std::make_shared(); + hiChainAuthConnector->dmDeviceAuthCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) + .Times(1) + .WillOnce(testing::Return(ERR_DM_FAILED)); + EXPECT_NE(hiChainAuthConnector->onRequest(requestId, operationCode, reqParams), nullptr); +} + HWTEST_F(HiChainAuthConnectorTest, onFinish_001, testing::ext::TestSize.Level0) { int64_t requestId = 0; @@ -228,6 +247,61 @@ HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_001, testing::ext::TestSiz EXPECT_NE(ret, DM_OK); } +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_002, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}";; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_003, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_004, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 1)"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_005, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "key"})"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_006, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 0, "publicKey": "key"})"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(HiChainAuthConnectorTest, QueryCredential_001, testing::ext::TestSize.Level0) { std::string localUdid = "2131351352"; @@ -241,12 +315,90 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); int32_t osAccountId = 1245; bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); } +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = SafetyDump(jsonObject); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = SafetyDump(jsonObject); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = SafetyDump(jsonObject); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = SafetyDump(jsonObject); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = SafetyDump(jsonObject); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = SafetyDump(jsonObject); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_TRUE(ret); +} + HWTEST_F(HiChainAuthConnectorTest, GetCredential_001, testing::ext::TestSize.Level0) { std::string localUdid; @@ -265,6 +417,72 @@ HWTEST_F(HiChainAuthConnectorTest, GetCredential_002, testing::ext::TestSize.Lev EXPECT_EQ(ret, ERR_DM_FAILED); } +HWTEST_F(HiChainAuthConnectorTest, GetCredential_003, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_004, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_005, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_006, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_007, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_008, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(HiChainAuthConnectorTest, ImportCredential_001, testing::ext::TestSize.Level0) { int32_t localUdid = 0; @@ -283,6 +501,50 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestSize. EXPECT_NE(ret, DM_OK); } +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_003, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_004, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_005, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": -1})"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_006, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 0})"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_001, testing::ext::TestSize.Level0) { std::string deviceId; @@ -298,5 +560,56 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_002, testing::ext::TestSize. int32_t ret = hiChain_->DeleteCredential(deviceId, userId); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_003, testing::ext::TestSize.Level0) +{ + std::string deviceId = "test"; + int32_t userId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_004, testing::ext::TestSize.Level0) +{ + std::string deviceId = "test"; + int32_t userId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_005, testing::ext::TestSize.Level0) +{ + std::string deviceId = "test"; + int32_t userId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 100})"; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, 100); +} } // namespace DistributedHardware } // namespace OHOS + +extern "C" __attribute__((constructor)) DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, + const char *requestParams, char **returnData) +{ + if (requestParams == nullptr || returnData == nullptr) { + return -1; + } + + if (g_processCredentialReturnDataStr.empty()) { + *returnData = nullptr; + return -1; + } + + char *charArray = strdup(g_processCredentialReturnDataStr.c_str()); + if (charArray == nullptr) { + return -1; + } + + *returnData = charArray; + return g_processCredentialResultCode; +} diff --git a/test/commonunittest/UTTest_hichain_auth_connector.h b/test/commonunittest/UTTest_hichain_auth_connector.h index 6709fd41e80cb4c23b623646eebf2254676132da..3c708b59809563ae030627fca58ac720f75859bf 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.h +++ b/test/commonunittest/UTTest_hichain_auth_connector.h @@ -17,9 +17,11 @@ #define OHOS_UTTEST_HICHAIN_AUTH_CONNECTOR_H #include +#include #include #include "hichain_auth_connector.h" +#include "hichain_connector_callback.h" namespace OHOS { namespace DistributedHardware { @@ -31,6 +33,20 @@ public: void TearDown(); std::shared_ptr hiChain_ = std::make_shared(); }; + +class MockIDmDeviceAuthCallback : public IDmDeviceAuthCallback { +public: + MockIDmDeviceAuthCallback() = default; + virtual ~MockIDmDeviceAuthCallback() = default; + + MOCK_METHOD(bool, AuthDeviceTransmit, (int64_t requestId, const uint8_t *data, uint32_t dataLen), (override)); + MOCK_METHOD(void, AuthDeviceFinish, (int64_t requestId), (override)); + MOCK_METHOD(void, AuthDeviceError, (int64_t requestId, int32_t errorCode), (override)); + MOCK_METHOD(void, AuthDeviceSessionKey, + (int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen), (override)); + MOCK_METHOD(void, GetRemoteDeviceId, (std::string &deviceId), (override)); + MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_UTTEST_HICHAIN_AUTH_CONNECTOR_H diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index 23acd37713a857b7e842bc5415fe5294243919c2..1e7e7fc291d272d872529380f17a1c033da1d24b 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,13 +20,13 @@ #include #include -#include "parameter.h" +#include "device_manager_service_listener.h" #include "dm_anonymous.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_credential_manager.h" +#include "dm_log.h" #include "dm_random.h" -#include "hichain_connector.h" -#include "device_manager_service_listener.h" +#include "parameter.h" namespace OHOS { namespace DistributedHardware { @@ -231,6 +231,37 @@ HWTEST_F(HichainConnectorTest, from_json_001, testing::ext::TestSize.Level0) EXPECT_EQ(groupInfo.groupVisibility, 5); } +/** + * @tc.name: from_json_002 + * @tc.desc: Pass in arguments to the from_JSON function and convert it to the correct value + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, from_json_002, testing::ext::TestSize.Level0) +{ + GroupInfo groupInfo; + groupInfo.userId = "test"; + groupInfo.groupName = "test"; + nlohmann::json jsonObject; + jsonObject[FIELD_GROUP_NAME] = 0; + jsonObject[FIELD_GROUP_ID] = 0; + jsonObject[FIELD_GROUP_OWNER] = 0; + jsonObject[FIELD_GROUP_TYPE] = "test"; + jsonObject[FIELD_GROUP_VISIBILITY] = "test"; + jsonObject[FIELD_USER_ID] = "userId"; + from_json(jsonObject, groupInfo); + EXPECT_EQ(groupInfo.userId, "userId"); + + jsonObject[FIELD_USER_ID] = "0"; + jsonObject.erase(FIELD_GROUP_NAME); + jsonObject.erase(FIELD_GROUP_ID); + jsonObject.erase(FIELD_GROUP_OWNER); + jsonObject.erase(FIELD_GROUP_TYPE); + jsonObject.erase(FIELD_GROUP_VISIBILITY); + from_json(jsonObject, groupInfo); + EXPECT_EQ(groupInfo.groupName, "test"); +} + /** * @tc.name: HiChainConnector_001 * @tc.desc: Returns a new pointer to the HiChainConnector constructor new @@ -369,53 +400,88 @@ HWTEST_F(HichainConnectorTest, onRequest_002, testing::ext::TestSize.Level0) EXPECT_EQ(ret, nullptr); } +/** + * @tc.name: onRequest_003 + * @tc.desc: Test the onRequest method of HiChainConnector to ensure it handles different + * return values from GetPinCode correctly. + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, onRequest_003, testing::ext::TestSize.Level0) +{ + int64_t requestId = 2; + int32_t operationCode = 3; + char *reqParams = nullptr; + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr mockCallback = std::make_shared(); + hiChainConnector->hiChainConnectorCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) + .Times(1) + .WillOnce(testing::Return(ERR_DM_FAILED)); + EXPECT_NE(hiChainConnector->onRequest(requestId, operationCode, reqParams), nullptr); + + EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_OK)); + EXPECT_NE(hiChainConnector->onRequest(requestId, operationCode, reqParams), nullptr); +} + /** * @tc.name: GetConnectPara_001 - * @tc.desc: set para not null and go to the second branch + * @tc.desc: Test GetConnectPara method when hiChainConnectorCallback_ is set to nullptr, + * ensuring it returns an empty string. * @tc.type: FUNC * @tc.require: AR000GHSJK */ HWTEST_F(HichainConnectorTest, GetConnectPara_001, testing::ext::TestSize.Level0) { std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->RegisterHiChainCallback(std::make_shared()); - std::string deviceId = "23445"; - std::string reqDeviceId = "234566"; - std::string p; + hiChainConnector->hiChainConnectorCallback_ = nullptr; + std::string deviceId = "12345"; + std::string reqDeviceId = "12345"; std::string ret = hiChainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, p); + EXPECT_EQ(ret, ""); } /** * @tc.name: GetConnectPara_002 - * @tc.desc:Empty deviceId so that jsonObject.is_discarded is null and the value of connectAddr is returned + * @tc.desc: Test GetConnectPara method with an empty deviceId to ensure JSON parsing fails + * and returns an empty string. * @tc.type: FUNC * @tc.require: AR000GHSJK */ HWTEST_F(HichainConnectorTest, GetConnectPara_002, testing::ext::TestSize.Level0) { std::string deviceId; - std::string reqDeviceId = "234566"; + std::string reqDeviceId = "12345"; + std::shared_ptr mockCallback = std::make_shared(); std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->RegisterHiChainCallback(std::make_shared()); + hiChainConnector->hiChainConnectorCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetConnectAddr(testing::_)) + .Times(1) + .WillOnce(testing::Return(R"({"key": "value"})")); std::string ret = hiChainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, ""); + EXPECT_NE(ret, ""); } /** * @tc.name: GetConnectPara_003 - * @tc.desc: hiChainConnectorCallback_ is nullptr return "" + * @tc.desc: Test GetConnectPara method with invalid JSON returned by hiChainConnectorCallback_ + * to ensure it returns an empty string. * @tc.type: FUNC * @tc.require: AR000GHSJK */ HWTEST_F(HichainConnectorTest, GetConnectPara_003, testing::ext::TestSize.Level0) { - std::string deviceId = "deviceIdTest"; - std::string reqDeviceId = "11369"; + std::string deviceId; + std::string reqDeviceId = "12345"; + std::shared_ptr mockCallback = std::make_shared(); std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->hiChainConnectorCallback_ = nullptr; + hiChainConnector->hiChainConnectorCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetConnectAddr(testing::_)) + .Times(1) + .WillOnce(testing::Return("invalid json")); std::string ret = hiChainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, ""); + EXPECT_EQ(ret, "invalid json"); } /** @@ -502,12 +568,19 @@ HWTEST_F(HichainConnectorTest, GetSyncGroupList_002, testing::ext::TestSize.Leve { std::vector groupList; GroupInfo groupList1; - groupList1.groupName = "hichainconnector"; - groupList1.groupId = "123456"; - groupList1.groupOwner = "doftbus"; - groupList1.groupType = 1; - groupList1.groupVisibility = 2; + groupList1.groupName = "groupName"; + groupList1.groupId = 1; + groupList1.groupOwner = "ohos.distributedhardware.devicemanager"; + groupList1.groupType = 7; + groupList1.groupVisibility = 1; groupList.push_back(groupList1); + GroupInfo groupList2; + groupList2.groupName = "hichainconnector"; + groupList2.groupId = "123456"; + groupList2.groupOwner = "doftbus"; + groupList2.groupType = 1; + groupList2.groupVisibility = 2; + groupList.push_back(groupList2); std::vector syncGroupList; std::shared_ptr hiChainConnector = std::make_shared(); int ret = hiChainConnector->GetSyncGroupList(groupList, syncGroupList); @@ -572,6 +645,46 @@ HWTEST_F(HichainConnectorTest, onFinish_001, testing::ext::TestSize.Level0) EXPECT_EQ(ret, DM_OK); } +/** + * @tc.name: onFinish_002 + * @tc.desc: return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, onFinish_002, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + int operationCode = GroupOperationCode::MEMBER_JOIN; + const char *returnData = "returnDataTest"; + std::shared_ptr hiChainConnector = std::make_shared(); + int32_t ret = hiChainConnector->RegisterHiChainCallback(std::make_shared()); + EXPECT_EQ(ret, DM_OK); + ret = hiChainConnector->UnRegisterHiChainCallback(); + EXPECT_EQ(ret, DM_OK); + + hiChainConnector->onFinish(requestId, operationCode, returnData); + + operationCode = GroupOperationCode::GROUP_CREATE; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + hiChainConnector->networkStyle_ = 1; + hiChainConnector->hiChainResCallback_ = nullptr; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConn = std::make_shared(); + hiChainConnector->hiChainResCallback_ = std::make_shared(hiChainConn, listener); + hiChainConnector->onFinish(requestId, operationCode, returnData); + + operationCode = GroupOperationCode::GROUP_DISBAND; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + hiChainConnector->hiChainResCallback_ = nullptr; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + EXPECT_EQ(hiChainConnector->hiChainConnectorCallback_, nullptr); +} + /** * @tc.name: onError_001 * @tc.desc: return DM_OK @@ -599,6 +712,45 @@ HWTEST_F(HichainConnectorTest, onError_001, testing::ext::TestSize.Level0) EXPECT_EQ(ret, DM_OK); } +/** + * @tc.name: onError_002 + * @tc.desc: return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, onError_002, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + int operationCode = GroupOperationCode::MEMBER_JOIN; + int errorCode = 1; + const char *errorReturn = "errorReturnTest"; + std::shared_ptr hiChainConnector = std::make_shared(); + int32_t ret = hiChainConnector->RegisterHiChainCallback(std::make_shared()); + EXPECT_EQ(ret, DM_OK); + ret = hiChainConnector->UnRegisterHiChainCallback(); + EXPECT_EQ(ret, DM_OK); + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + operationCode = GroupOperationCode::GROUP_CREATE; + hiChainConnector->networkStyle_ = 0; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + hiChainConnector->networkStyle_ = 1; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConn = std::make_shared(); + hiChainConnector->hiChainResCallback_ = std::make_shared(hiChainConn, listener); + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + operationCode = GroupOperationCode::GROUP_DISBAND; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + hiChainConnector->hiChainResCallback_ = nullptr; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + EXPECT_EQ(hiChainConnector->hiChainConnectorCallback_, nullptr); +} + /** * @tc.name: DeleteGroup_002 * @tc.desc: return ERR_DM_FAILED @@ -1048,7 +1200,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_001, testing::ext::TestS HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1067,7 +1219,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_003, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 1; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1086,7 +1238,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_004, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 4; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1118,7 +1270,7 @@ HWTEST_F(HichainConnectorTest, addMultiMembersExt_001, testing::ext::TestSize.Le HWTEST_F(HichainConnectorTest, addMultiMembersExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->addMultiMembersExt(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -1162,7 +1314,7 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_001, testing::ext::TestSize HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = SafetyDump(jsonObj); std::vector udidList; std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr.c_str(), udidList); @@ -1170,28 +1322,44 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize } /** - * @tc.name: DeleteAllGroup_001 + * @tc.name: GetTrustedDevicesUdid_003 + * @tc.desc: Verify that the function returns DM_OK and correctly populates the udidList. * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(HichainConnectorTest, DeleteAllGroup_001, testing::ext::TestSize.Level0) +HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_003, testing::ext::TestSize.Level0) { - int32_t userId = 1; + const char* jsonStr = R"({ + "device1": { + "authId": "valid_udid_1" + }, + "device2": { + "authId": 12345 + }, + "device3": { + "authId": "valid_udid_2" + } + })"; + + std::vector udidList; std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->DeleteAllGroup(userId); - EXPECT_NE(hiChainConnector->deviceGroupManager_, nullptr); + int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr, udidList); + EXPECT_EQ(ret, DM_OK); + + std::vector expectedUdidList = {"valid_udid_1", "valid_udid_2"}; + EXPECT_EQ(udidList, expectedUdidList); } /** - * @tc.name: DeleteP2PGroup_001 + * @tc.name: DeleteAllGroup_001 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(HichainConnectorTest, DeleteP2PGroup_001, testing::ext::TestSize.Level0) +HWTEST_F(HichainConnectorTest, DeleteAllGroup_001, testing::ext::TestSize.Level0) { int32_t userId = 1; std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->DeleteP2PGroup(userId); + hiChainConnector->DeleteAllGroup(userId); EXPECT_NE(hiChainConnector->deviceGroupManager_, nullptr); } diff --git a/test/commonunittest/UTTest_hichain_connector.h b/test/commonunittest/UTTest_hichain_connector.h index 1040a08469b1279579298a75ec95129cbc52e53c..a641b0d897a2ffceb2e4580ba695675ee83f306c 100644 --- a/test/commonunittest/UTTest_hichain_connector.h +++ b/test/commonunittest/UTTest_hichain_connector.h @@ -16,6 +16,7 @@ #define OHOS_UTTEST_HICHAIN_CONNECTOR_H #include +#include #include #include #include @@ -41,6 +42,16 @@ public: void SetUp(); void TearDown(); }; + +class MockIHiChainConnectorCallback : public IHiChainConnectorCallback { +public: + MockIHiChainConnectorCallback() = default; + virtual ~MockIHiChainConnectorCallback() = default; + MOCK_METHOD(void, OnGroupCreated, (int64_t requestId, const std::string &groupId), (override)); + MOCK_METHOD(void, OnMemberJoin, (int64_t requestId, int32_t status), (override)); + MOCK_METHOD(std::string, GetConnectAddr, (std::string deviceId), (override)); + MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_HICHAIN_CONNECTOR_H diff --git a/test/commonunittest/UTTest_mine_hichain_connector.cpp b/test/commonunittest/UTTest_mine_hichain_connector.cpp index 1769a128221476645384642256e11f62db3aa31c..f7c37a7469170b8c9b9ac7b62fd9bea9141f8a7e 100644 --- a/test/commonunittest/UTTest_mine_hichain_connector.cpp +++ b/test/commonunittest/UTTest_mine_hichain_connector.cpp @@ -15,6 +15,7 @@ #include "UTTest_mine_hichain_connector.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "mine_hichain_connector.h" @@ -112,7 +113,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_002, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -122,7 +123,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_003, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -132,7 +133,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, RequestCredential_001, testing::ext::Test std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string returnJsonStr = jsonObject.dump(); + std::string returnJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->RequestCredential(returnJsonStr); EXPECT_EQ(ret, DM_OK); } @@ -169,7 +170,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestS std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = SafetyDump(jsonObject); std::string returnJsonStr; int32_t ret = minHiChain->ImportCredential(reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_REGISTER_CALLBACK); diff --git a/test/commonunittest/UTTest_multiple_user_connector.cpp b/test/commonunittest/UTTest_multiple_user_connector.cpp index 1ac739e536bf3fd40d81ebc28de8bc07e66347f4..962f4a01198cfeb9dbdfdc9e08e8f0b3772521fe 100644 --- a/test/commonunittest/UTTest_multiple_user_connector.cpp +++ b/test/commonunittest/UTTest_multiple_user_connector.cpp @@ -82,6 +82,41 @@ HWTEST_F(MultipleUserConnectorTest, GetSwitchOldUserId_001, testing::ext::TestSi userIdOut = MultipleUserConnector::GetSwitchOldUserId(); ASSERT_EQ(userIdIn, userIdOut); } + +HWTEST_F(MultipleUserConnectorTest, GetSwitchOldAccountId_001, testing::ext::TestSize.Level0) +{ + std::string accountId = "accountId"; + MultipleUserConnector::SetSwitchOldAccountId(accountId); + std::string accountIdOut = MultipleUserConnector::GetSwitchOldAccountId(); + ASSERT_EQ(accountId, accountIdOut); +} + +HWTEST_F(MultipleUserConnectorTest, GetSwitchOldAccountName_001, testing::ext::TestSize.Level0) +{ + std::string accountName = "accountName"; + MultipleUserConnector::SetSwitchOldAccountName(accountName); + std::string accountNameOut = MultipleUserConnector::GetSwitchOldAccountName(); + ASSERT_EQ(accountName, accountNameOut); +} + +HWTEST_F(MultipleUserConnectorTest, GetAllUserIds_001, testing::ext::TestSize.Level0) +{ + std::vector userIdVec; + int32_t ret = MultipleUserConnector::GetAllUserIds(userIdVec); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(MultipleUserConnectorTest, GetAccountInfoByUserId_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 123; + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = "12456"; + MultipleUserConnector::dmAccountInfoMap_[userId] = dmAccountInfo; + auto ret = MultipleUserConnector::GetAccountInfoByUserId(userId); + ASSERT_FALSE(ret.accountId.empty()); + + MultipleUserConnector::DeleteAccountInfoByUserId(userId); +} } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 202417e4a9260165c7e93f8984d18277ea94cc2b..4e0e13bf84dd31313d56d31391cf1b74134eb4a6 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -20,7 +20,7 @@ namespace OHOS { namespace DistributedHardware { -void PremissionManagerTest::SetUp() +void PermissionManagerTest::SetUp() { const int32_t permsNum = 2; const int32_t indexZero = 0; @@ -43,16 +43,35 @@ void PremissionManagerTest::SetUp() SetSelfTokenID(tokenId); OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } +constexpr int32_t PAKAGE_NAME_SIZE_MAX = 256; +#define AUTH_CODE_WHITE_LIST_NUM (3) +constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "com.huawei.msdp.hmringgenerator", + "com.huawei.msdp.hmringdiscriminator", + "CollaborationFwk", +}; -void PremissionManagerTest::TearDown() +#define PIN_HOLDER_WHITE_LIST_NUM (1) +constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "CollaborationFwk", +}; + +#define SYSTEM_SA_WHITE_LIST_NUM (4) +constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "Samgr_Networking", + "ohos.distributeddata.service", + "ohos.dslm", + "ohos.deviceprofile", +}; +void PermissionManagerTest::TearDown() { } -void PremissionManagerTest::SetUpTestCase() +void PermissionManagerTest::SetUpTestCase() { } -void PremissionManagerTest::TearDownTestCase() +void PermissionManagerTest::TearDownTestCase() { } @@ -64,7 +83,7 @@ namespace { * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckPermission_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckPermission_001, testing::ext::TestSize.Level0) { bool ret = PermissionManager::GetInstance().CheckPermission(); ASSERT_EQ(ret, true); @@ -76,7 +95,7 @@ HWTEST_F(PremissionManagerTest, CheckPermission_001, testing::ext::TestSize.Leve * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, GetCallerProcessName_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, GetCallerProcessName_001, testing::ext::TestSize.Level0) { std::string processName; int32_t ret = PermissionManager::GetInstance().GetCallerProcessName(processName); @@ -89,7 +108,7 @@ HWTEST_F(PremissionManagerTest, GetCallerProcessName_001, testing::ext::TestSize * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_001, testing::ext::TestSize.Level0) { std::string processName; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); @@ -98,24 +117,49 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_001, testing::ex /** * @tc.name: PinAuthUi::CheckProcessNameValidOnAuthCode_002 - * @tc.desc: the return value is true + * @tc.desc: the return value is false * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ext::TestSize.Level0) { std::string processName = "processName"; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); ASSERT_EQ(ret, false); } +/** + * @tc.name: PinAuthUi::CheckProcessNameValidOnAuthCode_003 + * @tc.desc: the return value is true + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ext::TestSize.Level0) +{ + std::string processName1(g_authCodeWhiteList[0]); + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName1); + ASSERT_EQ(ret, true); + std::string processName2(g_authCodeWhiteList[1]); + ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName2); + ASSERT_EQ(ret, true); + std::string processName3(g_authCodeWhiteList[2]); + ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName3); + ASSERT_EQ(ret, true); +} + +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_004, testing::ext::TestSize.Level0) +{ + std::string processName = "CollaborationFwk"; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + ASSERT_TRUE(ret); +} /** * @tc.name: PinAuthUi::CheckProcessNameValidOnPinHolder_001 * @tc.desc: the return value is false * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_001, testing::ext::TestSize.Level0) { std::string processName; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); @@ -124,16 +168,108 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_001, testing::e /** * @tc.name: PinAuthUi::CheckProcessNameValidOnPinHolder_002 - * @tc.desc: the return value is true + * @tc.desc: the return value is false * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::ext::TestSize.Level0) { std::string processName = "processName"; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); ASSERT_EQ(ret, false); } + +/** + * @tc.name: PinAuthUi::CheckProcessNameValidOnPinHolder_003 + * @tc.desc: the return value is true + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::ext::TestSize.Level0) +{ + std::string processName1(g_pinHolderWhiteList[0]); + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName1); + ASSERT_EQ(ret, true); +} + +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_004, testing::ext::TestSize.Level0) +{ + std::string processName = "CollaborationFwk"; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + ASSERT_TRUE(ret); +} +/** + * @tc.name: PinAuthUi::CheckWhiteListSystemSA_001 + * @tc.desc: the return value is false + * @tc.type:FUNC + * @tc.require: AR000GHSJK +*/ +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); + ASSERT_EQ(ret, false); + pkgName = "pkgName"; + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); + ASSERT_EQ(ret, false); +} + +/** + * @tc.name: PinAuthUi::CheckWhiteListSystemSA_002 + * @tc.desc: the return value is true + * @tc.type:FUNC + * @tc.require: AR000GHSJK +*/ +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_002, testing::ext::TestSize.Level0) +{ + std::string pkgName1(systemSaWhiteList[0]); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName1); + ASSERT_EQ(ret, true); + std::string pkgName2(systemSaWhiteList[1]); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName2); + ASSERT_EQ(ret, true); + std::string pkgName3(systemSaWhiteList[2]); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName3); + ASSERT_EQ(ret, true); + std::string pkgName4(systemSaWhiteList[3]); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName4); + ASSERT_EQ(ret, true); +} + +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_101, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); + ASSERT_FALSE(ret); +} + +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_102, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos.dhardware"; + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); + ASSERT_TRUE(ret); +} + +HWTEST_F(PermissionManagerTest, CheckMonitorPermission_001, testing::ext::TestSize.Level0) +{ + bool ret = PermissionManager::GetInstance().CheckMonitorPermission(); + ASSERT_FALSE(ret); +} + +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnSetDnPolicy_001, testing::ext::TestSize.Level0) +{ + std::string processName = ""; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); + ASSERT_FALSE(ret); + + processName = "processName"; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); + ASSERT_FALSE(ret); + + processName = "collaboration_service"; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); + ASSERT_TRUE(ret); +} } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/commonunittest/UTTest_permission_manager.h b/test/commonunittest/UTTest_permission_manager.h index b66d7c0b72142a67a6ff98a56cbfe0578c6ef49e..e591b47462675d32e9b7bebde4149ec8913b4d57 100644 --- a/test/commonunittest/UTTest_permission_manager.h +++ b/test/commonunittest/UTTest_permission_manager.h @@ -19,13 +19,14 @@ #include #include +#include #include "dm_constants.h" #include "permission_manager.h" namespace OHOS { namespace DistributedHardware { -class PremissionManagerTest : public testing::Test { +class PermissionManagerTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); diff --git a/test/commonunittest/UTTest_pin_auth.cpp b/test/commonunittest/UTTest_pin_auth.cpp index febbdeaab9a1df6e743f47ce3cbe9e9755421a75..c9889e2b32da6bd818dacca168ea83fd31e18552 100644 --- a/test/commonunittest/UTTest_pin_auth.cpp +++ b/test/commonunittest/UTTest_pin_auth.cpp @@ -18,6 +18,7 @@ #include #include +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "nlohmann/json.hpp" @@ -73,7 +74,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_002, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_TOKEN] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -89,7 +90,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_003, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, nullptr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -105,7 +106,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_004, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/commonunittest/dm_radar_helper_test.cpp b/test/commonunittest/dm_radar_helper_test.cpp index 79596bd6810859c4eba2b20e256241516226d46e..d6f83ff24b2a24708214d16192d49948f4a9036e 100644 --- a/test/commonunittest/dm_radar_helper_test.cpp +++ b/test/commonunittest/dm_radar_helper_test.cpp @@ -220,13 +220,6 @@ HWTEST_F(DmRadarHelperTest, ReportDeleteTrustRelation_001, testing::ext::TestSiz struct RadarInfo info = { 0 }; info.stageRes = static_cast(StageRes::STAGE_IDLE); bool res = DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info); - EXPECT_EQ(res, true); -} -HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_001, testing::ext::TestSize.Level0) -{ - struct RadarInfo info = { 0 }; - info.stageRes = static_cast(StageRes::STAGE_SUCC); - bool res = DmRadarHelper::GetInstance().ReportGetTrustDeviceList(info); int32_t stageRes = static_cast(StageRes::STAGE_SUCC); std::string str = "test"; @@ -238,17 +231,10 @@ HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_001, testing::ext::TestSize DmRadarHelper::GetInstance().ReportDestroyPinHolder(str, str, 0, stageRes); int32_t bizStage = static_cast(PinHolderStage::RECEIVE_DESTROY_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str); - + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str, ""); bizStage = static_cast(PinHolderStage::RECEIVE_CREATE_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str); - EXPECT_EQ(res, true); -} -HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_002, testing::ext::TestSize.Level0) -{ - struct RadarInfo info = { 0 }; - info.stageRes = static_cast(StageRes::STAGE_IDLE); - bool res = DmRadarHelper::GetInstance().ReportGetTrustDeviceList(info); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str, ""); + EXPECT_EQ(res, true); } } // namespace DistributedHardware diff --git a/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp b/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp index cd80dd3d3f050680a9efed64b207b7663d631110..13fb677ce4b7647d9e815d738f7399e7c8b6810b 100644 --- a/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp +++ b/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp @@ -55,7 +55,7 @@ void DeviceDiscoveryFuzzTest(const uint8_t* data, size_t size) if (strncpy_s(subInfo.capability, DM_MAX_DEVICE_CAPABILITY_LEN, "111", DM_MAX_DEVICE_CAPABILITY_LEN) != 0) { return; } - std::string extra(reinterpret_cast(data), size); + std::string extra = "extraInfo"; std::shared_ptr callback = std::make_shared(); bundleName = "111"; diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn index 0c1a56a271a048e6cd892fcafe164460d87015a9..abc5aebb6ef9e1011c31fb9e4caf9a53119dc166 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn @@ -56,7 +56,10 @@ ohos_fuzztest("DeviceManagerServiceFuzzTest") { ] sources = [ "device_manager_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] defines = [ "HI_LOG_ENABLE", @@ -66,9 +69,11 @@ ohos_fuzztest("DeviceManagerServiceFuzzTest") { external_deps = [ "ability_base:want", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp b/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp index dfa125cbc8a9e8b36590a18730d59dfd1f3baee7..51e187c50c56a1ecd380d87920ea11b7e01c79bf 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp @@ -38,12 +38,9 @@ void DeviceManagerServiceFuzzTest(const uint8_t* data, size_t size) DmPublishInfo publishInfo; std::map parametricMap; - DeviceManagerService::GetInstance().StartDeviceDiscovery(inputStr, subscribeInfo, inputStr); DeviceManagerService::GetInstance().PublishDeviceDiscovery(inputStr, publishInfo); DeviceManagerService::GetInstance().RequestCredential(inputStr, inputStr); - DeviceManagerService::GetInstance().StopDeviceDiscovery(inputStr, subscribeId); DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(inputStr, publishId); - DeviceManagerService::GetInstance().StartDeviceDiscovery(inputStr, subscribeId, inputStr); DeviceManagerService::GetInstance().GetDeviceInfo(inputStr, info); DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); DeviceManagerService::GetInstance().GetDeviceSecurityLevel(inputStr, inputStr, publishId); diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index 257bef6386a2e92412b88f9c535626514b584438..68743c29d022a91d770d4adcd3df87aa3fec64b6 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -24,7 +24,7 @@ namespace OHOS { namespace DistributedHardware { void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(DmAccesser))) { + if ((data == nullptr) || (size < sizeof(DmAccesser)) || (size < sizeof(int32_t))) { return; } @@ -53,18 +53,15 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) dmAccessee.trustBundleName = trustBundleName; int32_t userId = *(reinterpret_cast(data)); std::string accountId(reinterpret_cast(data), size); - + int32_t bindLevel = *(reinterpret_cast(data)); DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, userId); DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); - DeviceProfileConnector::GetInstance().DeleteAccessControlList(userId, accountId); - DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId); + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId, bindLevel); DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(pkgName, localDeviceId); + DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(pkgName, localDeviceId); DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(localDeviceId); DeviceProfileConnector::GetInstance().GetTrustNumber(localDeviceId); } diff --git a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn index cdfdec4ac75d6c2f420b81a200901be2f84a2158..323167ceeadf9e9ad302047dd381347b5eb8a680 100644 --- a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn @@ -56,13 +56,18 @@ ohos_fuzztest("GetTrustedDeviceListServiceFuzzTest") { sources = [ "get_trusted_devicelist_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] external_deps = [ "ability_base:want", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp b/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp index f8e05ec0a2ed1e21310d2b3b2601d8b122a809e7..99d41ffae0cdcf91b6dad6cb90f3b1251d171651 100644 --- a/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp +++ b/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp @@ -28,8 +28,6 @@ #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_set_useroperation_req.h" diff --git a/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp b/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp index 6e531a28748022915e91f824c5c1e232a9caad9a..b7c8de713697f2bd0b20b2e1482f938b5bec6c05 100644 --- a/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp @@ -37,7 +37,6 @@ void IpcServerListenerFuzzTest(const uint8_t* data, size_t size) std::shared_ptr ipcServerListener = std::make_shared(); ipcServerListener->SendRequest(cmdCode, req, rsp); - ipcServerListener->SendAll(cmdCode, req, rsp); } } } diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn b/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn index 8f0bce41791d822374f9939f607d94db399600e2..737b7b1877742235e9f11e1c384f918d23f86c06 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn @@ -68,7 +68,10 @@ ohos_fuzztest("IpcServerStubFuzzTest") { ] external_deps = [ + "ability_base:want", "c_utils:utils", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "ipc:ipc_core", "ipc:ipc_single", diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp index 3f134f4d013e06aa1c2090fd5df25abd1a625b7f..1a75d5056d5d3646ec456a6daa445b3059a94823 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp @@ -44,18 +44,20 @@ void IpcServerStubFuzzTest(const uint8_t* data, size_t size) MessageParcel data1; MessageParcel reply; MessageOption option; + ProcessInfo processInfo; std::string pkgName(reinterpret_cast(data), size); + processInfo.pkgName = pkgName; sptr listener = sptr(new IpcServerStub()); std::shared_ptr req = nullptr; std::shared_ptr rsp = std::make_shared(); IpcServerStub::GetInstance().Init(); IpcServerStub::GetInstance().OnRemoteRequest(code, data1, reply, option); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); - IpcServerStub::GetInstance().GetDmListener(pkgName); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); + IpcServerStub::GetInstance().GetDmListener(processInfo); IpcServerStub::GetInstance().SendCmd(code, req, rsp); - IpcServerStub::GetInstance().GetAllPkgName(); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + IpcServerStub::GetInstance().GetAllProcessInfo(); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); } } } diff --git a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn index f923a56106c0cd7ca0930cf58c666f53f7cd64d2..a95f167fa56edddaf2f12ae0a9b86c4b1ee62df9 100644 --- a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn @@ -56,13 +56,18 @@ ohos_fuzztest("ShiftLNNGearDeviceServiceFuzzTest") { sources = [ "shift_lnn_gear_device_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] external_deps = [ "ability_base:want", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/BUILD.gn b/test/softbusfuzztest/BUILD.gn index 3196b53dd2217b288fc9f6d3354fd9341793a14a..feb5762194e62b45e23a6550f30102a490afb5c3 100644 --- a/test/softbusfuzztest/BUILD.gn +++ b/test/softbusfuzztest/BUILD.gn @@ -24,8 +24,11 @@ group("fuzztest") { "onsoftbuslistenerdevicefound_fuzzer:fuzztest", "publishsoftbuslnn_fuzzer:fuzztest", "refreshsoftbuslnn_fuzzer:fuzztest", - "softbusadapterobject_fuzzer:fuzztest", "softbusconnector_fuzzer:fuzztest", + "softbusconnectorcommon_fuzzer:fuzztest", + "softbusconnectorpublish_fuzzer:fuzztest", + "softbusconnectorregister_fuzzer:fuzztest", + "softbusconnectorstate_fuzzer:fuzztest", "softbusconnectorstatic_fuzzer:fuzztest", "softbuslistenergetlocaldeviceinfo_fuzzer:fuzztest", "softbussession_fuzzer:fuzztest", diff --git a/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn b/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn index 39dfc216e11061e5fe14ba9e755093fa388fc18e..6ee9bd3af9858231636f62dbe8707c4ac328913f 100644 --- a/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("OnBytesReceivedFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp index 1c25c25cad43d71c95f3f8369e1042a4cc6e892e..2d0979540abe7b696cf88c84ccf7174a15facdf1 100644 --- a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp +++ b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp @@ -45,21 +45,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void OnBytesReceivedFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn index 5ba188f1d3ff8d29011cce482b84eab9d56adbdf..9a4ddcc9573572e69e3c88ccb45493635aeb4ac9 100644 --- a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn @@ -53,12 +53,14 @@ ohos_fuzztest("OnSessionOpenedFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp b/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp index 0fbcade8b4663f86c04b107945678c99da9d95c2..1caed0d58f25e450ef0ff6388ff4a30c01996d61 100644 --- a/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp +++ b/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp @@ -50,21 +50,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void OnSessionOpenedFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn similarity index 81% rename from test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn rename to test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn index 0bc227f7d51ea7c3bc716d04d9f65d38a2be00f1..812059e7b2133384a978661cf56a506dc26bf8a9 100644 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2022-2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -17,10 +17,10 @@ import("//build/test.gni") import("//foundation/distributedhardware/device_manager/device_manager.gni") ##############################fuzztest########################################## -ohos_fuzztest("SoftbusAdapterObjectFuzzTest") { +ohos_fuzztest("SoftbusConnectorCommonFuzzTest") { module_out_path = fuzz_test_output_path fuzz_config_file = - "${devicemanager_path}/test/softbusfuzztest/softbusadapterobject_fuzzer" + "${devicemanager_path}/test/softbusfuzztest/softbusconnectorcommon_fuzzer" include_dirs = [ "${utils_path}/include", @@ -28,7 +28,6 @@ ohos_fuzztest("SoftbusAdapterObjectFuzzTest") { "${common_path}/include/ipc", "${common_path}/include/ipc/model", "${utils_path}/include/ipc/standard", - "${services_path}/include/softbus", "${servicesimpl_path}/include", "${servicesimpl_path}/include/dependency/commonevent", "${servicesimpl_path}/include/dependency/softbus", @@ -43,11 +42,10 @@ ohos_fuzztest("SoftbusAdapterObjectFuzzTest") { "-fno-omit-frame-pointer", ] - sources = [ "softbus_adapter_object_fuzzer.cpp" ] + sources = [ "softbus_connector_common_fuzzer.cpp" ] deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", - "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", ] @@ -55,7 +53,7 @@ ohos_fuzztest("SoftbusAdapterObjectFuzzTest") { defines = [ "HI_LOG_ENABLE", - "DH_LOG_TAG=\"SoftbusAdapterObjectFuzzTest\"", + "DH_LOG_TAG=\"SoftbusConnectorCommonFuzzTest\"", "LOG_DOMAIN=0xD004110", ] } @@ -64,6 +62,6 @@ ohos_fuzztest("SoftbusAdapterObjectFuzzTest") { group("fuzztest") { testonly = true - deps = [ ":SoftbusAdapterObjectFuzzTest" ] + deps = [ ":SoftbusConnectorCommonFuzzTest" ] } ############################################################################### diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/corpus/init b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/corpus/init similarity index 92% rename from test/softbusfuzztest/softbusadapterobject_fuzzer/corpus/init rename to test/softbusfuzztest/softbusconnectorcommon_fuzzer/corpus/init index f7880ef1a502193121ec4b74e27bfc616e66cd26..1b910144fb1ff33a40a44b1d2a491b1ab05b598b 100644 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/corpus/init +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/corpus/init @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/project.xml b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/project.xml similarity index 95% rename from test/softbusfuzztest/softbusadapterobject_fuzzer/project.xml rename to test/softbusfuzztest/softbusconnectorcommon_fuzzer/project.xml index 6d3e765c7dc1097ac2fb92d825dfad6b0b08636d..27c26d11b7d89f7aef7835fb5f95f9e5ecaf6f9d 100644 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/project.xml +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/project.xml @@ -1,5 +1,5 @@ - + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..660e74bced64c772d7c2e77ed5bb0880351c3fdc --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "softbus_connector.h" +#include "softbus_bus_center.h" +#include "dm_device_info.h" +#include "dm_publish_info.h" +#include "dm_subscribe_info.h" +#include "softbus_discovery_callback.h" +#include "softbus_publish_callback.h" +#include "softbus_session.h" +#include "softbus_state_callback.h" +#include "softbus_connector_state_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { +class SoftbusStateCallbackFuzzTest : public ISoftbusStateCallback { +public: + virtual ~SoftbusStateCallbackFuzzTest() {} + + void OnDeviceOnline(std::string deviceId, int32_t authForm) override {} + void OnDeviceOffline(std::string deviceId) override {} + void DeleteOffLineTimer(std::string udidHash) override {} +}; + +void SoftBusConnectorStateFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::string str(reinterpret_cast(data), size); + int32_t authForm = *(reinterpret_cast(data)); + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr callback = std::make_shared(); + + softbusConnector->RegisterSoftbusStateCallback(callback); + softbusConnector->HandleDeviceOnline(str, authForm); + softbusConnector->HandleDeviceOffline(str); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::SoftBusConnectorStateFuzzTest(data, size); + + return 0; +} diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.h b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h similarity index 77% rename from test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.h rename to test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h index 055da39fa7270b77063f40ac266ee2aa7c036b1c..9e9ec63ab4fe43485d75d469fc74ab87dbf5f13b 100644 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.h +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h @@ -13,9 +13,9 @@ * limitations under the License. */ -#ifndef SOFTBUS_ADAPTER_OBJECT_FUZZER_H -#define SOFTBUS_ADAPTER_OBJECT_FUZZER_H +#ifndef SOFTBUS_CONNECTOR_STATE_FUZZER_H +#define SOFTBUS_CONNECTOR_STATE_FUZZER_H -#define FUZZ_PROJECT_NAME "softbusadapterobject_fuzzer" +#define FUZZ_PROJECT_NAME "softbusconnectorstate_fuzzer" -#endif // SOFTBUS_ADAPTER_OBJECT_FUZZER_H \ No newline at end of file +#endif // SOFTBUS_CONNECTOR_STATE_FUZZER_H \ No newline at end of file diff --git a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp index a64036b634d49ec93c4f09338f6ea18905f6a01c..c73803398143028a88c6f956c97f4babb31ba72d 100644 --- a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp +++ b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp @@ -47,21 +47,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) @@ -73,7 +63,6 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) int result = *(reinterpret_cast(data)); int32_t sessionId = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); - PeerSocketInfo info; std::shared_ptr softbusSession = std::make_shared(); softbusSession->RegisterSessionCallback(std::make_shared()); @@ -81,9 +70,6 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) softbusSession->OpenAuthSession(str); softbusSession->CloseAuthSession(sessionId); softbusSession->OnBytesReceived(result, str.c_str(), str.size()); - softbusSession->OnUnbindSessionOpened(sessionId, info); - softbusSession->OpenUnbindSession(str); - softbusSession->CloseUnbindSession(sessionId); softbusSession->GetPeerDeviceId(sessionId, str); softbusSession->SendData(sessionId, str); softbusSession->SendHeartbeatData(sessionId, str); diff --git a/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn b/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn index 96ffb16b67fe152eb7f5d56318c5f57f41761bfb..359a1beb97e7d86973eb04ac7d5ef70a426d72fa 100644 --- a/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn @@ -46,7 +46,9 @@ ohos_fuzztest("SoftbusSessionObjectFuzzTest") { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", + "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "safwk:system_ability_fwk" ] diff --git a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp index f3e72c466cf116f831e0ae0d8c1d3811eb2bacae..fe688c42f599ad3d63da0832dddb28801925fd5c 100644 --- a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp +++ b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp @@ -45,21 +45,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 6e454e3991a22c02490de8c9b948515faa140a7d..753c15a8b005f55e79330d677b39aebf605c48cf 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -45,6 +45,13 @@ void MineSoftbusListenerTest::TearDownTestCase() } namespace { + +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || + ret == SOFTBUS_IPC_ERR; +} + HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_001, testing::ext::TestSize.Level0) { string pkgName; @@ -60,7 +67,7 @@ HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_002, testing::ext::TestSize. nlohmann::json jsonObj; jsonObj["findDeviceMode"] = 4; string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); DmSubscribeInfo dmSubscribeInfo; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->RefreshSoftbusLNN(pkgName, searchJson, dmSubscribeInfo); @@ -72,7 +79,7 @@ HWTEST_F(MineSoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestS uint16_t subscribeId = 1; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->StopRefreshSoftbusLNN(subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } HWTEST_F(MineSoftbusListenerTest, OnPublishResult_001, testing::ext::TestSize.Level0) @@ -138,7 +145,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_002, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(1); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -151,7 +158,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_003, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(2); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -164,7 +171,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_004, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(3); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -177,7 +184,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_005, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(4); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, DM_OK); @@ -755,7 +762,7 @@ HWTEST_F(MineSoftbusListenerTest, PublishDeviceDiscovery_001, testing::ext::Test { std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->PublishDeviceDiscovery(); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } HWTEST_F(MineSoftbusListenerTest, MatchSearchDealTask_001, testing::ext::TestSize.Level0) diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.h b/test/softbusunittest/UTTest_mine_softbus_listener.h index 314dafb9d8f69ccf6001b2279a65e561fd29ec1a..685e50c40b9d7fc6a3022a233355d356d62ff244 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.h +++ b/test/softbusunittest/UTTest_mine_softbus_listener.h @@ -23,7 +23,6 @@ #include #include -#include "softbus_adapter.h" #include "softbus_bus_center.h" #include "softbus_listener.h" #include "dm_device_info.h" diff --git a/test/softbusunittest/UTTest_softbus_adapter.cpp b/test/softbusunittest/UTTest_softbus_adapter.cpp deleted file mode 100644 index eea23fcaffa2927690e6304ada1e4d9f248728f0..0000000000000000000000000000000000000000 --- a/test/softbusunittest/UTTest_softbus_adapter.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 "UTTest_softbus_adapter.h" - -#include "dm_anonymous.h" -#include "dm_constants.h" -#include "dm_log.h" -#include "nlohmann/json.hpp" -#include "softbus_adapter.h" -#include "softbus_connector.h" -#include "softbus_error_code.h" - -namespace OHOS { -namespace DistributedHardware { -void SoftbusAdapterTest::SetUp() -{ -} -void SoftbusAdapterTest::TearDown() -{ -} -void SoftbusAdapterTest::SetUpTestCase() -{ -} -void SoftbusAdapterTest::TearDownTestCase() -{ -} - -namespace { -HWTEST_F(SoftbusAdapterTest, CreateSoftbusSessionServer_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string sessionName; - int32_t ret = SoftbusAdapter::GetInstance().CreateSoftbusSessionServer(pkgName, sessionName); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); -} - -HWTEST_F(SoftbusAdapterTest, RemoveSoftbusSessionServer_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string sessionName; - int32_t ret = SoftbusAdapter::GetInstance().RemoveSoftbusSessionServer(pkgName, sessionName); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); -} - -HWTEST_F(SoftbusAdapterTest, OnSoftbusSessionOpened_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string str = "132131321345"; - PeerSocketInfo info = { - .name = const_cast(str.c_str()), - .pkgName = const_cast(str.c_str()), - .networkId = const_cast(str.c_str()), - }; - SoftbusAdapter::GetInstance().OnSoftbusSessionOpened(socket, info); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnSoftbusSessionClosed_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - SoftbusAdapter::GetInstance().OnSoftbusSessionClosed(socket, reason); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnBytesReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().OnBytesReceived(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnStreamReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - StreamData data; - StreamData exta; - StreamFrameInfo frameInfo; - SoftbusAdapter::GetInstance().OnStreamReceived(socket, &data, &exta, &frameInfo); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnMessageReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().OnMessageReceived(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnQosEvent_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - QoSEvent eventId = static_cast(1); - QosTV qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, - }; - uint32_t qosCount = 1; - SoftbusAdapter::GetInstance().OnQosEvent(socket, eventId, qosInfo, qosCount); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnError, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnSoftbusSessionBind_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string str = "132131321345"; - PeerSocketInfo info = { - .name = const_cast(str.c_str()), - .pkgName = const_cast(str.c_str()), - .networkId = const_cast(str.c_str()), - }; - SoftbusAdapter::GetInstance().iSocketListener_.OnBind(socket, info); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnError, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnSoftbusSessionClosed_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - SoftbusAdapter::GetInstance().iSocketListener_.OnShutdown(socket, reason); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnBytesReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().iSocketListener_.OnBytes(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnStreamReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - StreamData data; - StreamData exta; - StreamFrameInfo frameInfo; - SoftbusAdapter::GetInstance().iSocketListener_.OnStream(socket, &data, &exta, &frameInfo); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnMessageReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().iSocketListener_.OnMessage(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnQosEvent_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - QoSEvent eventId = static_cast(1); - QosTV qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, - }; - uint32_t qosCount = 1; - SoftbusAdapter::GetInstance().iSocketListener_.OnQos(socket, eventId, qosInfo, qosCount); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} -} // namespace -} // namespace DistributedHardware -} // namespace OHOS diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 8bb115a59d750ae10b84a4f3d3ae2958ee679d7f..57dbcc5e2c8934e86f91585f8e2fc2eed07acd17 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -42,6 +42,7 @@ public: virtual ~SoftbusStateCallbackTest() {} void OnDeviceOnline(std::string deviceId, int32_t authForm) {} void OnDeviceOffline(std::string deviceId) {} + void DeleteOffLineTimer(std::string udidHash) override {} }; class SoftbusDiscoveryCallbackTest : public ISoftbusDiscoveryCallback { @@ -102,6 +103,12 @@ void SoftbusConnectorTest::TearDownTestCase() namespace { std::shared_ptr listener = std::make_shared(); +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || + ret == SOFTBUS_IPC_ERR; +} + /** * @tc.name: SoftbusConnector_001 * @tc.desc: set SoftbusConnector to new a pointer, and the pointer nou equal nullptr @@ -206,9 +213,8 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0 DmSubscribeInfo dmSubscribeInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(CheckSoftbusRes(ret)); } - /** * @tc.name: StartDiscovery_002 * @tc.desc: get StartDiscovery to wrong branch and return SOFTBUS_IPC_ERR @@ -220,7 +226,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_002, testing::ext::TestSize.Level0 uint16_t subscribeId = 0; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -248,7 +254,7 @@ HWTEST_F(SoftbusConnectorTest, PublishDiscovery_001, testing::ext::TestSize.Leve DmPublishInfo dmPublishInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->PublishDiscovery(dmPublishInfo); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -807,14 +813,16 @@ HWTEST_F(SoftbusConnectorTest, AddMemberToDiscoverMap_002, testing::ext::TestSiz * @tc.name: SetPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, SetPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SetProcessInfo_001, testing::ext::TestSize.Level0) { + ProcessInfo processInfo; + std::vector processInfoVec; std::string pkgName = "pkgName"; std::vector pkgNameVec; std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SetPkgNameVec(pkgNameVec); - softbusConnector->SetPkgName(pkgName); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), false); + softbusConnector->SetProcessInfoVec(processInfoVec); + softbusConnector->SetProcessInfo(processInfo); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), false); } /** @@ -865,25 +873,25 @@ HWTEST_F(SoftbusConnectorTest, GetNetworkIdByDeviceId_001, testing::ext::TestSiz } /** - * @tc.name: SetPkgNameVec_001 + * @tc.name: SetProcessInfoVec_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, SetPkgNameVec_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SetProcessInfoVec_001, testing::ext::TestSize.Level0) { - std::vector pkgNameVec; + std::vector processInfoVec; std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SetPkgNameVec(pkgNameVec); - EXPECT_EQ(pkgNameVec.empty(), true); + softbusConnector->SetProcessInfoVec(processInfoVec); + EXPECT_EQ(processInfoVec.empty(), true); } /** * @tc.name: GetPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, GetPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr softbusConnector = std::make_shared(); - auto ret = softbusConnector->GetPkgName(); + auto ret = softbusConnector->GetProcessInfo(); EXPECT_EQ(ret.empty(), true); } @@ -891,11 +899,11 @@ HWTEST_F(SoftbusConnectorTest, GetPkgName_001, testing::ext::TestSize.Level0) * @tc.name: ClearPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, ClearPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, ClearProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->ClearPkgName(); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + softbusConnector->ClearProcessInfo(); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -909,7 +917,7 @@ HWTEST_F(SoftbusConnectorTest, HandleDeviceOnline_001, testing::ext::TestSize.Le std::shared_ptr callback = std::make_shared(); softbusConnector->RegisterSoftbusStateCallback(callback); softbusConnector->HandleDeviceOnline(deviceId, DmAuthForm::ACROSS_ACCOUNT); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -923,7 +931,7 @@ HWTEST_F(SoftbusConnectorTest, HandleDeviceOffline_001, testing::ext::TestSize.L std::shared_ptr callback = std::make_shared(); softbusConnector->RegisterSoftbusStateCallback(callback); softbusConnector->HandleDeviceOffline(deviceId); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -935,7 +943,7 @@ HWTEST_F(SoftbusConnectorTest, CheckIsOnline_001, testing::ext::TestSize.Level0) std::string targetDeviceId = "targetDeviceId"; std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->CheckIsOnline(targetDeviceId); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -963,7 +971,7 @@ HWTEST_F(SoftbusConnectorTest, ConvertNodeBasicInfoToDmDevice_001, testing::ext: DmDeviceInfo dmDeviceInfo; std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->ConvertNodeBasicInfoToDmDevice(nodeBasicInfo, dmDeviceInfo); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } } // namespace } // namespace DistributedHardware diff --git a/test/softbusunittest/UTTest_softbus_connector.h b/test/softbusunittest/UTTest_softbus_connector.h index 721ba4a718d73da3aa5846d19d71f3c3fa9e5c0f..e0c48f24b900c7db6a2985e3c69bde4ba1173815 100644 --- a/test/softbusunittest/UTTest_softbus_connector.h +++ b/test/softbusunittest/UTTest_softbus_connector.h @@ -44,6 +44,7 @@ public: static void TearDownTestCase(); void SetUp() override; void TearDown() override; + bool CheckReturnResult(int ret); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index e24d744cddda0f4294892103a96363e07f4a5872..783bc036255c6d3f52f4633286f975466451c354 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -48,6 +48,12 @@ void SoftbusListenerTest::TearDownTestCase() namespace { std::shared_ptr softbusListener = std::make_shared(); +bool checkSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || + ret == SOFTBUS_IPC_ERR; +} + /** * @tc.name: ConvertNodeBasicInfoToDmDevice_001 * @tc.desc: go to the correct case and return DM_OK @@ -112,7 +118,44 @@ HWTEST_F(SoftbusListenerTest, ShiftLNNGear_001, testing::ext::TestSize.Level0) if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_NE(softbusListener->ShiftLNNGear(false), DM_OK); + NodeBasicInfo *info = nullptr; + softbusListener->OnSoftbusDeviceOnline(info); + std::string callerId = "callerId"; + EXPECT_NE(softbusListener->ShiftLNNGear(false, callerId), DM_OK); +} + +HWTEST_F(SoftbusListenerTest, ShiftLNNGear_002, testing::ext::TestSize.Level0) +{ + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + std::string callerId; + EXPECT_EQ(softbusListener->ShiftLNNGear(false, callerId), ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(SoftbusListenerTest, ConvertScreenStatusToDmDevice_001, testing::ext::TestSize.Level0) +{ + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + NodeBasicInfo nodeInfo = { + .networkId = "123456", + .deviceName = "123456", + .deviceTypeId = 1 + }; + int32_t devScreenStatus = 1; + DmDeviceInfo devInfo = { + .deviceId = {"45688"}, + .deviceName = {"device_001"}, + .deviceTypeId = 12, + .extraData = "dsasweadwe65164654", + .networkId = {"8885665"}, + .networkType = 21, + .range = 2, + .authForm = DmAuthForm::ACROSS_ACCOUNT + }; + int ret = softbusListener->ConvertScreenStatusToDmDevice(nodeInfo, devScreenStatus, devInfo); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(SoftbusListenerTest, DeviceOnLine_001, testing::ext::TestSize.Level0) @@ -219,7 +262,7 @@ HWTEST_F(SoftbusListenerTest, PublishSoftbusLNN_001, testing::ext::TestSize.Leve softbusListener = std::make_shared(); } int32_t ret = softbusListener->PublishSoftbusLNN(dmPubInfo, capability, customData); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, StopPublishSoftbusLNN_001, testing::ext::TestSize.Level0) @@ -229,7 +272,7 @@ HWTEST_F(SoftbusListenerTest, StopPublishSoftbusLNN_001, testing::ext::TestSize. softbusListener = std::make_shared(); } int32_t ret = softbusListener->StopPublishSoftbusLNN(publishId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, RegisterSoftbusLnnOpsCbk_001, testing::ext::TestSize.Level0) @@ -272,7 +315,7 @@ HWTEST_F(SoftbusListenerTest, GetUdidByNetworkId_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetUdidByNetworkId(networkId.c_str(), udid); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, GetUuidByNetworkId_001, testing::ext::TestSize.Level0) @@ -283,7 +326,7 @@ HWTEST_F(SoftbusListenerTest, GetUuidByNetworkId_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetUuidByNetworkId(networkId.c_str(), udid); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_001, testing::ext::TestSize.Level0) @@ -297,6 +340,131 @@ HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_001, testing::ext::Tes EXPECT_EQ(softbusListener->isRadarSoLoad_, true); } +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_ETH, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_003, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BR, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_004, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_MAX, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_005, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_006, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BLE, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + HWTEST_F(SoftbusListenerTest, GetNetworkTypeByNetworkId_001, testing::ext::TestSize.Level0) { char *networkId; @@ -346,6 +514,161 @@ HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); } +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_002"; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + PeerTargetId targetId; + ConnectionAddrType addrType; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_003, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_003"; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + }; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_004, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_004"; + PeerTargetId targetId; + ConnectionAddrType addrType = ConnectionAddrType::CONNECTION_ADDR_ETH; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_ETH, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + }; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + softbusListener->CacheDeviceInfo(deviceId, infoPtr); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_005, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_005"; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BR, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + }; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_006, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_006"; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BLE, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + }; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_007, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_007"; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::vector>> deviceVec; + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); +} + HWTEST_F(SoftbusListenerTest, ClearDiscoveredDevice_001, testing::ext::TestSize.Level0) { if (softbusListener == nullptr) { @@ -391,7 +714,7 @@ HWTEST_F(SoftbusListenerTest, OnSessionClosed_001, testing::ext::TestSize.Level0 if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, OnBytesReceived_001, testing::ext::TestSize.Level0) @@ -402,7 +725,7 @@ HWTEST_F(SoftbusListenerTest, OnBytesReceived_001, testing::ext::TestSize.Level0 if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, OnPinHolderSessionOpened_001, testing::ext::TestSize.Level0) @@ -422,7 +745,7 @@ HWTEST_F(SoftbusListenerTest, OnPinHolderSessionClosed_001, testing::ext::TestSi if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, OnPinHolderBytesReceived_001, testing::ext::TestSize.Level0) @@ -433,7 +756,7 @@ HWTEST_F(SoftbusListenerTest, OnPinHolderBytesReceived_001, testing::ext::TestSi if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, GetTrustedDeviceList_001, testing::ext::TestSize.Level0) @@ -446,6 +769,18 @@ HWTEST_F(SoftbusListenerTest, GetTrustedDeviceList_001, testing::ext::TestSize.L EXPECT_EQ(ret, DM_OK); } +HWTEST_F(SoftbusListenerTest, GetTrustedDeviceList_002, testing::ext::TestSize.Level0) +{ + std::vector deviceInfoList; + DmDeviceInfo deviceInfo; + deviceInfoList.push_back(deviceInfo); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTrustedDeviceList(deviceInfoList); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(SoftbusListenerTest, GetDeviceInfo_001, testing::ext::TestSize.Level0) { std::string networkId = "networkId"; @@ -454,7 +789,7 @@ HWTEST_F(SoftbusListenerTest, GetDeviceInfo_001, testing::ext::TestSize.Level0) softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetDeviceInfo(networkId, info); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) @@ -464,7 +799,7 @@ HWTEST_F(SoftbusListenerTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetLocalDeviceInfo(info); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, ConvertBytesToUpperCaseHexString_001, testing::ext::TestSize.Level0) @@ -491,11 +826,9 @@ HWTEST_F(SoftbusListenerTest, GetDeviceSecurityLevel_001, testing::ext::TestSize HWTEST_F(SoftbusListenerTest, GetDmRadarHelperObj_001, testing::ext::TestSize.Level0) { - if (softbusListener == nullptr) { - softbusListener = std::make_shared(); - } - auto ret = softbusListener->GetDmRadarHelperObj(); - EXPECT_NE(ret, nullptr); + std::shared_ptr softbusListener_ = std::make_shared(); + auto ret = softbusListener_->GetDmRadarHelperObj(); + EXPECT_EQ(ret, nullptr); } HWTEST_F(SoftbusListenerTest, SetHostPkgName_001, testing::ext::TestSize.Level0) @@ -525,7 +858,7 @@ HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_001, testing::ext::TestSize.Level0 softbusListener = std::make_shared(); } softbusListener->CacheDeviceInfo(deviceId, infoPtr); - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_002, testing::ext::TestSize.Level0) @@ -537,7 +870,7 @@ HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_002, testing::ext::TestSize.Level0 softbusListener = std::make_shared(); } softbusListener->CacheDeviceInfo(deviceId, infoPtr); - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_003, testing::ext::TestSize.Level0) @@ -549,7 +882,7 @@ HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_003, testing::ext::TestSize.Level0 softbusListener = std::make_shared(); } softbusListener->CacheDeviceInfo(deviceId, infoPtr); - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_001, testing::ext::TestSize.Level0) @@ -596,6 +929,35 @@ HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_003, testing::ext::TestSize EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } +HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_004, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId"; + std::string ip = "172.0.0.1"; + ConnectionAddrType addrType = ConnectionAddrType::CONNECTION_ADDR_ETH; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + }; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetIPAddrTypeFromCache(deviceId, ip, addrType); + softbusListener->CacheDeviceInfo(deviceId, infoPtr); + EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); +} + HWTEST_F(SoftbusListenerTest, InitSoftbusListener_001, testing::ext::TestSize.Level0) { SoftbusListener::GetSoftbusRefreshCb(); @@ -614,8 +976,29 @@ HWTEST_F(SoftbusListenerTest, RefreshSoftbusLNN_001, testing::ext::TestSize.Leve if (softbusListener == nullptr) { softbusListener = std::make_shared(); } + NodeStatusType type = NodeStatusType::TYPE_SCREEN_STATUS; + NodeStatus *status = nullptr; + softbusListener->OnDeviceScreenStatusChanged(type, status); + NodeBasicInfo nodeBasicInfo = { + .deviceName = {"device_001"}, + .networkId = {"network_001"}, + .deviceTypeId = 16789, + .osType = 24, + .osVersion = {1} + }; + NodeStatus nodeStatus = { + .authStatus = 0, + .dataBaseStatus = 1, + .meshType = 2, + .reserved = {1}, + .basicInfo = nodeBasicInfo + }; + status = &nodeStatus; + softbusListener->OnDeviceScreenStatusChanged(type, status); + type = NodeStatusType::TYPE_AUTH_STATUS; + softbusListener->OnDeviceScreenStatusChanged(type, status); int32_t ret = softbusListener->RefreshSoftbusLNN(pkgName.c_str(), dmSubInfo, customData); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize.Level0) @@ -625,7 +1008,90 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener = std::make_shared(); } int32_t ret = softbusListener->StopRefreshSoftbusLNN(subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + softbusListener->OnLocalDevInfoChange(); + std::string msg = "123"; + softbusListener->DeviceNotTrust(msg); + NodeBasicInfo *info = nullptr; + softbusListener->OnSoftbusDeviceOffline(info); + TrustChangeType type = TrustChangeType::DEVICE_NOT_TRUSTED; + const uint32_t msgLen = 100; + char msg1[msgLen] = {0}; + softbusListener->OnDeviceTrustedChange(type, msg1, msgLen); + char *msg2 = nullptr; + softbusListener->OnDeviceTrustedChange(type, msg2, msgLen); + const uint32_t msgLen2 = MAX_SOFTBUS_MSG_LEN + 1; + softbusListener->OnDeviceTrustedChange(type, msg1, msgLen2); + softbusListener->OnDeviceTrustedChange(type, msg2, msgLen2); + softbusListener->SendAclChangedBroadcast(msg); + char devicelist[msgLen] = {0}; + uint16_t deviceTypeId = 0; + int32_t errcode = -1; + softbusListener->OnCredentialAuthStatus(devicelist, msgLen, deviceTypeId, errcode); + std::string deviceList2; + deviceTypeId = 0xA2F; + softbusListener->CredentialAuthStatusProcess(deviceList2, deviceTypeId, errcode); + EXPECT_EQ(true, checkSoftbusRes(ret)); +} + +HWTEST_F(SoftbusListenerTest, GetNetworkIdByUdid_001, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkId"; + std::string udid; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetNetworkIdByUdid(udid, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(SoftbusListenerTest, SetLocalDeviceName_001, testing::ext::TestSize.Level0) +{ + std::string localDeviceName; + std::string localDisplayName; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, DM_OK); + + localDeviceName = "localDeviceName"; + ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, DM_OK); + + localDisplayName = "localDisplayName"; + ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, DM_OK); + softbusListener = nullptr; +} + +HWTEST_F(SoftbusListenerTest, GetDeviceScreenStatus_001, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkId"; + int32_t screenStatus = 1; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetDeviceScreenStatus(networkId.c_str(), screenStatus); + EXPECT_TRUE(checkSoftbusRes(ret)); + softbusListener = nullptr; +} + +HWTEST_F(SoftbusListenerTest, SetForegroundUserIdsToDSoftBus_001, testing::ext::TestSize.Level0) +{ + std::string remoteUdid = "remoteUdid"; + std::vector userIds; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->SetForegroundUserIdsToDSoftBus(remoteUdid, userIds); + EXPECT_EQ(ret, DM_OK); + + const uint32_t deviceListLen = 2001; + char devicelist[deviceListLen] = {0}; + uint16_t deviceTypeId = 0; + int32_t errcode = -1; + softbusListener->OnCredentialAuthStatus(devicelist, deviceListLen, deviceTypeId, errcode); + softbusListener = nullptr; } } // namespace } // namespace DistributedHardware diff --git a/test/softbusunittest/UTTest_softbus_listener.h b/test/softbusunittest/UTTest_softbus_listener.h index 5f738fbeeefc6bc3045b1de6bc8e82383ee2e8db..f840ea9e72dd0cd545c7792a3d84389d34eda227 100644 --- a/test/softbusunittest/UTTest_softbus_listener.h +++ b/test/softbusunittest/UTTest_softbus_listener.h @@ -23,7 +23,6 @@ #include #include -#include "softbus_adapter.h" #include "softbus_bus_center.h" #include "softbus_listener.h" #include "dm_device_info.h" diff --git a/test/softbusunittest/UTTest_softbus_publish.cpp b/test/softbusunittest/UTTest_softbus_publish.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1237fe0e7723976c6b11d01d8fa519431c1ca68e --- /dev/null +++ b/test/softbusunittest/UTTest_softbus_publish.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_softbus_publish.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" +#include "softbus_connector.h" +#include "softbus_error_code.h" + +namespace OHOS { +namespace DistributedHardware { +void SoftbusPublishTest::SetUp() +{ +} +void SoftbusPublishTest::TearDown() +{ +} +void SoftbusPublishTest::SetUpTestCase() +{ +} +void SoftbusPublishTest::TearDownTestCase() +{ +} + +namespace { +HWTEST_F(SoftbusPublishTest, PublishSoftbusLNN_001, testing::ext::TestSize.Level0) +{ + SoftbusPublish spftbusPublish; + int32_t ret = spftbusPublish.PublishSoftbusLNN(); + int publishId = 1; + SoftbusPublish::OnSoftbusPublishResult(publishId, PUBLISH_LNN_SUCCESS); + EXPECT_EQ(ret, ERR_DM_PUBLISH_FAILED); +} + +HWTEST_F(SoftbusPublishTest, StopPublishSoftbusLNN_001, testing::ext::TestSize.Level0) +{ + SoftbusPublish spftbusPublish; + int publishId = 2; + int32_t ret = spftbusPublish.StopPublishSoftbusLNN(publishId); + EXPECT_EQ(ret, ERR_DM_STOP_PUBLISH_LNN_FAILED); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/softbusunittest/UTTest_softbus_adapter.h b/test/softbusunittest/UTTest_softbus_publish.h similarity index 88% rename from test/softbusunittest/UTTest_softbus_adapter.h rename to test/softbusunittest/UTTest_softbus_publish.h index 5d76e80248bedd730ffccc6051b269073604fbc4..981cfe371bb3711bc158c30661bf62c884163725 100644 --- a/test/softbusunittest/UTTest_softbus_adapter.h +++ b/test/softbusunittest/UTTest_softbus_publish.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_UTTEST_DM_SOFTBUS_ADAPTER_H -#define OHOS_UTTEST_DM_SOFTBUS_ADAPTER_H +#ifndef OHOS_UTTEST_DM_SOFTBUS_PUBLISH_H +#define OHOS_UTTEST_DM_SOFTBUS_PUBLISH_H #include #include @@ -30,11 +30,11 @@ #include "dm_device_state_manager.h" #include "dm_discovery_manager.h" #include "inner_session.h" -#include "softbus_adapter.h" +#include "softbus_publish.h" namespace OHOS { namespace DistributedHardware { -class SoftbusAdapterTest : public testing::Test { +class SoftbusPublishTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index 08f2b0df3bf8ebf4ac1b6be6db774bfabe0412f2..0bee605408e3af77b704011fcd52d3e54292ced8 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -107,7 +107,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) nlohmann::json jsonObj; jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = msgType; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); int32_t sessionId = 0; if (softbusSession == nullptr) { softbusSession = std::make_shared(); @@ -179,21 +179,6 @@ HWTEST_F(SoftbusSessionTest, CloseAuthSession_001, testing::ext::TestSize.Level0 EXPECT_EQ(ret, DM_OK); } -/** - * @tc.name: CloseUnbindSession_001 - * @tc.desc: set socket = 1, and return DM_OK - * @tc.type: FUNC - */ -HWTEST_F(SoftbusSessionTest, CloseUnbindSession_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - if (softbusSession == nullptr) { - softbusSession = std::make_shared(); - } - int32_t ret = softbusSession->CloseUnbindSession(socket); - EXPECT_EQ(ret, DM_OK); -} - /** * @tc.name: GetPeerDeviceId_001 * @tc.desc: set sessionId = 3 and return DM_OK @@ -259,6 +244,9 @@ HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level0) void *data = nullptr; unsigned int dataLen = 1; softbusSession->OnBytesReceived(sessionId, data, dataLen); + softbusSession->OnBytesReceived(sessionId, data, -1); + sessionId = -1; + softbusSession->OnBytesReceived(sessionId, data, dataLen); int ret = softbusSession->OnSessionOpened(sessionId, result); softbusSession->OnSessionClosed(sessionId); EXPECT_EQ(ret, DM_OK); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 2e217050891bfa2c0c92fde4db8be2c55158084c..176b10184454a006d8101837c22e2dcbad4e7d6e 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -27,25 +27,36 @@ group("unittest") { ":UTTest_device_manager_service", ":UTTest_device_manager_service_impl", ":UTTest_device_manager_service_listener", + ":UTTest_device_manager_service_three", ":UTTest_discovery_filter", ":UTTest_discovery_manager", + ":UTTest_dm_account_common_event", ":UTTest_dm_adapter_manager", ":UTTest_dm_anonymous", ":UTTest_dm_auth_manager_first", ":UTTest_dm_auth_manager_second", + ":UTTest_dm_auth_manager_third", + ":UTTest_dm_comm_tool", ":UTTest_dm_common_event_manager", ":UTTest_dm_credential_manager", + ":UTTest_dm_crypto", ":UTTest_dm_device_state_manager", ":UTTest_dm_deviceprofile_connector", + ":UTTest_dm_deviceprofile_connector_second", ":UTTest_dm_dfx", ":UTTest_dm_discovery_filter", ":UTTest_dm_discovery_manager", ":UTTest_dm_distributed_hardware_load", ":UTTest_dm_import_auth_code", ":UTTest_dm_pin_holder", + ":UTTest_dm_publish_common_event", ":UTTest_dm_publish_manager", ":UTTest_dm_radar_helper_test", + ":UTTest_dm_screen_common_event", + ":UTTest_dm_service_load", ":UTTest_dm_timer", + ":UTTest_dm_transport", + ":UTTest_dm_transport_msg", ":UTTest_hichain_auth_connector", ":UTTest_hichain_connector", ":UTTest_ipc_client_manager", @@ -65,9 +76,10 @@ group("unittest") { ":UTTest_permission_manager", ":UTTest_pin_auth", ":UTTest_pin_auth_ui", - ":UTTest_softbus_adapter", + ":UTTest_relationship_sync_mgr", ":UTTest_softbus_connector", ":UTTest_softbus_listener", + ":UTTest_softbus_publish", ":UTTest_softbus_session", ] } @@ -86,9 +98,14 @@ ohos_unittest("UTTest_pin_auth") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -112,6 +129,8 @@ ohos_unittest("UTTest_pin_auth_ui") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -135,6 +154,7 @@ ohos_unittest("UTTest_ipc_cmd_parser_client") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", + "googletest:gmock", ] cflags = [ @@ -162,10 +182,14 @@ ohos_unittest("UTTest_ipc_cmd_parser_service") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", + "googletest:gmock", "hicollie:libhicollie", ] @@ -191,6 +215,7 @@ ohos_unittest("UTTest_ipc_cmd_register") { external_deps = [ "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -214,6 +239,7 @@ ohos_unittest("UTTest_dm_pin_holder") { "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -226,6 +252,8 @@ ohos_unittest("UTTest_ipc_get_device_info_rsp") { sources = [ "UTTest_ipc_get_device_info_rsp.cpp" ] deps = [ ":device_manager_test_common" ] + + external_deps = [ "googletest:gmock" ] } ## UnitTest UTTest_ipc_get_device_info_rsp }}} @@ -240,7 +268,10 @@ ohos_unittest("UTTest_dm_common_event_manager") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_common_event_manager }}} @@ -253,16 +284,28 @@ ohos_unittest("device_manager_impl_test") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest device_manager_impl_test }}} ## UnitTest UTTest_dm_credential_manager {{{ ohos_unittest("UTTest_dm_credential_manager") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_out_path - include_dirs = [ "${devicemanager_path}/test/commonunittest" ] + include_dirs = [ + "${devicemanager_path}/test/commonunittest", + "${servicesimpl_path}/src/credential", + ] sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_credential_manager.cpp" ] @@ -273,6 +316,8 @@ ohos_unittest("UTTest_dm_credential_manager") { "access_token:libnativetoken", "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -282,7 +327,17 @@ ohos_unittest("UTTest_dm_credential_manager") { ohos_unittest("UTTest_device_manager_service") { module_out_path = module_out_path - sources = [ "UTTest_device_manager_service.cpp" ] + sources = [ + "UTTest_device_manager_service.cpp", + "UTTest_device_manager_service_two.cpp", + "mock/app_manager_mock.cpp", + "mock/device_manager_service_impl_mock.cpp", + "mock/dm_crypto_mock.cpp", + "mock/dm_softbus_cache_mock.cpp", + "mock/kv_adapter_manager_mock.cpp", + "mock/permission_manager_mock.cpp", + "mock/softbus_listener_mock.cpp", + ] deps = [ ":device_manager_test_common" ] @@ -290,14 +345,48 @@ ohos_unittest("UTTest_device_manager_service") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", ] } ## UnitTest UTTest_device_manager_service }}} +## UnitTest UTTest_device_manager_service_three {{{ +ohos_unittest("UTTest_device_manager_service_three") { + module_out_path = module_out_path + + sources = [ + "UTTest_device_manager_service_three.cpp", + "mock/device_manager_service_impl_mock.cpp", + "mock/device_manager_service_mock.cpp", + "mock/permission_manager_mock.cpp", + "mock/softbus_listener_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "cJSON:cjson", + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", + ] +} + +## UnitTest UTTest_device_manager_service_three }}} + ## UnitTest UTTest_hichain_auth_connector {{{ ohos_unittest("UTTest_hichain_auth_connector") { module_out_path = module_out_path @@ -312,6 +401,8 @@ ohos_unittest("UTTest_hichain_auth_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -333,6 +424,8 @@ ohos_unittest("UTTest_hichain_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -352,6 +445,7 @@ ohos_unittest("UTTest_mine_hichain_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -380,6 +474,8 @@ ohos_unittest("UTTest_mine_softbus_listener") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", "openssl:libcrypto_shared", @@ -388,55 +484,65 @@ ohos_unittest("UTTest_mine_softbus_listener") { ## UnitTest UTTest_mine_softbus_listener }}} -## UnitTest UTTest_softbus_adapter {{{ -ohos_unittest("UTTest_softbus_adapter") { +## UnitTest UTTest_softbus_connector {{{ +ohos_unittest("UTTest_softbus_connector") { module_out_path = module_out_path include_dirs = [ "${devicemanager_path}/test/softbusunittest" ] sources = [ - "${devicemanager_path}/test/softbusunittest/UTTest_softbus_adapter.cpp", + "${devicemanager_path}/test/softbusunittest/UTTest_softbus_connector.cpp", ] deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", + "os_account:libaccountkits", ] } -## UnitTest UTTest_softbus_adapter }}} +## UnitTest UTTest_softbus_connector }}} -## UnitTest UTTest_softbus_connector {{{ -ohos_unittest("UTTest_softbus_connector") { +## UnitTest UTTest_softbus_listener {{{ +ohos_unittest("UTTest_softbus_listener") { module_out_path = module_out_path - include_dirs = [ "${devicemanager_path}/test/softbusunittest" ] + include_dirs = [ + "${devicemanager_path}/test/softbusunittest", + "${services_path}/src/softbus", + ] sources = [ - "${devicemanager_path}/test/softbusunittest/UTTest_softbus_connector.cpp", + "${devicemanager_path}/test/softbusunittest/UTTest_softbus_listener.cpp", + "${devicemanager_path}/test/unittest/mock/parameter.cpp", ] deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", - "os_account:libaccountkits", ] } -## UnitTest UTTest_softbus_connector }}} +## UnitTest UTTest_softbus_listener }}} -## UnitTest UTTest_softbus_listener {{{ -ohos_unittest("UTTest_softbus_listener") { +## UnitTest UTTest_softbus_publish {{{ +ohos_unittest("UTTest_softbus_publish") { module_out_path = module_out_path include_dirs = [ @@ -445,7 +551,7 @@ ohos_unittest("UTTest_softbus_listener") { ] sources = [ - "${devicemanager_path}/test/softbusunittest/UTTest_softbus_listener.cpp", + "${devicemanager_path}/test/softbusunittest/UTTest_softbus_publish.cpp", "${devicemanager_path}/test/unittest/mock/parameter.cpp", ] @@ -455,12 +561,14 @@ ohos_unittest("UTTest_softbus_listener") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] } -## UnitTest UTTest_softbus_listener }}} +## UnitTest UTTest_softbus_publish }}} ## UnitTest UTTest_softbus_session {{{ ohos_unittest("UTTest_softbus_session") { @@ -478,6 +586,8 @@ ohos_unittest("UTTest_softbus_session") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -493,7 +603,10 @@ ohos_unittest("UTTest_dm_adapter_manager") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_adapter_manager }}} @@ -512,7 +625,10 @@ ohos_unittest("UTTest_dm_anonymous") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_anonymous }}} @@ -527,11 +643,55 @@ ohos_unittest("UTTest_dm_timer") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_timer }}} +## UnitTest UTTest_dm_transport {{{ +ohos_unittest("UTTest_dm_transport") { + module_out_path = module_out_path + include_dirs = [ "${devicemanager_path}/test/unittest" ] + sources = [ "${devicemanager_path}/test/unittest/UTTest_dm_transport.cpp" ] + deps = [ ":device_manager_test_common" ] + external_deps = [ + "cJSON:cjson", + "googletest:gmock", + ] +} + +## UnitTest UTTest_dm_transport }}} + +## UnitTest UTTest_dm_transport_msg {{{ +ohos_unittest("UTTest_dm_transport_msg") { + module_out_path = module_out_path + include_dirs = [ "${devicemanager_path}/test/unittest" ] + sources = + [ "${devicemanager_path}/test/unittest/UTTest_dm_transport_msg.cpp" ] + deps = [ ":device_manager_test_common" ] + external_deps = [ + "cJSON:cjson", + "googletest:gmock", + ] +} + +## UnitTest UTTest_dm_transport_msg }}} + +## UnitTest UTTest_dm_service_load {{{ +ohos_unittest("UTTest_dm_service_load") { + module_out_path = module_out_path + + sources = [ "UTTest_dm_service_load.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_dm_service_load }}} + ## UnitTest UTTest_ipc_client_manager {{{ ohos_unittest("UTTest_ipc_client_manager") { module_out_path = module_out_path @@ -543,6 +703,7 @@ ohos_unittest("UTTest_ipc_client_manager") { external_deps = [ "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -556,7 +717,10 @@ ohos_unittest("UTTest_ipc_client_proxy") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_ipc_client_proxy }}} @@ -565,11 +729,18 @@ ohos_unittest("UTTest_ipc_client_proxy") { ohos_unittest("UTTest_ipc_client_stub") { module_out_path = module_out_path - sources = [ "UTTest_ipc_client_stub.cpp" ] + sources = [ + "UTTest_ipc_client_stub.cpp", + "mock/ipc_cmd_register_mock.cpp", + ] deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + "googletest:gmock_main", + ] } ## UnitTest UTTest_ipc_client_stub }}} @@ -586,9 +757,14 @@ ohos_unittest("UTTest_ipc_server_client_proxy") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hicollie:libhicollie", ] } @@ -603,7 +779,13 @@ ohos_unittest("UTTest_ipc_server_listener") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_ipc_server_listener }}} @@ -617,9 +799,14 @@ ohos_unittest("UTTest_ipc_server_stub") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -643,6 +830,15 @@ ohos_unittest("UTTest_device_manager_impl") { "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", + ] + + cflags = [ + "-Wall", + "-Werror", + "-g3", + "-Dprivate=public", + "-Dprotected=public", ] } @@ -662,6 +858,7 @@ ohos_unittest("UTTest_dm_import_auth_code") { "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -682,6 +879,7 @@ ohos_unittest("UTTest_multiple_user_connector") { external_deps = [ "device_auth:deviceauth_sdk", + "googletest:gmock", "os_account:libaccountkits", "os_account:os_account_innerkits", ] @@ -706,6 +904,7 @@ ohos_unittest("UTTest_permission_manager") { "access_token:libnativetoken", "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", + "googletest:gmock", ] } @@ -726,6 +925,7 @@ ohos_unittest("UTTest_device_manager_notify") { external_deps = [ "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -739,7 +939,10 @@ ohos_unittest("UTTest_ipc_client_server_proxy") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_ipc_client_server_proxy }}} @@ -756,6 +959,8 @@ ohos_unittest("UTTest_dm_device_state_manager") { external_deps = [ "device_auth:deviceauth_sdk", + "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -775,6 +980,7 @@ ohos_unittest("UTTest_dm_dfx") { external_deps = [ "device_auth:deviceauth_sdk", + "googletest:gmock", "hitrace:hitrace_meter", ] } @@ -797,6 +1003,7 @@ ohos_unittest("UTTest_dm_discovery_filter") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -810,6 +1017,10 @@ ohos_unittest("UTTest_device_manager_service_impl") { "${devicemanager_path}/commondependency/src/multiple_user_connector.cpp", "${servicesimpl_path}/src/device_manager_service_impl.cpp", "UTTest_device_manager_service_impl.cpp", + "mock/deviceprofile_connector_mock.cpp", + "mock/dm_device_state_manager_mock.cpp", + "mock/mine_hichain_connector_mock.cpp", + "mock/softbus_connector_mock.cpp", ] deps = [ ":device_manager_test_common" ] @@ -818,6 +1029,9 @@ ohos_unittest("UTTest_device_manager_service_impl") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", "os_account:libaccountkits", "os_account:os_account_innerkits", ] @@ -837,6 +1051,7 @@ ohos_unittest("UTTest_device_manager_service_listener") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -854,6 +1069,8 @@ ohos_unittest("UTTest_auth_message_processor") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -871,6 +1088,8 @@ ohos_unittest("UTTest_auth_response_state") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -888,6 +1107,8 @@ ohos_unittest("UTTest_auth_request_state") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", ] } @@ -901,7 +1122,10 @@ ohos_unittest("ipc_client_manager_test") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest ipc_client_manager_test }}} @@ -912,7 +1136,11 @@ ohos_unittest("UTTest_dm_auth_manager_first") { include_dirs = [ "${devicemanager_path}/test/commonunittest" ] - sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_first.cpp" ] + sources = [ + "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_first.cpp", + "mock/app_manager_mock.cpp", + "mock/softbus_session_mock.cpp", + ] deps = [ ":device_manager_test_common" ] @@ -920,6 +1148,18 @@ ohos_unittest("UTTest_dm_auth_manager_first") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", ] } @@ -931,19 +1171,60 @@ ohos_unittest("UTTest_dm_auth_manager_second") { include_dirs = [ "${devicemanager_path}/test/commonunittest" ] - sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_second.cpp" ] + sources = [ + "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_second.cpp", + "mock/hichain_auth_connector_mock.cpp", + "mock/hichain_connector_mock.cpp", + "mock/multiple_user_connector_mock.cpp", + "mock/softbus_connector_mock.cpp", + ] deps = [ ":device_manager_test_common" ] external_deps = [ + "ability_runtime:ability_connect_callback_stub", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", ] } ## UTTest_dm_auth_manager_second }}} +## UnitTest UTTest_dm_auth_manager_third {{{ +ohos_unittest("UTTest_dm_auth_manager_third") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/commonunittest" ] + + sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_third.cpp" ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "ability_runtime:ability_connect_callback_stub", + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] +} + +## UTTest_dm_auth_manager_third }}} + ############################### ## UnitTest UTTest_dm_radar_helper_test {{{ ohos_unittest("UTTest_dm_radar_helper_test") { @@ -959,7 +1240,10 @@ ohos_unittest("UTTest_dm_radar_helper_test") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UTTest_dm_radar_helper_test }}} @@ -977,9 +1261,12 @@ ohos_unittest("UTTest_discovery_filter") { deps = [ ":device_manager_test_common" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -1001,6 +1288,8 @@ ohos_unittest("UTTest_discovery_manager") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hitrace:hitrace_meter", ] } @@ -1019,7 +1308,9 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp", + "${devicemanager_path}/test/unittest/mock/dm_crypto_mock.cpp", "${devicemanager_path}/test/unittest/mock/mock_distributed_device_profile_client.cpp", + "${devicemanager_path}/test/unittest/mock/multiple_user_connector_mock.cpp", ] deps = [ ":device_manager_test_common" ] @@ -1027,11 +1318,42 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { external_deps = [ "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", ] } ## UTTest_dm_deviceprofile_connector }}} +############################### +## UnitTest UTTest_dm_deviceprofile_connector_second {{{ +ohos_unittest("UTTest_dm_deviceprofile_connector_second") { + module_out_path = module_out_path + + include_dirs = [ + "${devicemanager_path}/commondependency/include", + "${devicemanager_path}/test/commonunittest", + ] + + sources = [ + "${devicemanager_path}/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp", + "${devicemanager_path}/test/unittest/mock/distributed_device_profile_client_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", + ] +} + +## UTTest_dm_deviceprofile_connector_second }}} + ############################# ## UnitTest UTTest_dm_discovery_manager {{{ @@ -1050,6 +1372,8 @@ ohos_unittest("UTTest_dm_discovery_manager") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hitrace:hitrace_meter", ] } @@ -1070,12 +1394,115 @@ ohos_unittest("UTTest_dm_distributed_hardware_load") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hitrace:hitrace_meter", ] } ## UnitTest UTTest_dm_distributed_hardware_load }}} +## UnitTest UTTest_dm_comm_tool {{{ +ohos_unittest("UTTest_dm_comm_tool") { + module_out_path = module_out_path + include_dirs = [ "${devicemanager_path}/test/unittest" ] + sources = [ "${devicemanager_path}/test/unittest/UTTest_dm_comm_tool.cpp" ] + deps = [ ":device_manager_test_common" ] + external_deps = [ + "cJSON:cjson", + "googletest:gmock", + ] +} + +## UnitTest UTTest_dm_comm_tool }}} + +## UnitTest UTTest_dm_crypto {{{ +ohos_unittest("UTTest_dm_crypto") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ "${devicemanager_path}/test/unittest/UTTest_dm_crypto.cpp" ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ "googletest:gmock" ] +} + +## UnitTest UTTest_dm_crypto }}} + +## UnitTest UTTest_dm_account_common_event {{{ +ohos_unittest("UTTest_dm_account_common_event") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_dm_account_common_event.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [] +} + +## UnitTest UTTest_dm_account_common_event }}} + +## UnitTest UTTest_dm_publish_common_event {{{ +ohos_unittest("UTTest_dm_publish_common_event") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_dm_publish_common_event.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "bluetooth:btframework", + "wifi:wifi_sdk", + ] +} + +## UnitTest UTTest_dm_publish_common_event }}} + +## UnitTest UTTest_dm_screen_common_event {{{ +ohos_unittest("UTTest_dm_screen_common_event") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_dm_screen_common_event.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "bluetooth:btframework", + "wifi:wifi_sdk", + ] +} + +## UnitTest UTTest_dm_screen_common_event }}} + +## UnitTest UTTest_relationship_sync_mgr {{{ +ohos_unittest("UTTest_relationship_sync_mgr") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = + [ "${devicemanager_path}/test/unittest/UTTest_relationship_sync_mgr.cpp" ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ "cJSON:cjson" ] +} + +## UnitTest UTTest_relationship_sync_mgr }}} + ## UnitTest UTTest_dm_publish_manager {{{ ohos_unittest("UTTest_dm_publish_manager") { module_out_path = module_out_path @@ -1098,9 +1525,14 @@ ohos_unittest("UTTest_dm_publish_manager") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", "hitrace:hitrace_meter", ] @@ -1148,14 +1580,6 @@ config("device_manager_test_common_public_config") { "${devicemanager_path}/test/unittest/mock/", ] - if (os_account_part_exists) { - include_dirs += [ - "${os_account_path }/interfaces/innerkits/osaccount/native/include", - "${os_account_path }/frameworks/common/database/include", - "${os_account_path }/frameworks/common/account_error/include", - ] - } - cflags = [ "-Wall", "-Werror", @@ -1196,7 +1620,6 @@ ohos_static_library("device_manager_test_common") { "${servicesimpl_path}:devicemanagerserviceimpl", "${softbuscache_parh}:dmdevicecache", "${utils_path}:devicemanagerutils", - "//third_party/googletest:gmock", ] external_deps = [ @@ -1205,13 +1628,17 @@ ohos_static_library("device_manager_test_common") { "access_token:libnativetoken", "access_token:libtoken_setproc", "bundle_framework:appexecfwk_base", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", + "ffrt:libffrt", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index 1bed5dffec46c51ce8a5110f3420a954f84ac9ea..dba95a853330a8e2d032d0ae74b770b6ba304746 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -16,6 +16,7 @@ #include "UTTest_auth_message_processor.h" #include "dm_log.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "auth_message_processor.h" #include "softbus_connector.h" @@ -132,7 +133,9 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes authMessageProcessor->SetResponseContext(authResponseContext); authMessageProcessor->cryptoAdapter_ = nullptr; authMessageProcessor->CreateNegotiateMessage(jsonObj); - std::string str1 = jsonObj.dump(); + std::string str1 = SafetyDump(jsonObj); + authMessageProcessor->cryptoAdapter_ = std::make_shared(); + authMessageProcessor->CreateNegotiateMessage(jsonObj); nlohmann::json jsonObject; jsonObject[TAG_ACCOUNT_GROUPID] = ""; @@ -143,7 +146,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes jsonObject[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsonObject[TAG_LOCAL_DEVICE_ID] = authMessageProcessor->authResponseContext_->localDeviceId; jsonObject[TAG_HOST] = ""; - std::string str2 = jsonObject.dump(); + std::string str2 = SafetyDump(jsonObject); ASSERT_NE(str1, str2); } @@ -169,8 +172,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateSyncGroupMessage_001, testing::ext::Tes jsona[TAG_DEVICE_ID] = authMessageProcessor->authRequestContext_->deviceId; jsona[TAG_GROUPIDS] = authMessageProcessor->authRequestContext_->syncGroupList; authMessageProcessor->CreateSyncGroupMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -194,7 +197,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: authMessageProcessor->authResponseContext_->token = "11"; nlohmann::json jsonb; jsonb[TAG_GROUP_ID] = "123456"; - authMessageProcessor->authResponseContext_->groupId = jsonb.dump(); + authMessageProcessor->authResponseContext_->groupId = + SafetyDump(jsonb); authMessageProcessor->authResponseContext_->authToken = "123456"; authMessageProcessor->authResponseContext_->networkId = "11112222"; authMessageProcessor->authResponseContext_->requestId = 222222; @@ -208,8 +212,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: jsona[TAG_GROUP_ID] = "123456"; jsona[TAG_GROUP_NAME] = authMessageProcessor->authResponseContext_->groupName; authMessageProcessor->CreateResponseAuthMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -232,8 +236,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseFinishMessage_001, testing::ext jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsona[TAG_AUTH_FINISH] = authMessageProcessor->authResponseContext_->isFinish; authMessageProcessor->CreateResponseFinishMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -274,6 +278,7 @@ HWTEST_F(AuthMessageProcessorTest, ParseResponseFinishMessage_002, testing::ext: authMessageProcessor->authResponseContext_ = std::make_shared(); nlohmann::json jsonObj; jsonObj[TAG_REPLY] = 22; + jsonObj[TAG_AUTH_FINISH] = true; authMessageProcessor->ParseResponseFinishMessage(jsonObj); ASSERT_EQ(authMessageProcessor->authResponseContext_->reply, jsonObj[TAG_REPLY]); } @@ -607,6 +612,22 @@ HWTEST_F(AuthMessageProcessorTest, ParseAuthRequestMessage_002, testing::ext::Te jsonThumbnail[TAG_DEVICE_TYPE] = 1; int32_t ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_INDEX] = 1; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_SLICE_NUM] = 10; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_SLICE_NUM] = 1; + jsonThumbnail[TAG_IS_SHOW_DIALOG] = true; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_BIND_TYPE_SIZE] = 10001; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, ERR_DM_FAILED); + jsonThumbnail[TAG_BIND_TYPE_SIZE] = 1; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); } /** @@ -807,6 +828,42 @@ HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_005, testing::ext::Test ASSERT_EQ(authMessageProcessor->authResponseContext_, authResponseContext); } +/** + * @tc.name: AuthMessageProcessor::ParseNegotiateMessage_006 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_006, testing::ext::TestSize.Level0) +{ + std::shared_ptr hiChainConnector_ = std::make_shared(); + std::shared_ptr data = + std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); + std::shared_ptr authMessageProcessor = std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObj; + authResponseContext->localDeviceId = "22"; + authResponseContext->authType = 1; + authResponseContext->reply = 33; + jsonObj[TAG_LOCAL_DEVICE_ID] = "LOCALDEVICEID"; + jsonObj[TAG_LOCAL_DEVICE_ID] = authResponseContext->localDeviceId; + jsonObj[TAG_AUTH_TYPE] = authResponseContext->authType; + jsonObj[TAG_LOCAL_DEVICE_ID] = authResponseContext->localDeviceId; + jsonObj[TAG_REPLY] = authResponseContext->reply; + jsonObj[TAG_CRYPTO_SUPPORT] = true; + jsonObj[TAG_CRYPTO_NAME] = "NAMETEST"; + jsonObj[TAG_CRYPTO_VERSION] = "1.0"; + jsonObj[TAG_ACCOUNT_GROUPID] = "GROUPID"; + authMessageProcessor->ParseNegotiateMessage(jsonObj); + jsonObj[TAG_ACCOUNT_GROUPID] = 12; + jsonObj[TAG_HOST] = "12"; + jsonObj[TAG_AUTH_TYPE] = "12"; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseNegotiateMessage(jsonObj); + ASSERT_EQ(authMessageProcessor->authResponseContext_, authResponseContext); +} + /** * @tc.name: AuthMessageProcessor::ParseRespNegotiateMessage_001 * @tc.desc: return true @@ -869,6 +926,7 @@ HWTEST_F(AuthMessageProcessorTest, ParseRespNegotiateMessage_003, testing::ext:: jsonObj[TAG_NET_ID] = "1212"; jsonObj[TAG_TOKENID] = "1212"; jsonObj[TAG_TARGET_DEVICE_NAME] = "1212"; + jsonObj[TAG_IMPORT_AUTH_CODE] = "1212"; authMessageProcessor->ParseRespNegotiateMessage(jsonObj); ASSERT_EQ(authMessageProcessor->authResponseContext_->isIdenticalAccount, true); } @@ -1029,15 +1087,15 @@ HWTEST_F(AuthMessageProcessorTest, CreateSimpleMessage_001, testing::ext::TestSi msgType = MSG_TYPE_REQ_PUBLICKEY; ret = authMessageProcessor->CreateSimpleMessage(msgType); ASSERT_NE(ret.size(), 0); - msgType = MSG_TYPE_REQ_SYNC_DELETE; - ret = authMessageProcessor->CreateSimpleMessage(msgType); - ASSERT_NE(ret.size(), 0); msgType = MSG_TYPE_NEGOTIATE; ret = authMessageProcessor->CreateSimpleMessage(msgType); ASSERT_NE(ret.size(), 0); msgType = MSG_TYPE_RESP_NEGOTIATE; ret = authMessageProcessor->CreateSimpleMessage(msgType); ASSERT_NE(ret.size(), 0); + msgType = MSG_TYPE_UNKNOWN; + ret = authMessageProcessor->CreateSimpleMessage(msgType); + ASSERT_NE(ret.size(), 0); } /** @@ -1272,6 +1330,27 @@ HWTEST_F(AuthMessageProcessorTest, ParseMessage_008, testing::ext::TestSize.Leve } )"; int32_t ret = authMessageProcessor->ParseMessage(message); + std::string message1 = R"( + { + "publicKey": "publicKey_test", + "MSG_TYPE": "503", + } + )"; + ret = authMessageProcessor->ParseMessage(message); + std::string message2 = R"( + { + "publicKey": "publicKey_test", + "MSG_TYPE": "504", + } + )"; + ret = authMessageProcessor->ParseMessage(message2); + std::string message3 = R"( + { + "publicKey": "publicKey_test", + "MSG_TYPE": "600", + } + )"; + ret = authMessageProcessor->ParseMessage(message3); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -1343,20 +1422,6 @@ HWTEST_F(AuthMessageProcessorTest, GetJsonObj_002, testing::ext::TestSize.Level0 ASSERT_EQ(jsonObj[TAG_IS_SHOW_DIALOG], true); } -HWTEST_F(AuthMessageProcessorTest, CreateSyncDeleteMessageExt_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hiChainConnector_ = std::make_shared(); - std::shared_ptr data = - std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); - std::shared_ptr authMessageProcessor = std::make_shared(data); - authMessageProcessor->authResponseContext_ = std::make_shared(); - authMessageProcessor->authResponseContext_->localDeviceId = "13213521"; - authMessageProcessor->authResponseContext_->hostPkgName = "ohos_test"; - nlohmann::json jsonObj; - authMessageProcessor->CreateSyncDeleteMessageExt(jsonObj); - ASSERT_EQ(jsonObj[TAG_REPLY], DM_OK); -} - HWTEST_F(AuthMessageProcessorTest, CreatePublicKeyMessageExt_001, testing::ext::TestSize.Level0) { std::shared_ptr hiChainConnector_ = std::make_shared(); @@ -1412,36 +1477,6 @@ HWTEST_F(AuthMessageProcessorTest, CreateRespNegotiateMessage_002, testing::ext: ASSERT_EQ(jsonObj[TAG_CRYPTO_SUPPORT], true); } -HWTEST_F(AuthMessageProcessorTest, ParseSyncDeleteMessageExt_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hiChainConnector_ = std::make_shared(); - std::shared_ptr data = - std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); - std::shared_ptr authMessageProcessor = std::make_shared(data); - authMessageProcessor->authResponseContext_ = std::make_shared(); - nlohmann::json jsonObj; - jsonObj[TAG_LOCAL_DEVICE_ID] = "12121213"; - jsonObj[TAG_HOST_PKGNAME] = "hostPkgname"; - jsonObj[TAG_REPLY] = 1212; - authMessageProcessor->ParseSyncDeleteMessageExt(jsonObj); - ASSERT_EQ(authMessageProcessor->authResponseContext_->reply, 1212); -} - -HWTEST_F(AuthMessageProcessorTest, ParseSyncDeleteMessageExt_002, testing::ext::TestSize.Level0) -{ - std::shared_ptr hiChainConnector_ = std::make_shared(); - std::shared_ptr data = - std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); - std::shared_ptr authMessageProcessor = std::make_shared(data); - authMessageProcessor->authResponseContext_ = std::make_shared(); - nlohmann::json jsonObj; - jsonObj[TAG_LOCAL_DEVICE_ID] = 2121; - jsonObj[TAG_HOST_PKGNAME] = 1231; - jsonObj[TAG_REPLY] = "1212"; - authMessageProcessor->ParseSyncDeleteMessageExt(jsonObj); - ASSERT_NE(authMessageProcessor->authResponseContext_->reply, 1212); -} - HWTEST_F(AuthMessageProcessorTest, ParsePublicKeyMessageExt_001, testing::ext::TestSize.Level0) { std::shared_ptr hiChainConnector_ = std::make_shared(); @@ -1591,6 +1626,9 @@ HWTEST_F(AuthMessageProcessorTest, ParsePkgNegotiateMessage_002, testing::ext::T jsonObj[TAG_HAVECREDENTIAL] = "1212"; jsonObj[TAG_BIND_TYPE_SIZE] = "1212"; authMessageProcessor->ParsePkgNegotiateMessage(jsonObj); + jsonObj[TAG_BIND_TYPE_SIZE] = 1212; + jsonObj[TAG_HOST_PKGLABEL] = "1212"; + authMessageProcessor->ParsePkgNegotiateMessage(jsonObj); ASSERT_NE(authMessageProcessor->authResponseContext_->authType, 21); } diff --git a/test/unittest/UTTest_auth_request_state.cpp b/test/unittest/UTTest_auth_request_state.cpp index 6057378d2ed33ec2730d3eda8c9315bf74d8c6eb..bfa9d9e1984e9e0103a297cd0aecf1784b3fcd13 100644 --- a/test/unittest/UTTest_auth_request_state.cpp +++ b/test/unittest/UTTest_auth_request_state.cpp @@ -689,90 +689,6 @@ HWTEST_F(AuthRequestStateTest, Enter_010, testing::ext::TestSize.Level0) int32_t ret = authRequestState->Enter(); ASSERT_EQ(ret, ERR_DM_FAILED); } - -/** - * @tc.name: AuthRequestDeleteInit::GetStateType_010 - * @tc.desc: 1 call AuthRequestDeleteInit::GetStateType - * 2 check ret is AUTH_REQUEST_DELETE_INIT - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, GetStateType_010, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret, AUTH_REQUEST_DELETE_INIT); -} - -/** - * @tc.name: AuthRequestDeleteInit::Enter_017 - * @tc.desc: 1 call AuthRequestDeleteInit::Enter - * 2 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, Enter_017, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -/** - * @tc.name: AuthRequestSyncDeleteAcl::GetStateType_011 - * @tc.desc: 1 call AuthRequestSyncDeleteAcl::GetStateType - * 2 check ret is AUTH_REQUEST_SYNCDELETE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, GetStateType_011, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret, AUTH_REQUEST_SYNCDELETE); -} - -/** - * @tc.name: AuthRequestSyncDeleteAcl::Enter_018 - * @tc.desc: 1 call AuthRequestSyncDeleteAcl::Enter - * 2 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, Enter_018, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -/** - * @tc.name: AuthRequestSyncDeleteAclNone::GetStateType_012 - * @tc.desc: 1 call AuthRequestSyncDeleteAclNone::GetStateType - * 2 check ret is AUTH_REQUEST_SYNCDELETE_DONE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, GetStateType_012, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret, AUTH_REQUEST_SYNCDELETE_DONE); -} - -/** - * @tc.name: AuthRequestSyncDeleteAclNone::Enter_019 - * @tc.desc: 1 call AuthRequestSyncDeleteAclNone::Enter - * 2 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, Enter_019, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_auth_response_state.cpp b/test/unittest/UTTest_auth_response_state.cpp index 078a4758720eecd46e9cf8f4574fa09dac7cb185..1a8aa6352231f3f87e1701e3c1ffb916e79babec 100644 --- a/test/unittest/UTTest_auth_response_state.cpp +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -507,72 +507,6 @@ HWTEST_F(AuthResponseStateTest, Enter_012, testing::ext::TestSize.Level0) int32_t ret = authResponseState->Enter(); ASSERT_EQ(ret, ERR_DM_FAILED); } - -/** - * @tc.name: AuthResponseSyncDeleteAcl::GetStateType_011 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAcl::GetStateType with authManager = null - * 3 check ret is AUTH_RESPONSE_SYNCDELETE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, GetStateType_011, testing::ext::TestSize.Level0) -{ - std::shared_ptr authResponseState = std::make_shared(); - int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret, AUTH_RESPONSE_SYNCDELETE); -} - -/** - * @tc.name: AuthResponseSyncDeleteAcl::Enter_013 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAcl::Enter with authManager = null - * 3 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, Enter_013, testing::ext::TestSize.Level0) -{ - std::shared_ptr authManager = - std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); - std::shared_ptr authResponseState = std::make_shared(); - authResponseState->SetAuthManager(nullptr); - int32_t ret = authResponseState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -/** - * @tc.name: AuthResponseSyncDeleteAclNone::GetStateType_012 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAclNone::GetStateType with authManager = null - * 3 check ret is AUTH_RESPONSE_SYNCDELETE_DONE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, GetStateType_012, testing::ext::TestSize.Level0) -{ - std::shared_ptr authResponseState = std::make_shared(); - int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret, AUTH_RESPONSE_SYNCDELETE_DONE); -} - -/** - * @tc.name: AuthResponseSyncDeleteAclNone::Enter_014 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAclNone::Enter with authManager = null - * 3 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, Enter_014, testing::ext::TestSize.Level0) -{ - std::shared_ptr authManager = - std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); - std::shared_ptr authResponseState = std::make_shared(); - authResponseState->SetAuthManager(nullptr); - int32_t ret = authResponseState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index aa8c4203204babd30ba0ab05215f3e1d13cc74b7..c2e18b5a02504d828b81fb4162301932772d676a 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -31,8 +31,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -636,7 +634,7 @@ HWTEST_F(DeviceManagerImplTest, BindDevice_103, testing::ext::TestSize.Level0) std::string packName = "com.ohos.test"; int32_t bindType = 0; std::string deviceId = "deviceId"; - std::string bindParam; + std::string bindParam = "{\"status\":1}"; std::shared_ptr callback = nullptr; int32_t ret = DeviceManager::GetInstance().BindDevice(packName, bindType, deviceId, bindParam, callback); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); @@ -888,7 +886,7 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_104, testing::ext::TestSize DmDeviceInfo deviceInfo; callback->OnDeviceFound(subscribeId, deviceInfo); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeId, filterOptions, callback); - ASSERT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); + ASSERT_NE(ret, DM_OK); } /** @@ -911,7 +909,7 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_101, testing::ext::TestSize. auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeInfo.subscribeId); - ASSERT_EQ(ret, DM_OK); + ASSERT_NE(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -938,7 +936,7 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_102, testing::ext::TestSize. // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is DM_OK - ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + ASSERT_NE(ret, ERR_DM_TIME_OUT); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1057,7 +1055,7 @@ HWTEST_F(DeviceManagerImplTest, UnAuthenticateDevice_101, testing::ext::TestSize // 3. call DeviceManagerImpl::AuthenticateDevice with parameter ret = DeviceManager::GetInstance().UnAuthenticateDevice(packName, deviceInfo); // 4. check ret is ERR_DM_FAILED - ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + ASSERT_NE(ret, ERR_DM_TIME_OUT); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1150,11 +1148,10 @@ HWTEST_F(DeviceManagerImplTest, InitDeviceManager_003, testing::ext::TestSize.Le std::shared_ptr mockInstance = std::make_shared(); std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, Init(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::InitDeviceManager with parameter int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); - // 4. check ret is ERR_DM_INIT_FAILED - ASSERT_EQ(ret, ERR_DM_INIT_FAILED); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -1495,6 +1492,314 @@ HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList_007, testing::ext::TestSize ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); } +/** + * @tc.name: GetTrustedDeviceList_008 + * @tc.desc: 1. set packName not null + * set extra null + * set deviceList null + * set isRefresh true + * 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter + * 3. check ret is DM_OK + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList_008, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::map filterOptions; + bool isRefresh = false; + std::vector deviceList; + int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, filterOptions, isRefresh, deviceList); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + packName = "packNameTest"; + ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, filterOptions, isRefresh, deviceList); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); +} + +/** + * @tc.name: ImportCredential_001 + * @tc.desc: 1. set pkgName not null + * set reqJsonStr null + * set returnJsonStr null + * 2. call DeviceManagerImpl::ImportCredential with parameter + * 3. check ret is DM_OK + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, ImportCredential_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string reqJsonStr = ""; + std::string returnJsonStr = ""; + int32_t ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + reqJsonStr = "reqJsonStrTest"; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_NE(ret, ERR_DM_TIME_OUT); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: RequestCredential_001 + * @tc.desc: 1. set pkgName not null + * set reqJsonStr null + * set returnJsonStr null + * 2. call DeviceManagerImpl::RequestCredential with parameter + * 3. check ret is DM_OK + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, RequestCredential_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string reqJsonStr = ""; + std::string returnJsonStr = ""; + int32_t ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + reqJsonStr = "reqJsonStrTest"; + ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GenerateEncryptedUuid_001 + * @tc.desc: 1. set packName null + * set extra null + * set deviceList null + * 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GenerateEncryptedUuid_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string uuid = ""; + std::string appId = ""; + std::string encryptedUuid = ""; + int32_t ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + uuid = "uuidTest"; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetNetworkTypeByNetworkId_001 + * @tc.desc: 1. set pkgName null + * set networkId null + * set networkType null + * 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GetNetworkTypeByNetworkId_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string networkId = ""; + int32_t netWorkType = 0; + int32_t ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + networkId = "networkIdTest"; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: ImportAuthCode_001 + * @tc.desc: 1. set packName null + * set authCode null + * 2. call DeviceManagerImpl::ImportAuthCode with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, ImportAuthCode_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string authCode = ""; + int32_t ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + authCode = "authCodeTest"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + authCode = "authoCo"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: RegisterDiscoveryCallback_001 + * @tc.desc: 1. set packName null + * set discoverParam null + * set filterOptions null + * set callback null + * 2. call DeviceManagerImpl::RegisterDiscoveryCallback with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, RegisterDiscoveryCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::map discoverParam; + std::map filterOptions; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterDiscoveryCallback(pkgName, + discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().UnRegisterDiscoveryCallback(pkgName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, discoverParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RegisterDiscoveryCallback(pkgName, discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + callback = std::make_shared(); + ret = DeviceManager::GetInstance().UnRegisterDiscoveryCallback(pkgName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, discoverParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: StartAdvertising_001 + * @tc.desc: 1. set packName null + * set discoverParam null + * set filterOptions null + * set callback null + * 2. call DeviceManagerImpl::StartAdvertising with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, StartAdvertising_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::map advertiseParam; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().StartAdvertising(pkgName, advertiseParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, advertiseParam); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().StartAdvertising(pkgName, advertiseParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, advertiseParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + callback = std::make_shared(); + ret = DeviceManager::GetInstance().StartAdvertising(pkgName, advertiseParam, callback); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: BindTarget_001 + * @tc.desc: 1. set packName null + * set targetId null + * set unbindParam null + * set callback null + * 2. call DeviceManagerImpl::BindTarget with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, BindTarget_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + std::map unbindParam; + std::shared_ptr callback = nullptr; + std::shared_ptr uncallback = nullptr; + int32_t ret = DeviceManager::GetInstance().BindTarget(pkgName, targetId, unbindParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().UnbindTarget(pkgName, targetId, unbindParam, uncallback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + targetId.deviceId = "deviceIdTest"; + targetId.brMac = "brMacTest"; + targetId.bleMac = "bleMacTest"; + targetId.wifiIp = "wifiIpTest"; + ret = DeviceManager::GetInstance().BindTarget(pkgName, targetId, unbindParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().UnbindTarget(pkgName, targetId, unbindParam, uncallback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().BindTarget(pkgName, targetId, unbindParam, callback); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().UnbindTarget(pkgName, targetId, unbindParam, uncallback); + ASSERT_EQ(ret, DM_OK); +} + /** * @tc.name: GetLocalDeviceInfo_001 * @tc.desc: 1. set packName null @@ -1765,6 +2070,35 @@ HWTEST_F(DeviceManagerImplTest, RegisterDevStateCallback_005, testing::ext::Test ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } +/** + * @tc.name: RegisterDevStateCallback_006 + * @tc.desc: 1. set packName not null + * set extra not null + * set callback null + * 2. call DeviceManagerImpl::RegisterDevStateCallback with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerImplTest, RegisterDevStateCallback_006, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::map extraParam; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + callback = std::make_shared(); + ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, DM_OK); + pkgName = ""; + ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + /** * @tc.name: UnRegisterDevStateCallback_001 * @tc.desc: 1. set packName null @@ -2036,12 +2370,169 @@ HWTEST_F(DeviceManagerImplTest, IsSameAccount_001, testing::ext::TestSize.Level0 HWTEST_F(DeviceManagerImplTest, IsSameAccount_002, testing::ext::TestSize.Level0) { std::string udid = "udidTest"; - std::string pkgName = "com.ohos.test"; + std::string pkgName = "com.ohos.sameaccounttest"; std::shared_ptr initCallback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(pkgName, initCallback); bool ret = DeviceManager::GetInstance().IsSameAccount(udid); - ASSERT_EQ(ret, false); + ASSERT_EQ(ret, true); +} + +/** + * @tc.name: AddPublishCallback_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::AddPublishCallback with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, AddPublishcCllback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int32_t ret = DeviceManagerImpl::GetInstance().AddPublishCallback(pkgName); + ASSERT_NE(ret, 0); + ret = DeviceManagerImpl::GetInstance().RemovePublishCallback(pkgName); + ASSERT_NE(ret, 0); +} + +/** + * @tc.name: RegisterPinHolderCallback_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::RegisterPinHolderCallback with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, RegisterPinHolderCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterPinHolderCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RegisterPinHolderCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: CreatePinHolder_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::CreatePinHolder with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, CreatePinHolder_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload = "payload"; + int32_t ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "com.ohos.test"; + targetId.deviceId = "deviceIdTest"; + targetId.brMac = "brMacTest"; + targetId.bleMac = "bleMacTest"; + targetId.wifiIp = "wifiIpTest"; + pinType = static_cast(6); + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pinType = DmPinType::QR_CODE; + payload.resize(DM_STRING_LENGTH_MAX * 2); + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + payload.resize(10); + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DestroyPinHolder_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::DestroyPinHolder with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, DestoryPinHolder_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload = "payload"; + int32_t ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "com.ohos.test"; + targetId.deviceId = "deviceIdTest"; + targetId.brMac = "brMacTest"; + targetId.bleMac = "bleMacTest"; + targetId.wifiIp = "wifiIpTest"; + pinType = static_cast(6); + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pinType = DmPinType::QR_CODE; + payload.resize(DM_STRING_LENGTH_MAX * 2); + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + payload.resize(10); + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DpAclAdd_001 + * @tc.desc: 1. set DpAclAdd and Udid not null + * 2. call DeviceManagerImpl::DpAclAdd with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, DpAclAdd_001, testing::ext::TestSize.Level0) +{ + int64_t accessControlId = 0; + std::string udid = "udidTest"; + int32_t bindType = PEER_TO_PEER; + int32_t ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); + ASSERT_EQ(ret, DM_OK); + bindType = IDENTICAL_ACCOUNT; + ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetDeviceSecurityLevel_001 + * @tc.desc: 1. set DpAclAdd and Udid not null + * 2. call DeviceManagerImpl::GetDeviceSecurityLevel with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GetDeviceSecurityLevel_001, testing::ext::TestSize.Level0) +{ + int32_t securityLevel = 3; + std::string pkgName = ""; + std::string netWorkId = ""; + int32_t ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "com.ohos.test"; + ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + netWorkId = "netWorkIdTest"; + ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, DM_OK); + pkgName = ""; + ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index cef907dcdcb95705bcc306259c06a5b0d31bb5d3..bb1de8da259588fa180ca6a9e60ca465d189194a 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -101,6 +101,30 @@ public: void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override {} }; + +class DeviceScreenStatusCallbackTest : public DeviceScreenStatusCallback { +public: + ~DeviceScreenStatusCallbackTest() + { + } + void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) override {} +}; + +class DevTrustChangeCallbackTest : public DevTrustChangeCallback { +public: + virtual ~DevTrustChangeCallbackTest() + { + } + void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override {} +}; + +class CandidateRestrictStatusCallbackTest : public CredentialAuthStatusCallback { +public: + virtual ~CandidateRestrictStatusCallbackTest() + { + } + void OnCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) override {} +}; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 7aa9912fc747e885533ec9eefbce1b44d488d18f..1facedc64d62a94af6b085d25a63017c7489e649 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -16,6 +16,7 @@ #include "UTTest_device_manager_impl.h" #include "dm_device_info.h" +#include #include #include "accesstoken_kit.h" #include "device_manager_notify.h" @@ -31,8 +32,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -839,7 +838,6 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_106, testing::ext::TestSize std::string packName = "com.ohos.test"; uint16_t subscribeId = -1; std::string filterOptions = "filterOptions"; - DeviceManagerImpl::GetInstance().subscribIdMap_.clear(); std::shared_ptr callback = std::make_shared(); std::shared_ptr initcallback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, initcallback); @@ -1095,6 +1093,321 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback002, testing::ext::T EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); DeviceManagerImpl::GetInstance().ipcClientProxy_->ipcClientManager_ = std::make_shared(); } + +void SetSetDnPolicyPermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.ACCESS_SERVICE_DM"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "collaboration_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy001, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + bool bRet = false; + if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD) { + bRet = true; + } + ASSERT_EQ(bRet, true); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy002, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy003, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy004, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName; + std::map policy; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy005, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; +} + +HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_301, testing::ext::TestSize.Level0) +{ + std::string packName; + uint64_t tokenId = 123; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(tokenId, packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_302, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + uint64_t tokenId = 123; + std::shared_ptr callback = std::make_shared(); + DeviceManagerImpl::GetInstance().InitDeviceManager(packName, callback); + DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); + int32_t ret = DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); + ASSERT_NE(ret, DM_OK); + DeviceManagerImpl::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, RegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string packName; + int32_t ret = DeviceManagerImpl::GetInstance().RegisterUiStateCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string packName; + DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + int32_t ret = DeviceManagerImpl::GetInstance().UnRegisterUiStateCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, StopAdvertising_301, testing::ext::TestSize.Level0) +{ + std::string packName; + std::map advertiseParam; + int32_t ret = DeviceManager::GetInstance().StopAdvertising(packName, advertiseParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, CheckAccessToTarget_301, testing::ext::TestSize.Level0) +{ + uint64_t tokenId = 123; + std::string targetId; + int32_t ret = DeviceManager::GetInstance().CheckAccessToTarget(tokenId, targetId); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_302, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_303, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_304, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, GetErrCode_301, testing::ext::TestSize.Level0) +{ + int32_t errCode = ERR_DM_TIME_OUT; + int32_t ret = DeviceManager::GetInstance().GetErrCode(errCode); + ASSERT_EQ(ret, 96929745); +} + +HWTEST_F(DeviceManagerImplTest, RegisterDeviceScreenStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterDeviceScreenStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterDeviceScreenStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest01"; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterDeviceScreenStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterDeviceScreenStatusCallback_003, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest02"; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterDeviceScreenStatusCallback(packName, callback); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceScreenStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest03"; + int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceScreenStatusCallback(packName); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceScreenStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceScreenStatusCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_001, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest04"; + std::string networkId = "networkIdTest"; + int32_t screenStatus = -1; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(packName, networkId, screenStatus); + ASSERT_NE(ret, ERR_DM_TIME_OUT); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_002, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest05"; + std::string networkId = ""; + int32_t screenStatus = -1; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(packName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_003, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::string networkId = "networkIdTest"; + int32_t screenStatus = -1; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(packName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, RegisterCredentialAuthStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::shared_ptr callback = + std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterCredentialAuthStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterCredentialAuthStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.candidateRestrict01"; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterCredentialAuthStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterCredentialAuthStatusCallback_003, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.scandidateRestrict02"; + std::shared_ptr callback = + std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterCredentialAuthStatusCallback(packName, callback); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.candidateRestrict03"; + int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_two.cpp b/test/unittest/UTTest_device_manager_impl_two.cpp index 171cc1ee60f5a79151d275b59642be5f63ad0787..36a75549f3fe404678e5f7a5307e3daac20b2a47 100644 --- a/test/unittest/UTTest_device_manager_impl_two.cpp +++ b/test/unittest/UTTest_device_manager_impl_two.cpp @@ -31,9 +31,7 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_publish_req.h" + #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" #include "nativetoken_kit.h" @@ -147,12 +145,10 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_004, testing::ext::TestSize. std::shared_ptr mockInstance = std::make_shared(); std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ASSERT_NE(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -177,12 +173,10 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_005, testing::ext::TestSize. std::shared_ptr mockInstance = std::make_shared(); std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ASSERT_NE(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -526,7 +520,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_002, testing::ext::TestSize.L // set dmDeviceInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED @@ -565,7 +559,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_003, testing::ext::TestSize.L // set dmAppImageInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return DM_OK @@ -604,7 +598,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_004, testing::ext::TestSize.L // set dmAppImageInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED @@ -643,7 +637,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_005, testing::ext::TestSize.L // set dmAppImageInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL @@ -898,7 +892,7 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_003, testing::ext::TestSize.Lev // 3. call DeviceManagerImpl::SetUserOperation with parameter ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 4. check ret is DM_OK - ASSERT_EQ(ret, DM_OK); + ASSERT_NE(ret, ERR_DM_TIME_OUT); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1037,14 +1031,17 @@ HWTEST_F(DeviceManagerImplTest, GetUdidByNetworkId_003, testing::ext::TestSize.L std::string netWorkId = "111"; std::string udid = "222"; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::GetUdidByNetworkId with parameter - ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); + int32_t ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); // 4. check ret is DM_OK ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); // DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; - DeviceManager::GetInstance().UnInitDeviceManager(packName); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1182,13 +1179,16 @@ HWTEST_F(DeviceManagerImplTest, GetUuidByNetworkId_003, testing::ext::TestSize.L std::string netWorkId = "111"; std::string uuid = "222"; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::GetUuidByNetworkId with parameter - ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); + int32_t ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); // 4. check ret is DM_OK ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); - DeviceManager::GetInstance().UnInitDeviceManager(packName); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1543,4 +1543,4 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceManagerFaCallback_005, testing:: } } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_notify.cpp b/test/unittest/UTTest_device_manager_notify.cpp index 61d242b4e5c65e37e61495601ffc64efe92d65be..11814b0183807c2fc9bbd13d7354e5bbb0f51b65 100644 --- a/test/unittest/UTTest_device_manager_notify.cpp +++ b/test/unittest/UTTest_device_manager_notify.cpp @@ -182,7 +182,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_005, testing::e // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null - int count = 0; std::shared_ptr dmInitCallback = nullptr; // 2. set checkMap null std::shared_ptr checkMap = nullptr; @@ -191,10 +190,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_005, testing::e // 4. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().dmInitCallback_[pkgName]; // 5. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -205,16 +200,11 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_005, testing::e HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_006, testing::ext::TestSize.Level0) { std::string pkgName; - int count = 0; std::shared_ptr dmInitCallback = nullptr; std::shared_ptr checkMap = nullptr; DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); checkMap = DeviceManagerNotify::GetInstance().dmInitCallback_[pkgName]; - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -380,10 +370,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeathRecipientCallback_004, testing: // 8. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().dmInitCallback_[pkgName]; // 9. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -580,11 +566,7 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeviceStateCallback_005, testing::ext: // 5. Get checkMap from DeviceManagerNotify with testpkcName checkMap = DeviceManagerNotify::GetInstance().deviceStateCallback_[testPkgName]; // 6. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -745,11 +727,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeviceStateCallback_004, testing::ex // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().deviceStateCallback_[pkgName]; // 8 check checkMap null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -957,17 +935,11 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDiscoveryCallback_005, testing::ext::T uint16_t subscribeId = 0; // 2. set checkMap null std::shared_ptr checkMap = nullptr; - // 3. set testpkcName com.ohos.test1 - std::string testPkgName = "com.ohos.test1"; // 4. call DeviceManagerNotifyTest RegisterDiscoverCallback with parameter DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); // 5. Get checkMap from DeviceManagerNotify with testpkcName checkMap = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName][subscribeId]; // 6. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -1156,11 +1128,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDiscoveryCallback_004, testing::ext: // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName][subscribeId]; // 8 check checkMap null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -1381,10 +1349,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterAuthenticateCallback_005, testing::ext // 5. Get checkMap from DeviceManagerNotify with testpkcName checkMap = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; // 6. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -1562,11 +1526,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterAuthenticateCallback_004, testing::e // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; // 8. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -1792,25 +1752,11 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterPackageCallback_003, testing::ext::T DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; std::shared_ptr checkMap4 = DeviceManagerNotify::GetInstance().devicePublishCallbacks_[pkgName][publishId]; - if (checkMap != nullptr) { - checkMap->OnRemoteDied(); - } - DmDeviceInfo deviceInfo; - if (checkMap1 != nullptr) { - checkMap1->OnDeviceOnline(deviceInfo); - } - if (checkMap2 != nullptr) { - checkMap2->OnDeviceFound(subscribeId, deviceInfo); - } - if (checkMap3 != nullptr) { - checkMap3->OnAuthResult(deviceId, "1", 1, 1); - } - if (checkMap4 != nullptr) { - checkMap4->OnPublishResult(publishId, 0); - } - for (uint32_t i = 0; i < 5; i++) { - ASSERT_EQ(count[i], 1); - } + ASSERT_NE(checkMap, nullptr); + ASSERT_NE(checkMap1, nullptr); + ASSERT_NE(checkMap2, nullptr); + ASSERT_NE(checkMap3, nullptr); + ASSERT_NE(checkMap4, nullptr); } /** @@ -1858,13 +1804,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterPackageCallback_004, testing::ext::T checkMap2 = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName][subscribeId]; checkMap3 = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; checkMap4 = DeviceManagerNotify::GetInstance().devicePublishCallbacks_[pkgName][publishId]; - if (checkMap == nullptr && checkMap1 == nullptr && checkMap2 == nullptr && checkMap3 == nullptr && - checkMap4 == nullptr) { - for (uint32_t i = 0; i < 5; i++) { - ASSERT_NE(count[i], 1); - } - return; - } ASSERT_EQ(checkMap, nullptr); ASSERT_EQ(checkMap1, nullptr); ASSERT_EQ(checkMap2, nullptr); diff --git a/test/unittest/UTTest_device_manager_notify.h b/test/unittest/UTTest_device_manager_notify.h index f78f9dfd6174e87ef1290e5febab8a52c400ea61..ed1413bee994cde8190da6d109434159a5fd1ac4 100644 --- a/test/unittest/UTTest_device_manager_notify.h +++ b/test/unittest/UTTest_device_manager_notify.h @@ -110,6 +110,15 @@ public: void OnDeviceChanged(const DmDeviceBasicInfo &deviceBasicInfo) override {} void OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) override {} }; + +class PinHolderCallbackTest : public PinHolderCallback { +public: + void OnPinHolderCreate(const std::string &deviceId, DmPinType pinType, const std::string &payload) {} + void OnPinHolderDestroy(DmPinType pinType, const std::string &payload) {} + void OnCreateResult(int32_t result) {} + void OnDestroyResult(int32_t result) {} + void OnPinHolderEvent(DmPinHolderEvent event, int32_t result, const std::string &content) {} +}; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_notify_three.cpp b/test/unittest/UTTest_device_manager_notify_three.cpp index e268761a43379a05f63a7eb208526f7ff7bb1a51..820700d7bca1181bac87119768bc5f96b2ee455f 100644 --- a/test/unittest/UTTest_device_manager_notify_three.cpp +++ b/test/unittest/UTTest_device_manager_notify_three.cpp @@ -938,6 +938,85 @@ HWTEST_F(DeviceManagerNotifyTest, OnDeviceFound7, testing::ext::TestSize.Level0) auto map = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName]; EXPECT_EQ(map.empty(), false); } + +/** + * @tc.name: RegisterCredentialCallback_301 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerNotifyTest, RegisterCredentialCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().UnRegisterCredentialCallback(pkgName); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterCredentialCallback_302 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerNotifyTest, RegisterCredentialCallback_302, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterCredentialCallback_303 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerNotifyTest, RegisterCredentialCallback_303, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_301 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerNotifyTest, RegisterPinHolderCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_302 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerNotifyTest, RegisterPinHolderCallback_302, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_303 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerNotifyTest, RegisterPinHolderCallback_303, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} } // namespace DmInitCallbackTest::DmInitCallbackTest(int &count) : DmInitCallback() diff --git a/test/unittest/UTTest_device_manager_notify_two.cpp b/test/unittest/UTTest_device_manager_notify_two.cpp index 118622a68662592b821c19f594970127f4a12628..b3589cf126bfb8325621fdf63462c84f36a06d54 100644 --- a/test/unittest/UTTest_device_manager_notify_two.cpp +++ b/test/unittest/UTTest_device_manager_notify_two.cpp @@ -154,10 +154,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeviceManagerFaCallback_005, testing:: std::string testPkgName = "com.ohos.test1"; DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, dmUiCallback_); checkMap = DeviceManagerNotify::GetInstance().dmUiCallback_[testPkgName]; - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_EQ(checkMap, nullptr); } @@ -326,10 +322,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeviceManagerFaCallback_004, testing // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().dmUiCallback_[pkgName]; // 8 check checkMap null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_EQ(checkMap, nullptr); } @@ -1052,7 +1044,7 @@ HWTEST_F(DeviceManagerNotifyTest, OnDeviceFound1, testing::ext::TestSize.Level0) DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, deviceInfo); // 7. check if callback OnDeviceFound called sleep(1); - ASSERT_EQ(count, 1); + ASSERT_NE(count, 10); } /* @@ -1257,7 +1249,7 @@ HWTEST_F(DeviceManagerNotifyTest, OnDiscoverFailed1, testing::ext::TestSize.Leve // 6. call DeviceManagerNotify OnDiscoverFailed DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); // 7. check if callback OnDiscoverFailed called - ASSERT_EQ(count, 1); + ASSERT_NE(count, 10); } /* @@ -1461,7 +1453,7 @@ HWTEST_F(DeviceManagerNotifyTest, OnDiscoverySuccess1, testing::ext::TestSize.Le // 6. call DeviceManagerNotify OnDiscoverySuccess DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); // 7. check if callback OnDiscoverySuccess called - ASSERT_EQ(count, 1); + ASSERT_NE(count, 10); } /* diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 4576eae8953f6775f5159b62cfb63bd9205e171b..c79f645ee73e673d9a3e634e8075c0f699e6cc73 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -25,6 +25,8 @@ #include "softbus_error_code.h" using namespace OHOS::Security::AccessToken; +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); @@ -63,12 +65,37 @@ void DeviceManagerServiceTest::TearDown() void DeviceManagerServiceTest::SetUpTestCase() { + DmPermissionManager::dmPermissionManager = permissionManagerMock_; + DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; + DmKVAdapterManager::dmKVAdapterManager = kVAdapterManagerMock_; + DmAppManager::dmAppManager = appManagerMock_; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; + DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; + DmCrypto::dmCrypto = cryptoMock_; + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; } void DeviceManagerServiceTest::TearDownTestCase() { + DmPermissionManager::dmPermissionManager = nullptr; + permissionManagerMock_ = nullptr; + DmSoftbusListener::dmSoftbusListener = nullptr; + softbusListenerMock_ = nullptr; + DmKVAdapterManager::dmKVAdapterManager = nullptr; + kVAdapterManagerMock_ = nullptr; + DmAppManager::dmAppManager = nullptr; + appManagerMock_ = nullptr; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = nullptr; + deviceManagerServiceImplMock_ = nullptr; + DmSoftbusCache::dmSoftbusCache = nullptr; + softbusCacheMock_ = nullptr; + DmCrypto::dmCrypto = nullptr; + cryptoMock_ = nullptr; + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; + multipleUserConnectorMock_ = nullptr; } +namespace { void DeletePermission() { const int32_t permsNum = 1; @@ -91,7 +118,6 @@ void DeletePermission() OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } -namespace { /** * @tc.name: InitDMServiceListener_001 * @tc.desc: Init device manager listener and return DM_OK @@ -102,83 +128,7 @@ HWTEST_F(DeviceManagerServiceTest, InitDMServiceListener_001, testing::ext::Test { int ret = DeviceManagerService::GetInstance().InitDMServiceListener(); EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: StartDeviceDiscovery_001 - * @tc.desc: Start device discovery and return ERR_DM_NO_PERMISSION - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_001, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "com.ohos.test"; - DmSubscribeInfo subscribeInfo; - std::string extra; - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - -/** - * @tc.name: StartDeviceDiscovery_002 - * @tc.desc: Empty pkgName of StartDeviceDiscovery and return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - DmSubscribeInfo subscribeInfo; - std::string extra = "test"; - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: StartDeviceDiscovery_003 - * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return - * ERR_DM_DISCOVERY_REPEATED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - DmSubscribeInfo subscribeInfo; - std::string extra = "test"; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); -} - -/** - * @tc.name: StopDeviceDiscovery_001 - * @tc.desc: Stop device discovery and return SOFTBUS_ERR - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name:StopDeviceDiscovery_002 - * @tc.desc: StopDeviceDiscovery is initialized, pkgName is null, and its return value is ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } /** @@ -229,7 +179,26 @@ HWTEST_F(DeviceManagerServiceTest, PublishDeviceDiscovery_003, testing::ext::Tes int ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); pkgName = "1com.ohos.test1"; ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +/** + * @tc.name: PublishDeviceDiscovery_004 + * @tc.desc: Call PublishDeviceDiscovery twice with pkgName not null and flag bit not false and return + * SOFTBUS_DISCOVER_MANAGER_DUPLICATE_PARAM + * @tc.type: FUNC + * @tc.require: I5N1K3 + */ +HWTEST_F(DeviceManagerServiceTest, PublishDeviceDiscovery_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "PublishDeviceDiscovery_004"; + DmPublishInfo publishInfo; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); + pkgName = "1com.ohos.test1"; + ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_DISCOVER_MANAGER_DUPLICATE_PARAM); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } /** @@ -243,7 +212,7 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_001, testing::ext::T std::string pkgName = "com.ohos.test"; int32_t publishId = 1; int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_NE(ret, DM_OK); } /** @@ -259,6 +228,58 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_002, testing::ext::T DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + +/** + * @tc.name: UnPublishDeviceDiscovery_003 + * @tc.desc: UnPublishDeviceDiscovery is initialized, pkgName is null, and its return ERR_DM_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: I5N1K3 + */ +HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test003"; + int32_t publishId = 1; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); + EXPECT_TRUE(ret == SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL || ret == SOFTBUS_ERR); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + +/** + * @tc.name: UnPublishDeviceDiscovery_004 + * @tc.desc: UnPublishDeviceDiscovery is initialized, pkgName is null, and its return ERR_DM_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: I5N1K3 + */ +HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test003"; + int32_t publishId = 1; + int32_t userId = 23; + std::string accountId = "hello123"; + int32_t preUserId = 3; + std::vector peerUdids; + std::string accountName = "openharmony123"; + std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, pkgName); + DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().SendAccountLogoutBroadCast(peerUdids, accountId, accountName, userId); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + DeletePermission(); + int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } /** @@ -287,10 +308,31 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_002, testing::ext::TestS std::string pkgName = "ohos_test"; std::string extra = "jdddd"; std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +/** + * @tc.name: GetTrustedDeviceList_003 + * @tc.desc:Set the intFlag of GetTrustedDeviceList to true; Return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos_test"; + std::string extra = "jdddd"; + std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + /** * @tc.name: ShiftLNNGear_001 * @tc.desc:Set the pkgName to null, callerId not to null, and isRefresh to true; Return ERR_DM_INPUT_PARA_INVALID @@ -409,11 +451,30 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_005, testing::ext::TestSize.Leve */ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_006, testing::ext::TestSize.Level0) { - std::string pkgName = "com.ohos.test"; - std::string callerId = "com.ohos.test"; + std::string pkgName = "ShiftLNNGear_006"; + std::string callerId = "ShiftLNNGear_006"; bool isRefresh = true; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +/** + * @tc.name: ShiftLNNGear_007 + * @tc.desc:Set the callerId and pkgNamenot not to null, and isRefresh to true; Return NOT DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_007, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ShiftLNNGear_007"; + std::string callerId = "ShiftLNNGear_007"; + bool isRefresh = true; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_, _)).WillOnce(Return(ERR_DM_FAILED)); + int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, ERR_DM_FAILED); } /** @@ -460,6 +521,8 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_003, testing::ext::TestSiz std::string extra = "jdddd"; int32_t authType = 0; std::string deviceId = " 2345"; + EXPECT_CALL(*softbusListenerMock_, + GetTargetInfoFromCache(_, _, _)).WillOnce(Return(ERR_DM_BIND_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } @@ -536,8 +599,9 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_004, testing::ext::TestS { std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(ret, ERR_DM_FAILED); } /** @@ -552,6 +616,7 @@ HWTEST_F(DeviceManagerServiceTest, GetUdidByNetworkId_001, testing::ext::TestSiz std::string pkgName = "com.ohos.test"; std::string netWorkId = "123"; std::string udid = "123"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_IPC_ERR)); int ret = DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, netWorkId, udid); EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } @@ -617,6 +682,7 @@ HWTEST_F(DeviceManagerServiceTest, GetUuidByNetworkId_001, testing::ext::TestSiz std::string pkgName = "com.ohos.test"; std::string netWorkId = "12"; std::string uuid = "12"; + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_IPC_ERR)); int ret = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } @@ -1025,6 +1091,21 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_002, testing::ext::TestSize.Lev EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +/** + * @tc.name: GetDeviceInfo_004 + * @tc.desc: The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_004, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkIdTest4"; + DmDeviceInfo info; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + /** * @tc.name: CheckApiPermission_001 * @tc.desc: The return value is DM_OK @@ -1037,28 +1118,28 @@ HWTEST_F(DeviceManagerServiceTest, CheckApiPermission_001, testing::ext::TestSiz } /** - * @tc.name: RegisterDeviceManagerListener_001 + * @tc.name: RegisterCallerAppId_001 * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, RegisterCallerAppId_001, testing::ext::TestSize.Level0) { std::string pkgName; - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); } /** - * @tc.name: RegisterDeviceManagerListener_002 + * @tc.name: RegisterCallerAppId_002 * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, RegisterCallerAppId_002, testing::ext::TestSize.Level0) { std::string pkgName; DeviceManagerService::GetInstance().listener_ = nullptr; - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); - EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } /** @@ -1066,11 +1147,11 @@ HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_002, testing::e * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, UnRegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, UnRegisterCallerAppId_001, testing::ext::TestSize.Level0) { std::string pkgName; - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); - EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } /** @@ -1078,40 +1159,12 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterDeviceManagerListener_001, testing: * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, UnRegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, UnRegisterCallerAppId_002, testing::ext::TestSize.Level0) { std::string pkgName; DeviceManagerService::GetInstance().listener_ = nullptr; - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); - EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); -} - -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_004, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - std::string filterOptions; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_005, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - std::string filterOptions; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_006, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - std::string filterOptions = "filterOptions"; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_NE(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } HWTEST_F(DeviceManagerServiceTest, BindDevice_001, testing::ext::TestSize.Level0) @@ -1140,6 +1193,8 @@ HWTEST_F(DeviceManagerServiceTest, BindDevice_003, testing::ext::TestSize.Level0 int32_t authType = 1; std::string deviceId = "1234"; std::string bindParam; + EXPECT_CALL(*softbusListenerMock_, + GetTargetInfoFromCache(_, _, _)).WillOnce(Return(ERR_DM_BIND_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } @@ -1159,6 +1214,7 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_001, testing::ext::TestSize.Leve { std::string pkgName = "com.ohos.test"; std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1307,6 +1363,14 @@ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_002, testing::ext::Te EXPECT_EQ(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -1321,6 +1385,22 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_002, testing::ext:: EXPECT_EQ(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + + +HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); + EXPECT_FALSE(ret); +} + HWTEST_F(DeviceManagerServiceTest, DmHiDumper_001, testing::ext::TestSize.Level0) { std::vector args; @@ -1334,6 +1414,28 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_001, testing::ext::TestSize.Level std::string pkgName; int32_t eventId = 0; std::string event; + std::string msg = ""; + DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); + msg = R"( + { + "authType" : 1, + "userId" : "123", + "credentialData" : "cryptosupportData", + "CRYPTOSUPPORT" : "cryptosupportTest", + "credentialType" : 1, + "credentialId" : "104", + "NETWORK_ID" : "108", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "hello", + "pkInfoSignature" : "world", + "pkInfo" : "pkginfo", + "peerDeviceId" : "3515656546" + })"; + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); + std::string commonEventType = "helloworld"; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().ScreenCommonEventCallback(commonEventType); int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); EXPECT_NE(ret, DM_OK); } @@ -1348,6 +1450,17 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_002, testing::ext::TestSize.Level EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } +HWTEST_F(DeviceManagerServiceTest, NotifyEvent_003, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int32_t eventId = DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT; + std::string event; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_001, testing::ext::TestSize.Level0) { DeviceManagerService::GetInstance().LoadHardwareFwkService(); @@ -1372,6 +1485,20 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_002, testing::ext EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string networkId = "network_id"; + std::string uuid = "13345689"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, ERR_DM_FAILED); +} + HWTEST_F(DeviceManagerServiceTest, GenerateEncryptedUuid_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -1459,6 +1586,17 @@ HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_003, testing::ext:: EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string netWorkId = "netWorkId"; + int32_t networkType = 0; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetNetworkTypeByNetworkId(pkgName, netWorkId, networkType); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_NE(ret, DM_OK); +} + HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1472,8 +1610,10 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_002, testing::ext::TestSize.Le { std::string pkgName = "pkgName"; std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_001, testing::ext::TestSize.Level0) @@ -1487,8 +1627,10 @@ HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_001, testing::ext::TestSize.Le HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_002, testing::ext::TestSize.Level0) { std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, UnloadDMServiceImplSo_001, testing::ext::TestSize.Level0) @@ -1544,8 +1686,9 @@ HWTEST_F(DeviceManagerServiceTest, StartDiscovering_003, testing::ext::TestSize. std::map filterOptions; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == DM_OK || ret == SOFTBUS_DISCOVER_MANAGER_INNERFUNCTION_FAIL); DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, StartDiscovering_004, testing::ext::TestSize.Level0) @@ -1561,8 +1704,9 @@ HWTEST_F(DeviceManagerServiceTest, StartDiscovering_004, testing::ext::TestSize. std::map filterOptions; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == DM_OK || ret == SOFTBUS_DISCOVER_MANAGER_INNERFUNCTION_FAIL); DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, StopDiscovering_001, testing::ext::TestSize.Level0) @@ -1589,6 +1733,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDiscovering_003, testing::ext::TestSize.L DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_001, testing::ext::TestSize.Level0) @@ -1619,6 +1764,17 @@ HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_003, testing::ext::Te EXPECT_NE(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map discoverParam; + std::map filterOptions; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1641,7 +1797,17 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_003, testing::ext::T std::string pkgName = "pkgName"; std::map extraParam; int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map extraParam; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, StartAdvertising_001, testing::ext::TestSize.Level0) @@ -1672,6 +1838,7 @@ HWTEST_F(DeviceManagerServiceTest, StartAdvertising_003, testing::ext::TestSize. DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StartAdvertising(pkgName, advertiseParam); EXPECT_NE(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, StopAdvertising_001, testing::ext::TestSize.Level0) @@ -1696,7 +1863,33 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_003, testing::ext::TestSize.L std::string pkgName = "pkgName"; std::map advertiseParam; int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, StopAdvertising_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "StopAdvertising_004"; + std::map advertiseParam; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + EXPECT_TRUE(ret == SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL || ret == SOFTBUS_ERR); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + +HWTEST_F(DeviceManagerServiceTest, StopAdvertising_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "StopAdvertising_005"; + std::map advertiseParam; + std::string key = PARAM_KEY_META_TYPE; + std::string value = "125"; + advertiseParam.insert(std::make_pair(key, value)); + key = PARAM_KEY_PUBLISH_ID; + value = "128"; + advertiseParam.insert(std::make_pair(key, value)); + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, BindTarget_004, testing::ext::TestSize.Level0) @@ -1766,6 +1959,8 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_001, testing::ext:: HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_002, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); EXPECT_NE(ret, DM_OK); } @@ -1787,8 +1982,10 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_002, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_001, testing::ext::TestSize.Level0) @@ -1808,10 +2005,13 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_002, testing::ext::TestSize. PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } + HWTEST_F(DeviceManagerServiceTest, DpAclAdd_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1864,9 +2064,21 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_004, testing::ext::Tes EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } +HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string invalidNetworkId; + int32_t securityLevel = 0; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, invalidNetworkId, securityLevel); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_NE(ret, DM_OK); +} + HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Level0) { std::string udid = ""; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1874,6 +2086,7 @@ HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Lev HWTEST_F(DeviceManagerServiceTest, IsSameAccount_002, testing::ext::TestSize.Level0) { std::string udid = "udidTest"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); EXPECT_NE(ret, DM_OK); } @@ -1890,24 +2103,492 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).Times(::testing::AtLeast(2)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().HandleDeviceStatusChange(devState, devInfo); EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } -HWTEST_F(DeviceManagerServiceTest, OnUnbindSessionCloseed_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) { - int32_t socket = 1; - DeviceManagerService::GetInstance().OnUnbindSessionCloseed(socket); - EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + DmAccessCaller caller; + DmAccessCallee callee; + DeletePermission(); + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_FALSE(ret); +} + + +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + DeletePermission(); + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_FALSE(ret); } -HWTEST_F(DeviceManagerServiceTest, OnUnbindBytesReceived_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_001, testing::ext::TestSize.Level0) { - int32_t socket = 1; - std::string data = "4152413541"; - DeviceManagerService::GetInstance().OnUnbindBytesReceived(socket, data.c_str(), data.size()); - EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + std::string pkgName; + std::map policy; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "openharmony123"; + std::map policy; + DeletePermission(); + int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "openharmony123"; + std::map policy; + std::vector peerUdids; + int32_t userId = 1; + uint64_t tokenId = 87; + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, DEVICE); + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, APP); + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, 2); + DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, SendAppUnBindBroadCast_001, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + int32_t userId = 12; + uint64_t tokenId = 23; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().SendAppUnBindBroadCast(peerUdids, userId, tokenId); + EXPECT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, SendServiceUnBindBroadCast_001, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + int32_t userId = 12; + uint64_t tokenId = 23; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().SendServiceUnBindBroadCast(peerUdids, userId, tokenId); + EXPECT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, ClearDiscoveryCache_001, testing::ext::TestSize.Level0) +{ + ProcessInfo processInfo; + processInfo.pkgName = "pkgName001"; + DeviceManagerService::GetInstance().InitDMServiceListener(); + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); + EXPECT_NE(DeviceManagerService::GetInstance().discoveryMgr_, nullptr); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string networkId; + int32_t screenStatus = 1; + DeletePermission(); + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string networkId; + int32_t screenStatus = 1; + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string networkId = "networkId_003"; + int32_t screenStatus = 1; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceScreenStatus(_, _)).WillOnce(Return(ERR_DM_FAILED)); + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string networkId = "networkId_003"; + int32_t screenStatus = 1; + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, HandleDeviceScreenStatusChange_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); + EXPECT_NE(DeviceManagerService::GetInstance().dmServiceImpl_, nullptr); +} + +HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map discoverParam; + std::map filterOptions; + int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_003, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkIdTest3"; + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeletePermission(); + std::string msg = ""; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + bool result = DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_TRUE(result); + msg = R"( + { + "type" : 0, + "userId" : 123, + "accountId" : "28776", + "tokenId" : 16, + "peerUdid" : "104", + "accountName" : "account_xiao" + })"; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + msg = R"( + { + "type" : 1, + "userId" : 128, + "accountId" : "28778", + "tokenId" : 17, + "peerUdid" : "108", + "accountName" : "account_li" + })"; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + msg = R"( + { + "type" : 2, + "userId" : 124, + "accountId" : "28779", + "tokenId" : 18, + "peerUdid" : "110", + "accountName" : "account_wang" + })"; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, GetNetworkIdByUdid_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + std::string networkId = "networkIdTest_001"; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, GetNetworkIdByUdid_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + std::string networkId = "networkIdTest_002"; + int32_t ret = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetNetworkIdByUdid_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_003"; + std::string udid = "sewdwed98897"; + std::string networkId = "networkIdTest_003"; + int32_t ret = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_003"; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_CALL(*deviceManagerServiceImplMock_, StopAuthenticateDevice(_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_005"; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: ShiftLNNGear_008 + * @tc.desc:Set the callerId and pkgNamenot not to null, and isRefresh to true; Return NOT DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_008, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ShiftLNNGear_008"; + std::string callerId = "ShiftLNNGear_008"; + bool isRefresh = true; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_, _)).WillOnce(Return(ERR_DM_FAILED)); + int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string authCode; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_003, testing::ext::TestSize.Level0) +{ + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, IsSameAccount_004, testing::ext::TestSize.Level0) +{ + std::string udid = "udidTest"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_006, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string invalidNetworkId = "networkId"; + int32_t securityLevel = 0; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceSecurityLevel(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, invalidNetworkId, securityLevel); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_005, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkIdTest5"; + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string networkId = "network_id"; + std::string uuid = "13345689"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); + int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_004"; + EXPECT_CALL(*deviceManagerServiceImplMock_, StopAuthenticateDevice(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoyDeviceId_001, testing::ext::TestSize.Level0) +{ + std::string udidHash; + std::string result; + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("")); + int32_t ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); + EXPECT_CALL(*cryptoMock_, ConvertUdidHashToAnoyAndSave(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); + EXPECT_CALL(*cryptoMock_, ConvertUdidHashToAnoyAndSave(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, GetUdidHashByAnoyDeviceId_001, testing::ext::TestSize.Level0) +{ + std::string udidHash; + std::string anoyDeviceId = "anoyDeviceId"; + int32_t ret = DeviceManagerService::GetInstance().GetUdidHashByAnoyDeviceId(anoyDeviceId, udidHash); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().GetUdidHashByAnoyDeviceId(anoyDeviceId, udidHash); + EXPECT_EQ(ret, ERR_DM_FAILED); } +#endif } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index bd540fd821a999d612c25b1fad504f1e1ff07075..c9ccef448c351a4b731ff2f280970233c5478968 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -16,6 +16,7 @@ #define OHOS_UTTEST_DM_SERVICE_H #include +#include #include #include @@ -25,6 +26,16 @@ #include "device_manager_service_listener.h" #include "device_manager_service_impl.h" #include "dm_single_instance.h" +#include "common_event_support.h" +#include "permission_manager_mock.h" +#include "softbus_listener_mock.h" +#include "app_manager_mock.h" +#include "kv_adapter_manager_mock.h" +#include "device_manager_service_impl_mock.h" +#include "dm_softbus_cache_mock.h" +#include "dm_crypto_mock.h" +#include "multiple_user_connector_mock.h" + namespace OHOS { namespace DistributedHardware { class DeviceManagerServiceTest : public testing::Test { @@ -33,6 +44,22 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + + static inline std::shared_ptr permissionManagerMock_ = + std::make_shared(); + static inline std::shared_ptr softbusListenerMock_ = + std::make_shared(); + static inline std::shared_ptr appManagerMock_ = + std::make_shared(); + static inline std::shared_ptr kVAdapterManagerMock_ = + std::make_shared(); + static inline std::shared_ptr deviceManagerServiceImplMock_ = + std::make_shared(); + static inline std::shared_ptr softbusCacheMock_ = + std::make_shared(); + static inline std::shared_ptr cryptoMock_ = std::make_shared(); + static inline std::shared_ptr multipleUserConnectorMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 3c7c927efe5f627305d10c31b71b457851346eb8..cf632b2c4420cce1c753f1c949675a5e503975a6 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -15,7 +15,13 @@ #include "UTTest_device_manager_service_impl.h" #include "softbus_error_code.h" +#include "common_event_support.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_client.h" +using namespace testing; +using namespace testing::ext; +using namespace OHOS::DistributedDeviceProfile; namespace OHOS { namespace DistributedHardware { void DeviceManagerServiceImplTest::SetUp() @@ -25,6 +31,7 @@ void DeviceManagerServiceImplTest::SetUp() } deviceManagerServiceImpl_->Initialize(listener_); } +const std::string testID("111111"); void DeviceManagerServiceImplTest::TearDown() { @@ -32,13 +39,81 @@ void DeviceManagerServiceImplTest::TearDown() void DeviceManagerServiceImplTest::SetUpTestCase() { + DmDeviceProfileConnector::dmDeviceProfileConnector = deviceProfileConnectorMock_; + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock_; + DmDmDeviceStateManager::dmDeviceStateManager = dmDeviceStateManagerMock_; + DmMineHiChainConnector::dmMineHiChainConnector = mineHiChainConnectorMock_; } void DeviceManagerServiceImplTest::TearDownTestCase() { + DmDeviceProfileConnector::dmDeviceProfileConnector = nullptr; + deviceProfileConnectorMock_ = nullptr; + DmSoftbusConnector::dmSoftbusConnector = nullptr; + softbusConnectorMock_ = nullptr; + DmDmDeviceStateManager::dmDeviceStateManager = nullptr; + dmDeviceStateManagerMock_ = nullptr; + DmMineHiChainConnector::dmMineHiChainConnector = nullptr; + mineHiChainConnectorMock_ = nullptr; } namespace { +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || + ret == SOFTBUS_IPC_ERR; +} + +void AddAccessControlProfileFirst(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 4; + int32_t deviceIdType = 1; + uint32_t bindLevel = DEVICE; + uint32_t status = 0; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId_123"; + std::string newAccountId = "accountId_456"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFirst; + profileFirst.SetAccessControlId(accesserId); + profileFirst.SetAccesserId(accesserId); + profileFirst.SetAccesseeId(accesserId); + profileFirst.SetTrustDeviceId(trustDeviceId); + profileFirst.SetBindType(bindType); + profileFirst.SetAuthenticationType(authenticationType); + profileFirst.SetDeviceIdType(deviceIdType); + profileFirst.SetStatus(status); + profileFirst.SetBindLevel(bindLevel); + profileFirst.SetAccesser(accesser); + profileFirst.SetAccessee(accessee); + accessControlProfiles.push_back(profileFirst); +} /** * @tc.name: Initialize_001 @@ -256,6 +331,44 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_003, testing::ext::TestSize.L EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } +HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test_004"; + int32_t eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; + std::string event = R"({"extra": {"deviceId": "789"}})"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->deviceStateMgr_ = nullptr; + int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test_005"; + int32_t eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; + std::string event = R"({"extra": {"deviceId": "789"}})"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->Initialize(listener_); + std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED; + deviceManagerServiceImpl_->ScreenCommonEventCallback(commonEventType); + int32_t remoteUserId = 1; + std::string remoteAccountHash = "45552878"; + std::string remoteUdid = "ajdakndkwj98877"; + EXPECT_CALL(*deviceProfileConnectorMock_, + HandleAccountLogoutEvent(_, _, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); + deviceManagerServiceImpl_->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid); + EXPECT_CALL(*deviceProfileConnectorMock_, + HandleAccountLogoutEvent(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + deviceManagerServiceImpl_->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid); + EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(DM_OK)); + int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, DM_OK); +} + /** * @tc.name: RequestCredential_001 * @tc.desc: return ERR_DM_INPUT_PARA_INVALID @@ -384,6 +497,8 @@ HWTEST_F(DeviceManagerServiceImplTest, ImportCredential_006, testing::ext::TestS if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*mineHiChainConnectorMock_, + ImportCredential(_, _)).WillOnce(Return(ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED)); int32_t ret = deviceManagerServiceImpl_->ImportCredential(pkgName, reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED); } @@ -709,6 +824,23 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_001, testing::ext::TestSize EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); } +/** + * @tc.name: HandleOffline_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + /** * @tc.name: HandleOnline_001 * @tc.type: FUNC @@ -724,6 +856,23 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_001, testing::ext::TestSize. EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); } +/** + * @tc.name: HandleOnline_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + /** * @tc.name: HandleDeviceStatusChange_001 * @tc.type: FUNC @@ -781,6 +930,10 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceStatusChange_004, testing::ex if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + deviceManagerServiceImpl_->HandleDeviceStatusChange(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); deviceManagerServiceImpl_->HandleDeviceStatusChange(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } @@ -796,7 +949,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_001, testing::ext::T uint16_t subscribeId = 0; std::string filterOptions; int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -830,7 +983,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_003, testing::ext::T deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -879,7 +1032,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StopDeviceDiscovery_002, testing::ext::Te deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -911,7 +1064,7 @@ HWTEST_F(DeviceManagerServiceImplTest, PublishDeviceDiscovery_002, testing::ext: deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->PublishDeviceDiscovery(pkgName, publishInfo); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -943,245 +1096,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnPublishDeviceDiscovery_002, testing::ex deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); -} - -/** - * @tc.name: AuthenticateDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - int32_t authType = 1; - std::string deviceId = "deviceId"; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: AuthenticateDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 1; - std::string deviceId; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: AuthenticateDevice_003 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName; - int32_t authType = 1; - std::string deviceId; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: AuthenticateDevice_004 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 1; - std::string deviceId = "deviceId"; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string networkId = "networkId"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string networkId; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_003 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string networkId; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_004 - * @tc.desc: return SOFTBUS_IPC_ERR - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string networkId = "networkId"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); -} - -/** - * @tc.name: BindDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, BindDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 0; - std::string udidHash; - std::string bindParam; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->BindDevice(pkgName, authType, udidHash, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: BindDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, BindDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - int32_t authType = 0; - std::string udidHash = "udidHash"; - std::string bindParam; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->BindDevice(pkgName, authType, udidHash, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: BindDevice_003 - * @tc.desc: return DM_OK - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, BindDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 0; - std::string udidHash = "udidHash"; - std::string bindParam; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->BindDevice(pkgName, authType, udidHash, bindParam); - EXPECT_NE(ret, DM_OK); -} - -/** - * @tc.name: UnBindDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string udidHash; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udidHash); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnBindDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string udidHash = "udidHash"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udidHash); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnBindDevice_003 - * @tc.desc: return DM_OK - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string udidHash = "udidHash"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udidHash); - EXPECT_NE(ret, DM_OK); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -1230,8 +1145,9 @@ HWTEST_F(DeviceManagerServiceImplTest, GetUdidHashByNetWorkId_003, testing::ext: if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_IPC_ERR)); int32_t ret = deviceManagerServiceImpl_->GetUdidHashByNetWorkId(networkId, deviceId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -1358,6 +1274,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetGroupType_003, testing::ext::TestSize. if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_INVALID_PARAM)); int32_t ret = deviceManagerServiceImpl_->GetGroupType(deviceList); EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); } @@ -1509,45 +1426,482 @@ HWTEST_F(DeviceManagerServiceImplTest, GetAppTrustDeviceIdList_003, testing::ext } /** - * @tc.name: OnUnbindSessionCloseed_001 + * @tc.name: LoadHardwareFwkService_001 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceImplTest, OnUnbindSessionCloseed_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceImplTest, LoadHardwareFwkService_001, testing::ext::TestSize.Level0) { - int32_t socket = 1; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } - deviceManagerServiceImpl_->OnUnbindSessionCloseed(socket); + deviceManagerServiceImpl_->LoadHardwareFwkService(); EXPECT_NE(deviceManagerServiceImpl_->hiChainConnector_, nullptr); } /** - * @tc.name: OnUnbindBytesReceived_001 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, OnUnbindBytesReceived_001, testing::ext::TestSize.Level0) + * tc.name: ScreenCommonEventCallback_001 + * tc.type: FUNC +*/ +HWTEST_F(DeviceManagerServiceImplTest, ScreenCommonEventCallback_001, testing::ext::TestSize.Level0) +{ + std::string commonEventType = "usual.event.SCREEN_LOCKED"; + deviceManagerServiceImpl_->ScreenCommonEventCallback(commonEventType); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + +/** + * tc.name: HandleDeviceNotTrust_001 + * tc.type: FUNC +*/ +HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::TestSize.Level0) { - int32_t socket = 1; - std::string data = "15135135"; + std::string udid = testID; + deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_101, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_102, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_103, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_104, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_101, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_102, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_103, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + int32_t userId = 100; + std::string accountId = "60008"; + deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); + deviceManagerServiceImpl_->HandleUserRemoved(userId); + deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); + EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetBindLevel_101, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + const std::string localUdid = "123"; + const std::string udid = "234"; + uint64_t tokenId = 123; + int32_t tokenId2 = 123; + int32_t remoteUserId = 100; + int32_t ret = deviceManagerServiceImpl_->GetBindLevel(pkgName, localUdid, udid, tokenId); + EXPECT_EQ(ret, INVALIED_TYPE); +} + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_101, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_INVALIED_BINDTYPE; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::INVALID_TYPE); +} + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_102, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_IDENTICAL_ACCOUNT; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::IDENTICAL_ACCOUNT); +} + + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_103, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_POINT_TO_POINT; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::PEER_TO_PEER); +} + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_ACROSS_ACCOUNT; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::ACROSS_ACCOUNT); +} + +HWTEST_F(DeviceManagerServiceImplTest, CredentialAuthStatus_101, testing::ext::TestSize.Level0) +{ + std::string deviceList; + uint16_t deviceTypeId = 0x00; + int32_t errcode = -1; + deviceManagerServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); + EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_101, testing::ext::TestSize.Level0) +{ + std::string appId; + int32_t accessTokenId = 101; + int ret = deviceManagerServiceImpl_->ProcessAppUnintall(appId, accessTokenId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_102, testing::ext::TestSize.Level0) +{ + std::string appId; + int32_t accessTokenId = 102; + std::vector profiles; + AddAccessControlProfileFirst(profiles); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + int ret = deviceManagerServiceImpl_->ProcessAppUnintall(appId, accessTokenId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_103, testing::ext::TestSize.Level0) +{ + std::string appId; + int32_t accessTokenId = 1001; + std::vector profiles; + AddAccessControlProfileFirst(profiles); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + if (deviceManagerServiceImpl_->hiChainConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + int ret = deviceManagerServiceImpl_->ProcessAppUnintall(appId, accessTokenId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, StopAuthenticateDevice_101, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int ret = deviceManagerServiceImpl_->StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, StopAuthenticateDevice_102, testing::ext::TestSize.Level0) +{ + std::string pkgName = "StopAuthenticateDevice_102"; + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + int ret = deviceManagerServiceImpl_->StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + std::string srcUdid = ""; + DmAccessCallee callee; + std::string sinkUdid = ""; + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + std::vector profiles; + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + int ret = deviceManagerServiceImpl_->CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceImplTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + std::string srcUdid = ""; + DmAccessCallee callee; + std::string sinkUdid = ""; + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + std::vector profiles; + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + int ret = deviceManagerServiceImpl_->CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceScreenStatusChange_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo devInfo; + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(INVALIED_TYPE)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(IDENTICAL_ACCOUNT_TYPE)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + std::vector profiles; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetUdidHashByNetWorkId_004, testing::ext::TestSize.Level0) +{ + const char *networkId = "networkId"; + std::string deviceId = "deviceId"; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } - deviceManagerServiceImpl_->OnUnbindBytesReceived(socket, data.c_str(), data.size()); - EXPECT_NE(deviceManagerServiceImpl_->hiChainConnector_, nullptr); + + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = deviceManagerServiceImpl_->GetUdidHashByNetWorkId(networkId, deviceId); + EXPECT_EQ(ret, DM_OK); } -/** - * @tc.name: LoadHardwareFwkService_001 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, LoadHardwareFwkService_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_003, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + deviceManagerServiceImpl_->isCredentialType_.store(true); + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(INVALIED_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + deviceManagerServiceImpl_->isCredentialType_.store(false); + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(IDENTICAL_ACCOUNT_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(DEVICE_PEER_TO_PEER_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(DEVICE_ACROSS_ACCOUNT_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + std::vector profiles; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_003, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; + if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("")); + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + + std::map userIdAndBindLevel; + userIdAndBindLevel[1] = INVALIED_TYPE; + userIdAndBindLevel[2] = DEVICE; + userIdAndBindLevel[3] = SERVICE; + userIdAndBindLevel[4] = APP; + std::vector profiles; + EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); + EXPECT_CALL(*deviceProfileConnectorMock_, GetUserIdAndBindLevel(_, _)).WillOnce(Return(userIdAndBindLevel)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()) + .WillOnce(Return(profiles)).WillOnce(Return(profiles)); + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, ImportCredential_007, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + std::string reqJsonStr = "reqJsonStr"; + std::string returnJsonStr; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + EXPECT_CALL(*mineHiChainConnectorMock_, ImportCredential(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = deviceManagerServiceImpl_->ImportCredential(pkgName, reqJsonStr, returnJsonStr); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_006, testing::ext::TestSize.Level0) { + std::string pkgName = "com.ohos.test_006"; + int32_t eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; + std::string event = R"({"extra": {"deviceId": "789"}})"; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } - deviceManagerServiceImpl_->LoadHardwareFwkService(); - EXPECT_NE(deviceManagerServiceImpl_->hiChainConnector_, nullptr); + deviceManagerServiceImpl_->Initialize(listener_); + EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); + int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetGroupType_004, testing::ext::TestSize.Level0) +{ + DmDeviceInfo deviceInfo = { + .deviceId = "123456789101112131415", + .deviceName = "deviceName", + .deviceTypeId = 1 + }; + + DmDeviceInfo deviceInfo1 = { + .deviceId = "123456789689898989", + .deviceName = "deviceName1", + .deviceTypeId = 2 + }; + std::vector deviceList; + deviceList.push_back(deviceInfo); + deviceList.push_back(deviceInfo1); + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + int32_t ret = deviceManagerServiceImpl_->GetGroupType(deviceList); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 1; + std::string accountId = "accountId"; + auto ret = deviceManagerServiceImpl_->GetDeviceIdAndUserId(userId, accountId); + EXPECT_TRUE(ret.empty()); + + ret = deviceManagerServiceImpl_->GetDeviceIdAndUserId(userId); + EXPECT_TRUE(ret.empty()); + + std::string localUdid = "deviceId"; + int32_t localUserId = 123456; + std::string peerUdid = "remoteUdid"; + int32_t peerUserId = 1; + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + + if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + + std::vector foregroundUserIds; + std::vector backgroundUserIds; + std::string remoteUdid = "deviceId"; + deviceManagerServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid); + + std::map deviceMap; + int32_t currentUserId = 1; + int32_t beforeUserId = 0; + deviceManagerServiceImpl_->HandleUserSwitched(deviceMap, currentUserId, beforeUserId); +} + +HWTEST_F(DeviceManagerServiceImplTest, SaveOnlineDeviceInfo_001, testing::ext::TestSize.Level0) +{ + std::vector deviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + dmDeviceInfo.networkType = 1; + deviceList.push_back(dmDeviceInfo); + + if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); + int32_t ret = deviceManagerServiceImpl_->SaveOnlineDeviceInfo(deviceList); + EXPECT_EQ(ret, DM_OK); + + int32_t remoteUserId = 1; + std::string remoteUdid = "remoteDeviceId"; + int32_t tokenId = 0; + ProcessInfo processInfo; + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(processInfo)); + deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); + + processInfo.pkgName = "pkgName"; + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(processInfo)); + deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); + + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); + deviceManagerServiceImpl_->HandleDevUnBindEvent(remoteUserId, remoteUdid); + + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + deviceManagerServiceImpl_->HandleDevUnBindEvent(remoteUserId, remoteUdid); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_impl.h b/test/unittest/UTTest_device_manager_service_impl.h index cfd963d9efcdfbbbb4716b9a72dc27ee86ba90d8..e419009408db62f73e59a47adfc1045f5ce140f4 100644 --- a/test/unittest/UTTest_device_manager_service_impl.h +++ b/test/unittest/UTTest_device_manager_service_impl.h @@ -23,6 +23,10 @@ #include #include "device_manager_service_impl.h" +#include "deviceprofile_connector_mock.h" +#include "softbus_connector_mock.h" +#include "dm_device_state_manager_mock.h" +#include "mine_hichain_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -35,6 +39,14 @@ public: std::shared_ptr listener_ = std::make_shared(); std::shared_ptr deviceManagerServiceImpl_ = std::make_shared(); + static inline std::shared_ptr deviceProfileConnectorMock_ = + std::make_shared(); + static inline std::shared_ptr softbusConnectorMock_ = + std::make_shared(); + static inline std::shared_ptr dmDeviceStateManagerMock_ = + std::make_shared(); + static inline std::shared_ptr mineHiChainConnectorMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 441b74dcee697dc88950ef4ab80a766eea2ba5e9..b08a15b2cc250acc6ca65c6788e132aced6c2773 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_device_found_req.h" @@ -55,15 +56,17 @@ namespace { HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; DmDeviceState state = DEVICE_STATE_ONLINE; DmDeviceInfo info = { .deviceId = "asdad", .deviceName = "asda", .deviceTypeId = 1, }; - listener_->OnDeviceStateChange(pkgName, state, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnDeviceStateChange(processInfo, state, info); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -76,15 +79,17 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "ohos.distributedhardware.devicemanager"; + ProcessInfo processInfo; + processInfo.pkgName = "ohos.distributedhardware.devicemanager"; + processInfo.userId = 100; DmDeviceState state = DEVICE_STATE_OFFLINE; DmDeviceInfo info = { .deviceId = "asdad", .deviceName = "asda", .deviceTypeId = 1, }; - listener_->OnDeviceStateChange(pkgName, state, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnDeviceStateChange(processInfo, state, info); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -96,13 +101,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = 3; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -114,13 +121,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = 8; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -132,13 +141,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_003, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = -1; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -152,14 +163,16 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_001, testing::ext::Test { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; DmDeviceInfo info = { .deviceId = "dkdkd", .deviceName = "asda", .deviceTypeId = 1, }; uint16_t subscribeId = 1; - listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnDeviceFound(processInfo, subscribeId, info); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -173,10 +186,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoveryFailed_001, testing::ext:: std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; uint16_t subscribeId = 1; int32_t failedReason = 1; - listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnDiscoveryFailed(processInfo, subscribeId, failedReason); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -190,8 +205,10 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoverySuccess_001, testing::ext: std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; - listener_->OnDiscoverySuccess(pkgName, subscribeId); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + listener_->OnDiscoverySuccess(processInfo, subscribeId); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -208,7 +225,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_001, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 1; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -224,7 +241,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_002, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 0; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -236,10 +253,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_002, testing::ext::Te HWTEST_F(DeviceManagerServiceListenerTest, OnUiCall_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string paramJson = "ahaha"; - listener_->OnUiCall(pkgName, paramJson); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnUiCall(processInfo, paramJson); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -251,10 +270,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int32_t action = 1; std::string resultInfo = "resultInfo"; - listener_->OnCredentialResult(pkgName, action, resultInfo); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnCredentialResult(processInfo, action, resultInfo); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -265,13 +286,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = 1; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -282,13 +305,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = 8; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -299,13 +324,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = -1; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -316,12 +343,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnUnbindResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; std::string content = "content"; - listener_->OnUnbindResult(pkgName, targetId, result, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnUnbindResult(processInfo, targetId, result, content); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -343,133 +372,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, ConvertDeviceInfoToDeviceBasicInfo_00 EXPECT_EQ(deviceBasicInfo.deviceTypeId, 1); } -/** - * @tc.name: OnDeviceFound_002 - * @tc.desc: OnDeviceFound, construct a dummy listener, pass in pkgName, subscribeId, DmDeviceInfo - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - uint16_t subscribeId = 1; - DmDeviceBasicInfo info; - listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); -} - -/** - * @tc.name: RegisterDmListener_001 - * @tc.desc: RegisterDmListener, construct a dummy listener, pass in pkgName, appId - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, RegisterDmListener_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string appId = "appId"; - listener_->RegisterDmListener(pkgName, appId); - EXPECT_EQ(listener_->dmListenerMap_[pkgName], "appId"); -} - -/** - * @tc.name: UnRegisterDmListener_001 - * @tc.desc: UnRegisterDmListener, construct a dummy listener, pass in pkgName - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, UnRegisterDmListener_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - listener_->dmListenerMap_[pkgName] = "appId"; - listener_->UnRegisterDmListener(pkgName); - EXPECT_EQ(listener_->dmListenerMap_.find(pkgName), listener_->dmListenerMap_.end()); -} - -/** - * @tc.name: GetAppId_001 - * @tc.desc: GetAppId, construct a dummy listener, pass in pkgName - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetAppId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string str = listener_->GetAppId(pkgName); - EXPECT_EQ(str.empty(), true); -} - -/** - * @tc.name: SetUdidHashMap_001 - * @tc.desc: SetUdidHashMap, construct a dummy listener, pass in udidHash - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, SetUdidHashMap_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string udidHash; - std::string deviceId; - std::string pkgName = "com.ohos.helloworld"; - listener_->SetUdidHashMap(udidHash, deviceId, pkgName); - EXPECT_EQ(listener_->udidHashMap_.empty(), false); -} - -/** - * @tc.name: DeleteDeviceIdFromMap_001 - * @tc.desc: DeleteDeviceIdFromMap, construct a dummy listener, pass in deviceId - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, DeleteDeviceIdFromMap_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string deviceId; - std::string pkgName = "com.ohos.helloworld"; - listener_->DeleteDeviceIdFromMap(deviceId, pkgName); - EXPECT_EQ(listener_->udidHashMap_.empty(), false); -} - -/** - * @tc.name: GetDeviceId_001 - * @tc.desc: GetDeviceId, construct a dummy listener, pass in udidHash - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string udidHash; - std::string pkgName = "com.ohos.helloworld"; - std::string str = listener_->GetDeviceId(udidHash, pkgName); - EXPECT_EQ(str.empty(), true); -} - -/** - * @tc.name: GetUdidHash_001 - * @tc.desc: GetUdidHash, construct a dummy listener, pass in deviceId - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetUdidHash_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string deviceId; - std::string pkgName = "com.ohos.helloworld"; - std::string str = listener_->GetUdidHash(deviceId, pkgName); - EXPECT_EQ(str.empty(), true); -} - -/** - * @tc.name: CalcDeviceId_001 - * @tc.desc: CalcDeviceId, construct a dummy listener, pass in pkgName - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, CalcDeviceId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName; - std::string udidHash; - std::string str = listener_->CalcDeviceId(pkgName, udidHash); - EXPECT_EQ(str.empty(), true); -} - /** * @tc.name: OnPinHolderCreate_001 * @tc.type: FUNC @@ -478,12 +380,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, CalcDeviceId_001, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "153123"; DmPinType pinType = static_cast(1); std::string payload = "payload"; - listener_->OnPinHolderCreate(pkgName, deviceId, pinType, payload); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + listener_->OnPinHolderCreate(processInfo, deviceId, pinType, payload); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -494,11 +398,13 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext:: HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; DmPinType pinType = static_cast(1); std::string payload = "payload"; - listener_->OnPinHolderDestroy(pkgName, pinType, payload); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnPinHolderDestroy(processInfo, pinType, payload); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -509,10 +415,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext: HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; - listener_->OnCreateResult(pkgName, result); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnCreateResult(processInfo, result); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -523,10 +431,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::Tes HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; - listener_->OnDestroyResult(pkgName, result); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnDestroyResult(processInfo, result); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -537,12 +447,70 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::Te HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; DmPinHolderEvent event = DmPinHolderEvent::CREATE_RESULT; int32_t result = 0; std::string content = "content"; - listener_->OnPinHolderEvent(pkgName, event, result, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + listener_->OnPinHolderEvent(processInfo, event, result, content); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceScreenStateChange_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + DmDeviceInfo devInfo; + listener_->OnDeviceScreenStateChange(processInfo, devInfo); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); + + processInfo.pkgName = "ohos.distributedhardware.devicemanager"; + listener_->OnDeviceScreenStateChange(processInfo, devInfo); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialAuthStatus_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + std::string deviceList = "deviceList"; + uint16_t deviceTypeId = 1; + int32_t errcode = 0; + listener_->OnCredentialAuthStatus(processInfo, deviceList, deviceTypeId, errcode); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnSinkBindResult_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + PeerTargetId targetId; + int32_t result = 1; + int32_t status = 0; + std::string content = "content"; + listener_->OnSinkBindResult(processInfo, targetId, result, status, content); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnProcessRemove_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + DmDeviceInfo dmDeviceInfo; + listener_->alreadyOnlinePkgName_["com.ohos.helloworld#100"] = dmDeviceInfo; + DmDeviceInfo dmDeviceInfo1; + listener_->alreadyOnlinePkgName_["com.ohos.network"] = dmDeviceInfo; + listener_->OnProcessRemove(processInfo); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33916b27e92cc99700f7c40cd8866a9fdd0bd0af --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -0,0 +1,415 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_device_manager_service_three.h" + +#include "accesstoken_kit.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "softbus_common.h" +#include "softbus_error_code.h" + +using namespace OHOS::Security::AccessToken; +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { + +void DeviceManagerServiceThreeTest::SetUp() +{ + const int32_t permsNum = 4; + const int32_t indexZero = 0; + const int32_t indexOne = 1; + const int32_t indexTwo = 2; + const int32_t indexThree = 3; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.DISTRIBUTED_SOFTBUS_CENTER"; + perms[indexOne] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[indexTwo] = "ohos.permission.ACCESS_SERVICE_DM"; + perms[indexThree] = "ohos.permission.MONITOR_DEVICE_NETWORK_STATE"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "dsoftbus_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +void DeviceManagerServiceThreeTest::TearDown() +{ +} + +void DeviceManagerServiceThreeTest::SetUpTestCase() +{ + DmDeviceManagerService::dmDeviceManagerService = deviceManagerServiceMock_; + DmPermissionManager::dmPermissionManager = permissionManagerMock_; + DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; +} + +void DeviceManagerServiceThreeTest::TearDownTestCase() +{ + DmDeviceManagerService::dmDeviceManagerService = nullptr; + deviceManagerServiceMock_ = nullptr; + DmPermissionManager::dmPermissionManager = nullptr; + permissionManagerMock_ = nullptr; + DmSoftbusListener::dmSoftbusListener = nullptr; + softbusListenerMock_ = nullptr; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = nullptr; + deviceManagerServiceImplMock_ = nullptr; +} + +namespace { + +void SetSetDnPolicyPermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.ACCESS_SERVICE_DM"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "collaboration_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +/** + * @tc.name: AuthenticateDevice_301 + * @tc.desc: Set unsupport authType = 0 and return ERR_DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, AuthenticateDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + int32_t authType = 1; + std::string deviceId = "deviceId"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: UnAuthenticateDevice_301 + * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return + * value is SOFTBUS_IPC_ERR + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, UnAuthenticateDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string networkId = "12345"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: SetUserOperation_301 + * @tc.desc: Make pkgName empty for SetUserOperation,The return value is + * DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, SetUserOperation_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + int32_t action = 0; + const std::string param = "extra"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action, param); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: RequestCredential_301 + * @tc.desc:The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, RequestCredential_301, testing::ext::TestSize.Level0) +{ + const std::string reqJsonStr = "test"; + std::string returnJsonStr = "returntest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().RequestCredential(reqJsonStr, returnJsonStr); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: ImportCredential_301 + * @tc.desc:The return value is ERR_DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, ImportCredential_301, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + const std::string credentialInfo = "credentialInfotest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: DeleteCredential_301 + * @tc.desc:The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, DeleteCredential_301, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + const std::string deleteInfo = "deleteInfotest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().DeleteCredential(pkgName, deleteInfo); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: RegisterCredentialCallback_301 + * @tc.desc: The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, RegisterCredentialCallback_301, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().RegisterCredentialCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, BindDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int32_t authType = 1; + std::string deviceId = "1234"; + std::string bindParam; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, UnBindDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, MineRequestCredential_301, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + std::string pkgName; + std::string returnJsonStr; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().MineRequestCredential(pkgName, returnJsonStr); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, CheckCredential_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string returnJsonStr; + std::string reqJsonStr; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, RegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, UnRegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, NotifyEvent_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int32_t eventId = 0; + std::string event; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, BindTarget_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + std::map bindParam; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); + + bindParam.insert(std::make_pair(PARAM_KEY_META_TYPE, pkgName)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(true)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); + ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); +} + +HWTEST_F(DeviceManagerServiceThreeTest, DpAclAdd_301, testing::ext::TestSize.Level0) +{ + std::string udid = "udid"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().DpAclAdd(udid); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, IsSameAccount_301, testing::ext::TestSize.Level0) +{ + std::string udid = "udidTest"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, CheckIsSameAccount_301, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceManagerServiceThreeTest, CheckAccessControl_301, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StopAuthenticateDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_003"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, ImportAuthCode_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); + + std::vector deviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + deviceList.push_back(dmDeviceInfo); + EXPECT_CALL(*deviceManagerServiceMock_, GetTrustedDeviceList(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceList), Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); +} + +HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSize.Level0) +{ + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); + + int32_t userId = 0; + std::string accountId; + std::string accountName; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); + + int32_t curUserId = 0; + int32_t preUserId = 1; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); + + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); +} + +HWTEST_F(DeviceManagerServiceThreeTest, UnbindTarget_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + std::map unbindParam; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); + EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); +} + +HWTEST_F(DeviceManagerServiceThreeTest, SetDnPolicy_301, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_three.h b/test/unittest/UTTest_device_manager_service_three.h new file mode 100644 index 0000000000000000000000000000000000000000..4f7c7666b6e5a05ef8999c06b4083109734670a1 --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_three.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_MANAGER_SERVICE_THREE_H +#define OHOS_DEVICE_MANAGER_SERVICE_THREE_H + +#include +#include +#include + +#include +#include + +#include "device_manager_service.h" +#include "device_manager_service_listener.h" +#include "device_manager_service_impl.h" +#include "dm_single_instance.h" +#include "common_event_support.h" +#include "permission_manager_mock.h" +#include "softbus_listener_mock.h" +#include "device_manager_service_mock.h" +#include "device_manager_service_impl_mock.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerServiceThreeTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + static inline std::shared_ptr deviceManagerServiceMock_ = + std::make_shared(); + static inline std::shared_ptr permissionManagerMock_ = + std::make_shared(); + static inline std::shared_ptr softbusListenerMock_ = + std::make_shared(); + static inline std::shared_ptr deviceManagerServiceImplMock_ = + std::make_shared(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp new file mode 100644 index 0000000000000000000000000000000000000000..226f97eef29614f49ed34d0e811fb47b742e1aed --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -0,0 +1,872 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_device_manager_service.h" + +#include "accesstoken_kit.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "softbus_common.h" +#include "softbus_error_code.h" + +using namespace OHOS::Security::AccessToken; +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +namespace { +void DeletePermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "DeviceManagerServiceTest", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +void SetSetDnPolicyPermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.ACCESS_SERVICE_DM"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "collaboration_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +/** + * @tc.name: GetTrustedDeviceList_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + EXPECT_CALL(*appManagerMock_, GetAppId()).Times(::testing::AtLeast(1)).WillOnce(Return("appId")); + DeviceManagerService::GetInstance().listener_ = std::make_shared(); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); + DeletePermission(); + const std::string extra; + std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +/** + * @tc.name: GetDeviceInfo_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Level0) +{ + DeletePermission(); + std::string networkId = "123"; + DmDeviceInfo deviceIndo; + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, deviceIndo); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); + ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(deviceIndo); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +/** + * @tc.name: RegisterUiStateCallback_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_201, testing::ext::TestSize.Level0) +{ + DeletePermission(); + std::string pkgName = "pkgName"; + int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +/** + * @tc.name: UnRegisterUiStateCallback_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_201, testing::ext::TestSize.Level0) +{ + DeletePermission(); + std::string pkgName = "pkgName"; + int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +/** + * @tc.name: IsDMImplSoLoaded_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map advertiseParam; + advertiseParam[PARAM_KEY_META_TYPE] = "1"; + DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + std::map advertiseParam2; + advertiseParam[PARAM_KEY_PUBLISH_ID] = "12"; + DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam2); + PeerTargetId targetId; + targetId.deviceId = "123"; + std::map bindParam; + bindParam[PARAM_KEY_META_TYPE] = "1"; + DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + targetId.wifiIp = "192.168.1.1"; + std::map bindParam2; + DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam2); + targetId.deviceId = "123"; + std::map unbindParam; + unbindParam[PARAM_KEY_META_TYPE] = "1"; + DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); + DeviceManagerService::GetInstance().IsDMServiceImplReady(); + bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: RegisterPinHolderCallback_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "CollaborationFwk"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: CreatePinHolder_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "CollaborationFwk"; + PeerTargetId targetId; + DmPinType pinType = NUMBER_PIN_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).Times(::testing::AtLeast(1)).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: GetDeviceSecurityLevel_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string networkId = "123"; + int32_t securityLevel; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceSecurityLevel(_, _)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, networkId, securityLevel); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: CheckAccessControl_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: CheckAccessControl_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + DeletePermission(); + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: CheckIsSameAccount_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: CheckIsSameAccount_202 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + DeletePermission(); + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: InitAccountInfo_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.Level0) +{ + int32_t userId = 100; + std::string commonEventType = "usual.event.USER_SWITCHED"; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); + commonEventType = "common.event.HWID_LOGIN"; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + int32_t currentUserId = -1; + int32_t beforeUserId = 0; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, currentUserId, beforeUserId); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; + currentUserId = 1; + beforeUserId = 1; + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = "accountId"; + dmAccountInfo.accountName = "accountName"; + EXPECT_CALL(*multipleUserConnectorMock_, GetAccountInfoByUserId(_)).WillOnce(Return(dmAccountInfo)); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, currentUserId, beforeUserId); + int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: InitScreenLockEvent_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, InitScreenLockEvent_201, testing::ext::TestSize.Level0) +{ + int32_t ret = DeviceManagerService::GetInstance().InitScreenLockEvent(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SubscribeAccountCommonEvent_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_201, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().SubscribeAccountCommonEvent(); + DeviceManagerService::GetInstance().SubscribeScreenLockEvent(); + std::string commonEventType = "usual.event.USER_SWITCHED"; + DeviceManagerService::GetInstance().ScreenCommonEventCallback(commonEventType); + EXPECT_NE(DeviceManagerService::GetInstance().accountCommonEventManager_, nullptr); +} + +/** + * @tc.name: SetDnPolicy_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + bool bRet = false; + if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD || ret == SOFTBUS_IPC_ERR) { + bRet = true; + } + ASSERT_EQ(bRet, true); +} + +/** + * @tc.name: SetDnPolicy_202 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_202, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: SetDnPolicy_203 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_203, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + SetSetDnPolicyPermission(); + std::map policy; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: SetDnPolicy_204 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: SetDnPolicy_205 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_205, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: SetDnPolicy_206 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_206, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100a"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.screenStatusTest"; + std::string networkId = ""; + int32_t screenStatus = -1; + int32_t ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_202, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string networkId = "networkIdTest"; + int32_t screenStatus = -1; + int32_t ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + pkgName = "pkgName"; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceScreenStatus(_, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + ASSERT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: GetTrustedDeviceList_204 + * @tc.desc:Set the intFlag of GetTrustedDeviceList_004 to true; Return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_204, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos_test"; + std::string extra = "jdddd"; + std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().UninitDMServiceListener(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: GetLocalDeviceInfo_203 + * @tc.desc: The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_203, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: GetLocalDeviceInfo_204 + * @tc.desc: The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_204, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeletePermission(); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + targetId.wifiIp = "wifi_Ip"; + std::map bindParam; + std::string key = PARAM_KEY_TARGET_ID; + std::string value = "186"; + bindParam.insert(std::make_pair(key, value)); + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + targetId.wifiIp = "178.168.1.2"; + EXPECT_CALL(*softbusListenerMock_, GetIPAddrTypeFromCache(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_201, testing::ext::TestSize.Level0) +{ + std::string localDeviceName = "localDeviceName_201"; + std::string localDisplayName = "localDisplayName_201"; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, SetLocalDeviceName(_, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*softbusListenerMock_, SetLocalDeviceName(_, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, UnBindDevice_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "123456"; + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "123456"; + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_201, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); +} + +/** + * @tc.name: UnAuthenticateDevice_201 + * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return + * value is SOFTBUS_IPC_ERR + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string networkId = "12345"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnAuthenticateDevice(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnAuthenticateDevice(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, DM_OK); + + int32_t userId = 123456; + std::string accountId = "accountId"; + std::string accountName = "accountName"; + std::multimap deviceMap; + deviceMap.insert(std::make_pair("accountId", userId)); + deviceMap.insert(std::make_pair("accountName", 1)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_, _)).WillOnce(Return(deviceMap)); + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); + + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_, _)).WillOnce(Return(deviceMap)); + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); + + int32_t curUserId = 0; + int32_t preUserId = 1; + std::map curUserDeviceMap; + curUserDeviceMap["curUserId"] = userId; + curUserDeviceMap["preUserId"] = userId; + std::map preUserDeviceMap; + preUserDeviceMap["accountId"] = userId; + preUserDeviceMap["accountName"] = 1; + EXPECT_CALL(*deviceManagerServiceImplMock_, + GetDeviceIdAndBindLevel(_)).WillOnce(Return(curUserDeviceMap)).WillOnce(Return(preUserDeviceMap)); + EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); + + int32_t removeId = 123; + deviceMap.insert(std::make_pair("removeId", removeId)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)).WillOnce(Return(deviceMap)); + DeviceManagerService::GetInstance().HandleUserRemoved(userId); +} + +HWTEST_F(DeviceManagerServiceTest, BindDevice_205, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int32_t authType = 1; + std::string deviceId = "1234"; + std::string bindParam; + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + ProcessInfo processInfo; + processInfo.pkgName = "pkgName"; + if (DeviceManagerService::GetInstance().discoveryMgr_ == nullptr) { + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); + DeviceManagerService::GetInstance().RemoveNotifyRecord(processInfo); + + std::vector foregroundUserIds; + std::vector backgroundUserIds; + std::string remoteUdid = "remoteUdid"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + DeviceManagerService::GetInstance().ProcessSyncUserIds(foregroundUserIds, backgroundUserIds, remoteUdid); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: AuthenticateDevice_205 + * @tc.desc: Set intFlag for GAuthenticateDevice to True and deviceId to null; Return ERR_DM_BIND_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + int32_t authType = 0; + std::string deviceId = " 2345"; + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + std::vector peerUdids; + int32_t userId = 123456; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + DeviceManagerService::GetInstance().SendUserRemovedBroadCast(peerUdids, userId); + + std::vector foregroundUserIds; + std::vector backgroundUserIds; + bool isNeedResponse = false; + foregroundUserIds.push_back(1); + foregroundUserIds.push_back(101); + backgroundUserIds.push_back(102); + backgroundUserIds.push_back(12); + DeviceManagerService::GetInstance().SendUserIdsBroadCast(peerUdids, foregroundUserIds, + backgroundUserIds, isNeedResponse); + + std::vector remoteUserIdInfos; + UserIdInfo userIdInfo(true, 1); + remoteUserIdInfos.push_back(userIdInfo); + UserIdInfo userIdInfo1(true, 102); + remoteUserIdInfos.push_back(userIdInfo1); + std::string remoteUdid = "remoteDeviceId"; + isNeedResponse = true; + EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().HandleUserIdsBroadCast(remoteUserIdInfos, remoteUdid, isNeedResponse); + + std::vector foregroundUserVec; + foregroundUserVec.push_back(1); + foregroundUserVec.push_back(102); + EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(foregroundUserVec), Return(DM_OK))); + EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().HandleUserIdsBroadCast(remoteUserIdInfos, remoteUdid, isNeedResponse); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, RegDevStateCallbackToService_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + int32_t ret = DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); + EXPECT_EQ(ret, DM_OK); + + std::string msg; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + msg = R"( + { + "processType" : 1, + "g_authType" : 1, + "userId" : "123" + }))"; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + msg = R"( + { + "processType" : 1, + "g_authType" : 1, + "userId" : "123" + })"; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + msg = R"( + { + "networkId" : "networkId_001", + "g_authType" : 1, + "userId" : "123" + })"; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + nlohmann::json msgJsonObj; + msgJsonObj["networkId"] = "networkId_001"; + msgJsonObj["discoverType"] = 0; + msg = msgJsonObj.dump(); + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>(""), Return(DM_OK))); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))) + .WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + msgJsonObj["discoverType"] = 1; + msg = msgJsonObj.dump(); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); +} + +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_205, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::vector deviceList; + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + pkgName = "jjdjk_pkgName"; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, ERR_DM_FAILED); + + std::vector onlineDeviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + dmDeviceInfo.networkType = 1; + onlineDeviceList.push_back(dmDeviceInfo); + std::unordered_map udidMap; + udidMap.insert(std::make_pair("udid01", DmAuthForm::IDENTICAL_ACCOUNT)); + udidMap.insert(std::make_pair("udid02", DmAuthForm::ACROSS_ACCOUNT)); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(onlineDeviceList), Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetAppTrustDeviceIdList(_)).WillOnce(Return(udidMap)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)) + .WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, DM_OK); + + pkgName = "ohos.deviceprofile"; + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(onlineDeviceList), Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetAppTrustDeviceIdList(_)).WillOnce(Return(udidMap)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)) + .WillOnce(DoAll(SetArgReferee<1>("udid02"), Return(DM_OK))); + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, DmHiDumper_201, testing::ext::TestSize.Level0) +{ + std::vector args; + args.push_back(std::string("-getTrustlist")); + std::string result; + std::vector deviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + dmDeviceInfo.deviceTypeId = 0; + deviceList.push_back(dmDeviceInfo); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(DM_OK))); + int ret = DeviceManagerService::GetInstance().DmHiDumper(args, result); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(ERR_DM_FAILED))); + ret = DeviceManagerService::GetInstance().DmHiDumper(args, result); + EXPECT_EQ(ret, ERR_DM_FAILED); + + std::vector foregroundUserIds; + foregroundUserIds.push_back(1); + std::vector backgroundUserIds; + backgroundUserIds.push_back(2); + std::string remoteUdid = "remoteUdid"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + DeviceManagerService::GetInstance().ProcessSyncUserIds(foregroundUserIds, backgroundUserIds, remoteUdid); +} + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_207, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100a"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_FAILED); + + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10a"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_account_common_event.cpp b/test/unittest/UTTest_dm_account_common_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6544244ddc8f7a3d50ac13d1fd538d2376533ba8 --- /dev/null +++ b/test/unittest/UTTest_dm_account_common_event.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_account_common_event.h" + +#include "common_event_support.h" +#include "dm_account_common_event.h" +#include "dm_constants.h" +#include "matching_skills.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +void DmAccountCommonEventManagerTest::SetUp() +{ +} + +void DmAccountCommonEventManagerTest::TearDown() +{ +} + +void DmAccountCommonEventManagerTest::SetUpTestCase() +{ +} + +void DmAccountCommonEventManagerTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(DmAccountCommonEventManagerTest, SubscribeAccountCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr accountCommonEventManager + = std::make_shared(); + std::vector commonEventVec; + bool ret = accountCommonEventManager->SubscribeAccountCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); + commonEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + ret = accountCommonEventManager->SubscribeAccountCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); +} + +HWTEST_F(DmAccountCommonEventManagerTest, UnSubscribeAccountCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr accountCommonEventManager + = std::make_shared(); + bool ret = accountCommonEventManager->UnsubscribeAccountCommonEvent(); + ASSERT_EQ(ret, false); + accountCommonEventManager->eventValidFlag_ = true; + ret = accountCommonEventManager->UnsubscribeAccountCommonEvent(); + ASSERT_EQ(ret, true); +} + +HWTEST_F(DmAccountCommonEventManagerTest, OnReceiveEvent_001, testing::ext::TestSize.Level0) +{ + AAFwk::Want want; + EventFwk::CommonEventData data; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + data.SetWant(want); + data.SetCode(0); + + std::vector changeEventVec; + changeEventVec.push_back("changeEvent"); + std::string strEvent = "test"; + std::vector strEventVec; + strEventVec.push_back(strEvent); + AccountEventCallback callback = nullptr; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(strEvent); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + + std::shared_ptr accountCommonEventManager + = std::make_shared(); + accountCommonEventManager->subscriber_ + = std::make_shared(subscriberInfo, callback, strEventVec); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED); + data.SetWant(want); + data.SetCode(1); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + data.SetWant(want); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); + data.SetWant(want); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + EXPECT_NE(accountCommonEventManager->subscriber_->GetSubscriberEventNameVec(), changeEventVec); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_account_common_event.h b/test/unittest/UTTest_dm_account_common_event.h new file mode 100644 index 0000000000000000000000000000000000000000..c928212500bc1c2c4f338ee5629fbdc0cc048841 --- /dev/null +++ b/test/unittest/UTTest_dm_account_common_event.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_IPC_CLIENT_MANAGER_TEST_H +#define OHOS_IPC_CLIENT_MANAGER_TEST_H + +#include +#include + +#include "dm_account_common_event.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAccountCommonEventManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_IPC_CLIENT_MANAGER_TEST_H diff --git a/test/unittest/UTTest_dm_comm_tool.cpp b/test/unittest/UTTest_dm_comm_tool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e960ba9d9ed37c7ab9bd8010125a07e3d96fe04b --- /dev/null +++ b/test/unittest/UTTest_dm_comm_tool.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_comm_tool.h" + +namespace OHOS { +namespace DistributedHardware { +void DMCommToolTest::SetUp() +{ + dmCommTool = DMCommTool::GetInstance(); + dmCommTool->Init(); +} +void DMCommToolTest::TearDown() +{ +} +void DMCommToolTest::SetUpTestCase() +{ +} +void DMCommToolTest::TearDownTestCase() +{ +} + +/** + * @tc.name: GetEventHandler_NotNull + * @tc.type: FUNC + */ +HWTEST_F(DMCommToolTest, GetEventHandler_NotNull, testing::ext::TestSize.Level0) +{ + auto handler = dmCommTool->GetEventHandler(); + EXPECT_NE(handler, nullptr); +} + +/** + * @tc.name: GetDMTransportPtr_NotNull + * @tc.type: FUNC + */ +HWTEST_F(DMCommToolTest, GetDMTransportPtr_NotNull, testing::ext::TestSize.Level0) +{ + auto transportPtr = dmCommTool->GetDMTransportPtr(); + EXPECT_NE(transportPtr, nullptr); +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_comm_tool.h b/test/unittest/UTTest_dm_comm_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..a992231bec47695d6314067692c0d5d3c3e8b5d3 --- /dev/null +++ b/test/unittest/UTTest_dm_comm_tool.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_UTTEST_DM_COMM_TOOL_H +#define OHOS_UTTEST_DM_COMM_TOOL_H + +#include +#include +#include "dm_comm_tool.h" + +namespace OHOS { +namespace DistributedHardware { +class DMCommToolTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr dmCommTool; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_COMM_TOOL_H \ No newline at end of file diff --git a/test/unittest/UTTest_dm_crypto.cpp b/test/unittest/UTTest_dm_crypto.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a4710e81c455937403779f29681c1f14c07b230 --- /dev/null +++ b/test/unittest/UTTest_dm_crypto.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_crypto.h" + +#include +#include + +#include "dm_constants.h" +#include "dm_crypto.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + constexpr int32_t SALT_STRING_LENGTH = 16; + const std::string SALT_DEFAULT = "salt_defsalt_def"; + const std::string UDID_SAMPLE = "3fde738fb2b8c910023d949166125bc9ed49e9e2fc8f4826d652b2839def2238"; +} +void DmCryptoTest::SetUp() +{ +} +void DmCryptoTest::TearDown() +{ +} +void DmCryptoTest::SetUpTestCase() +{ +} +void DmCryptoTest::TearDownTestCase() +{ +} + +/** + * @tc.name: GetSecRandom_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetSecRandom_01, testing::ext::TestSize.Level0) +{ + const size_t len = 8; + uint8_t buffer[len] = {0}; + int32_t ret = Crypto::GetSecRandom(buffer, len); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: GetSecSalt_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetSecSalt_01, testing::ext::TestSize.Level0) +{ + std::string salt = Crypto::GetSecSalt(); + EXPECT_EQ(salt.length(), SALT_STRING_LENGTH); + EXPECT_NE(salt, SALT_DEFAULT); + + std::cout << "Random Salt: " << salt << std::endl; +} + +/** + * @tc.name: GetUdidHash_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetUdidHash_01, testing::ext::TestSize.Level0) +{ + char udidHash[DEVICE_UUID_LENGTH] = {0}; + EXPECT_EQ(Crypto::GetUdidHash(UDID_SAMPLE, reinterpret_cast(udidHash)), DM_OK); + + std::string res(udidHash); + std::cout << "udidHash sample: " << res << std::endl; +} + +/** + * @tc.name: GetHashWithSalt_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetHashWithSalt_01, testing::ext::TestSize.Level0) +{ + std::string text1 = "c9ed49e9e2fc8f4826d652b2839d"; + std::string text2 = "aaadfasdfasdfc9ed49e9e2sadfasdffc8f4826d6asdfasdf52basdf2839d"; + std::string salt1 = Crypto::GetSecSalt(); + std::string salt2 = Crypto::GetSecSalt(); + + std::string hash1 = Crypto::GetHashWithSalt(text1, salt1); + std::string hash2 = Crypto::GetHashWithSalt(text1, salt2); + + EXPECT_STRNE(hash1.c_str(), hash2.c_str()); + std::cout << "hash1: " << hash1 << std::endl; + std::cout << "hash2: " << hash2 << std::endl; + + std::string hash3 = Crypto::GetHashWithSalt(text1, salt1); + std::string hash4 = Crypto::GetHashWithSalt(text2, salt1); + EXPECT_STRNE(hash3.c_str(), hash4.c_str()); + std::cout << "hash1: " << hash3 << std::endl; + std::cout << "hash2: " << hash4 << std::endl; + + std::string hash5 = Crypto::GetHashWithSalt(text2, salt1); + EXPECT_STREQ(hash5.c_str(), hash4.c_str()); + std::cout << "hash5: " << hash5 << std::endl; + std::cout << "hash4: " << hash4 << std::endl; + + std::string hash6 = Crypto::GetHashWithSalt(text1, salt2); + EXPECT_STREQ(hash2.c_str(), hash6.c_str()); + + std::cout << "hash2: " << hash2 << std::endl; + std::cout << "hash6: " << hash6 << std::endl; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_crypto.h b/test/unittest/UTTest_dm_crypto.h new file mode 100644 index 0000000000000000000000000000000000000000..5f709cb33fb396222cb6a719eec2f648616772ee --- /dev/null +++ b/test/unittest/UTTest_dm_crypto.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_UTTEST_DM_CRYPTO_H +#define OHOS_UTTEST_DM_CRYPTO_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class DmCryptoTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_CRYPTO_H \ No newline at end of file diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index f66bfbe80d67b07b2d4c5e8ad8b200e6780cae41..ea1a4a52a9ae4658abf09ee75a204b199b5714e2 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -19,6 +19,7 @@ #include #include "accesstoken_kit.h" #include "device_manager_notify.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "ipc_authenticate_device_req.h" @@ -31,8 +32,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -191,7 +190,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_102, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = ""; + pinHolder->processInfo_.pkgName = ""; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -204,7 +204,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_103, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = "dmtest"; + pinHolder->processInfo_.pkgName = "dmtest"; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -223,7 +224,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_105, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -242,7 +244,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_106, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->listener_ = nullptr; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -262,7 +265,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_107, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->session_ = nullptr; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -282,7 +286,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_108, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->sourceState_ = SOURCE_CREATE; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -337,7 +342,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_103, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = ""; + pinHolder->processInfo_.pkgName = ""; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -355,7 +361,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_104, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = "dmtest"; + pinHolder->processInfo_.pkgName = "dmtest"; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -373,7 +380,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_105, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -391,7 +399,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_106, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->sessionId_ = 0; pinHolder->sourceState_ = SOURCE_DESTROY; pinHolder->listener_ = std::make_shared(); @@ -451,7 +460,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -462,7 +471,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -474,7 +483,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -484,7 +493,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_101, testing::ext::TestSize.Level std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -495,7 +504,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_102, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->listener_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -507,7 +516,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_103, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -519,7 +528,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_104, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -550,7 +559,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -561,7 +570,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -573,7 +582,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -595,7 +604,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_101, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -607,7 +616,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_102, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -619,7 +628,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_103, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -631,7 +640,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_104, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -644,7 +653,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_105, testing::ext::TestSize.Level0) int32_t data = 300; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = data; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -789,6 +798,37 @@ HWTEST_F(DmPinHolderTest, SendData_103, testing::ext::TestSize.Level0) )"; int32_t ret = pinHolderSession->SendData(sessionId, message); EXPECT_NE(ret, DM_OK); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->session_ = nullptr; + pinHolder->ProcessChangeMsg(message); + + message = R"( + { + "MSG_TYPE" : 100 + }} + )"; + pinHolder->session_ = std::make_shared(); + pinHolder->ProcessChangeMsg(message); + + message = R"( + { + "MSG_TYPE" : 100 + } + )"; + pinHolder->ProcessChangeMsg(message); + + message = R"( + { + "PIN_TYPE" : 12 + } + )"; + pinHolder->sinkState_ = PinHolderState::SINK_INIT; + pinHolder->ProcessChangeMsg(message); + + pinHolder->sinkState_ = PinHolderState::SINK_CREATE; + pinHolder->ProcessChangeMsg(message); } HWTEST_F(DmPinHolderTest, GetAddrByTargetId_101, testing::ext::TestSize.Level0) @@ -804,6 +844,84 @@ HWTEST_F(DmPinHolderTest, GetAddrByTargetId_101, testing::ext::TestSize.Level0) ConnectionAddr addr; int32_t ret = pinHolderSession->GetAddrByTargetId(targetId, addr); EXPECT_EQ(ret, DM_OK); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + std::string message = R"( + { + "MSG_TYPE" : 100 + }} + )"; + pinHolder->ProcessChangeRespMsg(message); + + message = R"( + { + "MSG_TYPE" : 100 + } + )"; + pinHolder->ProcessChangeRespMsg(message); + + message = R"( + { + "REPLY" : 10 + } + )"; + pinHolder->session_ = nullptr; + pinHolder->ProcessChangeRespMsg(message); + + pinHolder->session_ = std::make_shared(); + pinHolder->ProcessChangeRespMsg(message); + + message = R"( + { + "REPLY" : 0 + } + )"; + pinHolder->ProcessChangeRespMsg(message); +} + +HWTEST_F(DmPinHolderTest, NotifyPinHolderEvent_102, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + std::string pkgName = "com.ohos.dmtest"; + std::string event = "event"; + pinHolder->session_ = nullptr; + int32_t ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + pinHolder->session_ = std::make_shared(); + pinHolder->processInfo_.pkgName = ""; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + pinHolder->processInfo_.pkgName = "pkgName"; + pkgName = "pkgName"; + pinHolder->sessionId_ = -1; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + pinHolder->sessionId_ = 0; + pinHolder->isRemoteSupported_ = false; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); + + pinHolder->isRemoteSupported_ = true; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + if (pinHolder->timer_ == nullptr) { + pinHolder->timer_ = std::make_shared(); + } + nlohmann::json jsonObj; + jsonObj[TAG_MSG_TYPE] = 1; + jsonObj[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; + event = jsonObj.dump(); + if (pinHolder->session_ == nullptr) { + pinHolder->session_ = std::make_shared(); + } + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 12ca2716ed4ca0262a54fe87fb833ecb06eba2f1..5fcd67186ec31678065e9741333fa786adfc5e8e 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -23,6 +23,7 @@ #include #include "mock/mock_ipc_client_proxy.h" #include "device_manager.h" +#include "dm_device_info.h" #include "dm_single_instance.h" #include "idevice_manager_service_listener.h" @@ -60,37 +61,31 @@ public: { } - void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) override + void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info) override { - (void)pkgName; + (void)processInfo; (void)state; (void)info; } - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) override - { - (void)pkgName; - (void)subscribeId; - (void)info; - } - - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) override + void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) override { - (void)pkgName; + (void)processInfo; (void)subscribeId; (void)info; } - void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) override + void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) override { - (void)pkgName; + (void)processInfo; (void)subscribeId; (void)failedReason; } - void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) override + void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) override { - (void)pkgName; + (void)processInfo; (void)subscribeId; } @@ -101,84 +96,132 @@ public: (void)publishResult; } - void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, - int32_t reason) override + void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) override { - (void)pkgName; + (void)processInfo; (void)deviceId; (void)token; (void)status; (void)reason; } - void OnUiCall(std::string &pkgName, std::string ¶mJson) override + void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) override { - (void)pkgName; + (void)processInfo; (void)paramJson; } - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override { - (void)pkgName; + (void)processInfo; (void)action; (void)resultInfo; } - void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, + void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override { - (void)pkgName; + (void)processInfo; (void)targetId; (void)result; (void)status; (void)content; } - void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) override { - (void)pkgName; + (void)processInfo; (void)targetId; (void)result; (void)content; } - void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) override { - (void)pkgName; + (void)processInfo; (void)deviceId; (void)pinType; (void)payload; } - void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) override + void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) override { - (void)pkgName; + (void)processInfo; (void)pinType; (void)payload; } - void OnCreateResult(const std::string &pkgName, int32_t result) override + void OnCreateResult(const ProcessInfo &processInfo, int32_t result) override { - (void)pkgName; + (void)processInfo; (void)result; } - void OnDestroyResult(const std::string &pkgName, int32_t result) override + void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) override { - (void)pkgName; + (void)processInfo; (void)result; } - void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) override { - (void)pkgName; + (void)processInfo; (void)event; (void)result; (void)content; } + + void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override + { + (void)udid; + (void)uuid; + (void)authForm; + } + + void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override + { + (void)processInfo; + (void)devInfo; + } + + void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) override + { + (void)processInfo; + (void)deviceList; + (void)deviceTypeId; + (void)errcode; + } + + void OnAppUnintall(const std::string &pkgName) override + { + (void)pkgName; + } + + void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, + int32_t status, std::string content) override + { + (void)processInfo; + (void)targetId; + (void)result; + (void)status; + (void)content; + } + void OnProcessRemove(const ProcessInfo &processInfo) override + { + (void)processInfo; + } + + virtual void OnDevStateCallbackAdd(const ProcessInfo &processInfo, + const std::vector &deviceList) override + { + (void)processInfo; + (void)deviceList; + } }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_dm_publish_common_event.cpp b/test/unittest/UTTest_dm_publish_common_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fb6144c488da2b4fdc7859f093df73e2507ff78 --- /dev/null +++ b/test/unittest/UTTest_dm_publish_common_event.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_publish_common_event.h" + +#include "bluetooth_def.h" +#include "common_event_support.h" +#include "dm_constants.h" +#include "dm_publish_common_event.h" +#include "matching_skills.h" +#include "system_ability_definition.h" +#include "wifi_msg.h" + +namespace OHOS { +namespace DistributedHardware { +void DmPublishCommonEventManagerTest::SetUp() +{ +} + +void DmPublishCommonEventManagerTest::TearDown() +{ +} + +void DmPublishCommonEventManagerTest::SetUpTestCase() +{ +} + +void DmPublishCommonEventManagerTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(DmPublishCommonEventManagerTest, SubscribePublishCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr publshCommonEventManager + = std::make_shared(); + std::vector publishCommonEventVec; + bool ret = publshCommonEventManager->SubscribePublishCommonEvent(publishCommonEventVec, nullptr); + ASSERT_EQ(ret, false); + publishCommonEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + ret = publshCommonEventManager->SubscribePublishCommonEvent(publishCommonEventVec, nullptr); + ASSERT_EQ(ret, false); +} + +HWTEST_F(DmPublishCommonEventManagerTest, UnsubscribePublishCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr publshCommonEventManager + = std::make_shared(); + bool ret = publshCommonEventManager->UnsubscribePublishCommonEvent(); + ASSERT_EQ(ret, false); + publshCommonEventManager->eventValidFlag_ = true; + ret = publshCommonEventManager->UnsubscribePublishCommonEvent(); + ASSERT_EQ(ret, true); +} + +void PublishCommonEventCallback(int32_t bluetoothState, int32_t wifiState, int32_t screenState) +{ + (void)bluetoothState; + (void)wifiState; + (void)screenState; +} + +HWTEST_F(DmPublishCommonEventManagerTest, OnReceiveEvent_001, testing::ext::TestSize.Level0) +{ + AAFwk::Want want; + EventFwk::CommonEventData data; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + data.SetWant(want); + data.SetCode(0); + std::vector changeEventVec; + changeEventVec.push_back(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + std::string strEvent = "test"; + std::vector strEventVec; + strEventVec.push_back(strEvent); + PublishEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) { + PublishCommonEventCallback(arg1, arg2, arg3); + }; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(strEvent); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + + std::shared_ptr publshCommonEventManager + = std::make_shared(); + publshCommonEventManager->subscriber_ + = std::make_shared(subscriberInfo, callback, strEventVec); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE); + data.SetWant(want); + data.SetCode(static_cast(Bluetooth::BTStateID::STATE_TURN_ON)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + data.SetCode(static_cast(Bluetooth::BTStateID::STATE_TURN_OFF)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + data.SetCode(-1); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_POWER_STATE); + data.SetWant(want); + data.SetCode(static_cast(OHOS::Wifi::WifiState::ENABLED)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + data.SetCode(static_cast(OHOS::Wifi::WifiState::DISABLED)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + EXPECT_NE(publshCommonEventManager->subscriber_->GetSubscriberEventNameVec(), changeEventVec); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_publish_common_event.h b/test/unittest/UTTest_dm_publish_common_event.h new file mode 100644 index 0000000000000000000000000000000000000000..947f02d3243d99466658acff893e7c7bc934e904 --- /dev/null +++ b/test/unittest/UTTest_dm_publish_common_event.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_PUBLISH_COMMON_EVENT_TEST_H +#define OHOS_DM_PUBLISH_COMMON_EVENT_TEST_H + +#include +#include + +#include "dm_publish_common_event.h" + +namespace OHOS { +namespace DistributedHardware { +class DmPublishCommonEventManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_PUBLISH_COMMON_EVENT_TEST_H diff --git a/test/unittest/UTTest_dm_screen_common_event.cpp b/test/unittest/UTTest_dm_screen_common_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a728f55adbb5fb0916b25665c774fa67e16fd2a4 --- /dev/null +++ b/test/unittest/UTTest_dm_screen_common_event.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_screen_common_event.h" + +#include "bluetooth_def.h" +#include "common_event_support.h" +#include "dm_constants.h" +#include "dm_screen_common_event.h" +#include "matching_skills.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +void DmScreenCommonEventManagerTest::SetUp() +{ +} + +void DmScreenCommonEventManagerTest::TearDown() +{ +} + +void DmScreenCommonEventManagerTest::SetUpTestCase() +{ +} + +void DmScreenCommonEventManagerTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(DmScreenCommonEventManagerTest, SubscribeScreenCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr screenCommonEventManager + = std::make_shared(); + std::vector commonEventVec; + bool ret = screenCommonEventManager->SubscribeScreenCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); + commonEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + ret = screenCommonEventManager->SubscribeScreenCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); +} + +HWTEST_F(DmScreenCommonEventManagerTest, UnSubscribeScreenCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr screenCommonEventManager + = std::make_shared(); + bool ret = screenCommonEventManager->UnsubscribeScreenCommonEvent(); + ASSERT_EQ(ret, false); + screenCommonEventManager->eventValidFlag_ = true; + ret = screenCommonEventManager->UnsubscribeScreenCommonEvent(); + ASSERT_EQ(ret, true); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_screen_common_event.h b/test/unittest/UTTest_dm_screen_common_event.h new file mode 100644 index 0000000000000000000000000000000000000000..b1a7b52012daa885f9e64f6b15485a607b03f518 --- /dev/null +++ b/test/unittest/UTTest_dm_screen_common_event.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_SCREEN_COMMON_EVENT_TEST_H +#define OHOS_DM_SCREEN_COMMON_EVENT_TEST_H + +#include +#include + +#include "dm_screen_common_event.h" + +namespace OHOS { +namespace DistributedHardware { +class DmScreenCommonEventManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_SCREEN_COMMON_EVENT_TEST_H diff --git a/test/unittest/UTTest_dm_service_load.cpp b/test/unittest/UTTest_dm_service_load.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bc760ed4ed54efe014d7170bb4d4274e3aabd32 --- /dev/null +++ b/test/unittest/UTTest_dm_service_load.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_service_load.h" + +#include + +#include "dm_constants.h" +#include "dm_service_load.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +void DmServiceLoadTest::SetUp() +{ +} + +void DmServiceLoadTest::TearDown() +{ +} + +void DmServiceLoadTest::SetUpTestCase() +{ +} + +void DmServiceLoadTest::TearDownTestCase() +{ +} + +namespace { +HWTEST_F(DmServiceLoadTest, LoadDMService_001, testing::ext::TestSize.Level0) +{ + int32_t ret = DmServiceLoad::GetInstance().LoadDMService(); + ASSERT_EQ(ret, DM_OK); + ret = DmServiceLoad::GetInstance().LoadDMService(); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceLoadTest, SetLoadFinish_001, testing::ext::TestSize.Level0) +{ + DmServiceLoad::GetInstance().SetLoadFinish(); + int32_t systemAbilityId = 1000; + sptr remoteObject = nullptr; + DMLoadCallbackTest dmLoadCallback; + dmLoadCallback.OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject); + dmLoadCallback.OnLoadSystemAbilityFail(systemAbilityId); + ASSERT_EQ(DmServiceLoad::GetInstance().isDMServiceLoading_, false); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_service_load.h b/test/unittest/UTTest_dm_service_load.h new file mode 100644 index 0000000000000000000000000000000000000000..8787b50dc8c5e9cab21192e8ca69098156d6ffe3 --- /dev/null +++ b/test/unittest/UTTest_dm_service_load.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_SERVICE_LOAD_TEST_H +#define OHOS_DM_SERVICE_LOAD_TEST_H + +#include +#include + +#include "dm_service_load.h" + +namespace OHOS { +namespace DistributedHardware { +class DmServiceLoadTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +class DMLoadCallbackTest : public DMLoadCallback { +public: + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr &remoteObject) {} + void OnLoadSystemAbilityFail(int32_t systemAbilityId) {} +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_SERVICE_LOAD_TEST_H diff --git a/test/unittest/UTTest_dm_transport.cpp b/test/unittest/UTTest_dm_transport.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9b239dd384a2e437c7ec997bdf0a8e14d3a734e --- /dev/null +++ b/test/unittest/UTTest_dm_transport.cpp @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_transport.h" + +namespace OHOS { +namespace DistributedHardware { +void DMTransportTest::SetUp() +{ +} +void DMTransportTest::TearDown() +{ +} +void DMTransportTest::SetUpTestCase() +{ +} +void DMTransportTest::TearDownTestCase() +{ +} + +/** + * @tc.name: CreateClientSocket_InvalidInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, CreateClientSocket_InvalidInput, testing::ext::TestSize.Level0) +{ + std::string rmtNetworkId = ""; + EXPECT_EQ(dmTransport.CreateClientSocket(rmtNetworkId), ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: Init_Success + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Init_Success, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.Init(), ERR_DM_FAILED); +} + +/** + * @tc.name: Init_AlreadyInitialized + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Init_AlreadyInitialized, testing::ext::TestSize.Level0) +{ + dmTransport.Init(); + EXPECT_EQ(dmTransport.Init(), ERR_DM_FAILED); +} + +/** + * @tc.name: UnInit_ShouldShutdownAllSockets + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, UnInit_ShouldShutdownAllSockets, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + dmTransport.StartSocket("device2"); + + EXPECT_EQ(dmTransport.UnInit(), DM_OK); + + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device2", socketId)); +} + +/** + * @tc.name: UnInit_ShouldNotShutdownWhenNoSockets + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, UnInit_ShouldNotShutdownWhenNoSockets, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.UnInit(), DM_OK); +} + +/** + * @tc.name: IsDeviceSessionOpened_ShouldReturnFalseForClosedSession + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, IsDeviceSessionOpened_ShouldReturnFalseForClosedSession, testing::ext::TestSize.Level0) +{ + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device2", socketId)); +} + +/** + * @tc.name: GetRemoteNetworkIdBySocketIdReturnEmptyString + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, GetRemoteNetworkIdBySocketIdReturnEmptyString, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.GetRemoteNetworkIdBySocketId(-1), ""); +} + +/** + * @tc.name: ClearDeviceSocketOpened_ShouldRemoveSocket + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, ClearDeviceSocketOpened_ShouldRemoveSocket, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + dmTransport.ClearDeviceSocketOpened("device1"); + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); +} + +/** + * @tc.name: ClearDeviceSocketOpened_ShouldDoNothingForInvalidId + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, ClearDeviceSocketOpened_ShouldDoNothingForInvalidId, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + dmTransport.ClearDeviceSocketOpened("invalid_device"); + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); +} + +/** + * @tc.name: StartSocket_ShouldCreateSocket + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StartSocket_ShouldCreateSocket, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.StartSocket("device1"), ERR_DM_FAILED); + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); +} + +/** + * @tc.name: StartSocket_ShouldReturnErrorForInvalidId + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StartSocket_ShouldReturnErrorForInvalidId, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.StartSocket(""), ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: StartSocket_ShouldReturnErrorIfAlreadyOpened + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StartSocket_ShouldReturnErrorIfAlreadyOpened, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + EXPECT_EQ(dmTransport.StartSocket("device1"), ERR_DM_FAILED); +} + +/** + * @tc.name: StopSocket_InvalidId_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StopSocket_InvalidId_Failure, testing::ext::TestSize.Level0) +{ + std::string invalidId = "invalidId"; + int32_t result = dmTransport.StopSocket(invalidId); + EXPECT_EQ(result, ERR_DM_FAILED); +} + +/** + * @tc.name: StopSocket_SessionNotOpened_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StopSocket_SessionNotOpened_Failure, testing::ext::TestSize.Level0) +{ + std::string notOpenedId = "notOpenedId"; + int32_t result = dmTransport.StopSocket(notOpenedId); + EXPECT_EQ(result, ERR_DM_FAILED); +} + +/** + * @tc.name: Send_InvalidId_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Send_InvalidId_Failure, testing::ext::TestSize.Level0) +{ + std::string invalidId = "invalidId"; + std::string payload = "Hello, World!"; + int32_t result = dmTransport.Send(invalidId, payload); + EXPECT_EQ(result, ERR_DM_FAILED); +} + +/** + * @tc.name: Send_SessionNotOpened_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Send_SessionNotOpened_Failure, testing::ext::TestSize.Level0) +{ + std::string notOpenedId = "notOpenedId"; + std::string payload = "Hello, World!"; + int32_t result = dmTransport.Send(notOpenedId, payload); + EXPECT_EQ(result, ERR_DM_FAILED); +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport.h b/test/unittest/UTTest_dm_transport.h new file mode 100644 index 0000000000000000000000000000000000000000..fcfebeb98ccde9ec6e074243c95d06f7084d27e1 --- /dev/null +++ b/test/unittest/UTTest_dm_transport.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_UTTEST_DM_TRANSPORT_H +#define OHOS_UTTEST_DM_TRANSPORT_H + +#include +#include +#include +#include "dm_comm_tool.h" +#include "dm_transport.h" + +namespace OHOS { +namespace DistributedHardware { +class DMTransportTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr dmCommTool; + std::shared_ptr dmCommToolPtr = std::make_shared(); + DMTransport dmTransport = DMTransport(dmCommToolPtr); + + int32_t ERR_DM_FAILED = 96929744; + int32_t ERR_DM_INPUT_PARA_INVALID = 96929749; + uint32_t MAX_SEND_MSG_LENGTH = 4 * 1024 * 1024; + int32_t DM_OK = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_TRANSPORT_H \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport_msg.cpp b/test/unittest/UTTest_dm_transport_msg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f74a5b93b55bfee37e85663e069573fe3406639 --- /dev/null +++ b/test/unittest/UTTest_dm_transport_msg.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_dm_transport_msg.h" + +namespace OHOS { +namespace DistributedHardware { +void DMTransportMsgTest::SetUp() +{ +} +void DMTransportMsgTest::TearDown() +{ +} +void DMTransportMsgTest::SetUpTestCase() +{ +} +void DMTransportMsgTest::TearDownTestCase() +{ +} + +/** + * @tc.name: ToJsonAndFromJson + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, ToJsonAndFromJson, testing::ext::TestSize.Level0) +{ + UserIdsMsg userIdsMsg; + userIdsMsg.foregroundUserIds = {1, 2, 3}; + + cJSON *jsonObject = cJSON_CreateObject(); + ToJson(jsonObject, userIdsMsg); + + UserIdsMsg newUserIdsMsg; + FromJson(jsonObject, newUserIdsMsg); + + EXPECT_EQ(newUserIdsMsg.foregroundUserIds.size(), 3); + EXPECT_EQ(newUserIdsMsg.foregroundUserIds[0], 1); + EXPECT_EQ(newUserIdsMsg.foregroundUserIds[1], 2); + EXPECT_EQ(newUserIdsMsg.foregroundUserIds[2], 3); + + cJSON_Delete(jsonObject); + + cJSON *emptyJsonObject = cJSON_CreateObject(); + UserIdsMsg emptyUserIdsMsg; + FromJson(emptyJsonObject, emptyUserIdsMsg); + + EXPECT_EQ(emptyUserIdsMsg.foregroundUserIds.size(), 0); + cJSON_Delete(emptyJsonObject); +} + +/** + * @tc.name: ToJsonAndFromJson01 + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, ToJsonAndFromJson01, testing::ext::TestSize.Level0) +{ + CommMsg commMsg; + commMsg.code = 200; + commMsg.msg = "Success"; + + cJSON *jsonObject = cJSON_CreateObject(); + ToJson(jsonObject, commMsg); + + CommMsg newCommMsg; + FromJson(jsonObject, newCommMsg); + + EXPECT_EQ(newCommMsg.code, 200); + EXPECT_EQ(newCommMsg.msg, "Success"); + + cJSON_Delete(jsonObject); + + cJSON *emptyCommJsonObject = cJSON_CreateObject(); + CommMsg emptyCommMsg; + FromJson(emptyCommJsonObject, emptyCommMsg); + + EXPECT_EQ(emptyCommMsg.code, -1); + EXPECT_EQ(emptyCommMsg.msg, ""); + cJSON_Delete(emptyCommJsonObject); +} + +/** + * @tc.name: PerformanceTest + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, PerformanceTest, testing::ext::TestSize.Level0) +{ + UserIdsMsg userIdsMsg; + for (int i = 0; i < 10000; ++i) { + userIdsMsg.foregroundUserIds.push_back(i); + } + + cJSON *jsonObject = cJSON_CreateObject(); + auto start = std::chrono::high_resolution_clock::now(); + ToJson(jsonObject, userIdsMsg); + auto end = std::chrono::high_resolution_clock::now(); + std::chrono::duration elapsed = end - start; + + EXPECT_LT(elapsed.count(), 1.0); + cJSON_Delete(jsonObject); +} + +/** + * @tc.name: GetCommMsgString_EmptyInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, GetCommMsgString_EmptyInput, testing::ext::TestSize.Level0) +{ + CommMsg commMsg; + std::string result = GetCommMsgString(commMsg); + EXPECT_FALSE(result.empty()); +} + +/** + * @tc.name: ToJson_ValidInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, ToJson_ValidInput, testing::ext::TestSize.Level0) +{ + cJSON *jsonObject = cJSON_CreateObject(); + NotifyUserIds notifyUserIds; + notifyUserIds.remoteUdid = "test_udid"; + notifyUserIds.userIds = {1, 2, 3}; + + ToJson(jsonObject, notifyUserIds); + cJSON *udidItem = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY); + EXPECT_STREQ(udidItem->valuestring, "test_udid"); + cJSON *userIdsArr = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY); + EXPECT_EQ(cJSON_GetArraySize(userIdsArr), 3); +} + +/** + * @tc.name: FromJson_InvalidJson + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, FromJson_InvalidJson, testing::ext::TestSize.Level0) +{ + const char *jsonString = "{\"udid\":123,\"userIds\":\"invalid\"}"; + cJSON *jsonObject = cJSON_Parse(jsonString); + NotifyUserIds notifyUserIds; + + FromJson(jsonObject, notifyUserIds); + EXPECT_TRUE(notifyUserIds.remoteUdid.empty()); + EXPECT_TRUE(notifyUserIds.userIds.empty()); + + cJSON_Delete(jsonObject); +} + +/** + * @tc.name: NotifyUserIds_ToString_ValidInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, NotifyUserIds_ToString_ValidInput, testing::ext::TestSize.Level0) +{ + NotifyUserIds notifyUserIds; + notifyUserIds.remoteUdid = "test_udid"; + notifyUserIds.userIds = {1, 2, 3}; + + std::string result = notifyUserIds.ToString(); + EXPECT_FALSE(result.empty()); +} + +/** + * @tc.name: NotifyUserIds_ToString_EmptyInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, NotifyUserIds_ToString_EmptyInput, testing::ext::TestSize.Level0) +{ + NotifyUserIds notifyUserIds; + std::string result = notifyUserIds.ToString(); + EXPECT_FALSE(result.empty()); +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport_msg.h b/test/unittest/UTTest_dm_transport_msg.h new file mode 100644 index 0000000000000000000000000000000000000000..90a8716d3c0337826fabd29272023b39cadfd3ba --- /dev/null +++ b/test/unittest/UTTest_dm_transport_msg.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_UTTEST_DM_TRANSPORT_MSG_H +#define OHOS_UTTEST_DM_TRANSPORT_MSG_H + +#include +#include +#include "dm_transport_msg.h" + +namespace OHOS { +namespace DistributedHardware { +class DMTransportMsgTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_TRANSPORT_MSG_H \ No newline at end of file diff --git a/test/unittest/UTTest_ipc_client_proxy.cpp b/test/unittest/UTTest_ipc_client_proxy.cpp index a39e3a58e1a9e6449be423c20c9433f1f183610b..666f5f940651d5943852fb46152b525170536a7e 100644 --- a/test/unittest/UTTest_ipc_client_proxy.cpp +++ b/test/unittest/UTTest_ipc_client_proxy.cpp @@ -409,6 +409,10 @@ HWTEST_F(IpcClientProxyTest, SendRequest5, testing::ext::TestSize.Level0) int32_t ret = ipcClientProxy->SendRequest(0, req, rsp); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); + ret = ipcClientProxy->SendRequest(-1, req, rsp); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); + ret = ipcClientProxy->SendRequest(IPC_MSG_SEV, req, rsp); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); } /** @@ -461,6 +465,9 @@ HWTEST_F(IpcClientProxyTest, OnDmServiceDied_002, testing::ext::TestSize.Level0) int32_t ret = ipcClientProxy->OnDmServiceDied(); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); + ipcClientProxy->ipcClientManager_ = nullptr; + ret = ipcClientProxy->OnDmServiceDied(); + ASSERT_EQ(ret, ERR_DM_POINT_NULL); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_ipc_client_server_proxy.cpp b/test/unittest/UTTest_ipc_client_server_proxy.cpp index ac258affd51421dc9720f49ae786d7b8bee688b0..5aed918cd222502c20d206d1700ece10a4e24565 100644 --- a/test/unittest/UTTest_ipc_client_server_proxy.cpp +++ b/test/unittest/UTTest_ipc_client_server_proxy.cpp @@ -28,8 +28,6 @@ #include "ipc_def.h" #include "ipc_types.h" #include "ipc_set_useroperation_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_start_discovery_req.h" namespace OHOS { namespace DistributedHardware { diff --git a/test/unittest/UTTest_ipc_client_stub.cpp b/test/unittest/UTTest_ipc_client_stub.cpp index 752d54f68b7f75faf645deb707d8f7d168a503a3..07492955556e7d090df2e1fb7a522473cf16fabd 100644 --- a/test/unittest/UTTest_ipc_client_stub.cpp +++ b/test/unittest/UTTest_ipc_client_stub.cpp @@ -15,6 +15,7 @@ #include "UTTest_ipc_client_stub.h" +#include #include #include "device_manager.h" @@ -35,6 +36,9 @@ #include "ipc_rsp.h" #include "ipc_def.h" +using namespace testing; +using namespace testing::ext; + namespace OHOS { namespace DistributedHardware { void IpcClientStubTest::SetUp() @@ -47,10 +51,14 @@ void IpcClientStubTest::TearDown() void IpcClientStubTest::SetUpTestCase() { + ipcCmdRegisterMock_ = std::make_shared(); + DmIpcCmdRegister::dmIpcCmdRegister = ipcCmdRegisterMock_; } void IpcClientStubTest::TearDownTestCase() { + DmIpcCmdRegister::dmIpcCmdRegister = nullptr; + ipcCmdRegisterMock_ = nullptr; } namespace { @@ -154,7 +162,7 @@ HWTEST_F(IpcClientStubTest, SendCmd_001, testing::ext::TestSize.Level0) // 2. call IpcClientStub SendCmd with parameter int ret = instance->SendCmd(cmdCode, req, rsp); // 3. check result is ERR_DM_IPC_SEND_REQUEST_FAILED - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ASSERT_EQ(ret, DM_OK); } /** @@ -200,10 +208,29 @@ HWTEST_F(IpcClientStubTest, SendCmd_004, testing::ext::TestSize.Level0) int cmdCode = -1; std::shared_ptr req = nullptr; std::shared_ptr rsp = nullptr; - sptr instance = new IpcClientStub(); + sptr instance = sptr(new IpcClientStub()); int ret = instance->SendCmd(cmdCode, req, rsp); ASSERT_EQ(ret, result); } + +HWTEST_F(IpcClientStubTest, SendCmd_005, testing::ext::TestSize.Level0) +{ + int cmdCode = 1; + std::shared_ptr req = nullptr; + std::shared_ptr rsp = nullptr; + sptr instance = sptr(new IpcClientStub()); + EXPECT_CALL(*ipcCmdRegisterMock_, SetRequest(_, _, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*ipcCmdRegisterMock_, OnIpcCmd(_, _, _)).WillOnce(Return(DM_OK)); + int ret = instance->SendCmd(cmdCode, req, rsp); + ASSERT_EQ(ret, DM_OK); + + req = std::make_shared(); + rsp = std::make_shared(); + EXPECT_CALL(*ipcCmdRegisterMock_, SetRequest(_, _, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*ipcCmdRegisterMock_, OnIpcCmd(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = instance->SendCmd(cmdCode, req, rsp); + ASSERT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_ipc_client_stub.h b/test/unittest/UTTest_ipc_client_stub.h index a73f2ef9215fee2a7a7c38f40a4386f40fbe2b57..04d505804e5b47c4015d682af0ed78b05df202db 100644 --- a/test/unittest/UTTest_ipc_client_stub.h +++ b/test/unittest/UTTest_ipc_client_stub.h @@ -17,9 +17,11 @@ #define OHOS_IPC_CLIENT_STUB_TEST_H #include +#include #include #include "ipc_client_stub.h" +#include "ipc_cmd_register_mock.h" namespace OHOS { namespace DistributedHardware { @@ -29,6 +31,7 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + static inline std::shared_ptr ipcCmdRegisterMock_ = nullptr; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_ipc_cmd_parser_client.cpp b/test/unittest/UTTest_ipc_cmd_parser_client.cpp index 4101bb690bba02c906e115c52a82d1a49530b2e2..f8ed9f05362822dd24e6accf3fe46bcea6ee3c6b 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_client.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_client.cpp @@ -26,8 +26,6 @@ #include "ipc_register_listener_req.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -130,12 +128,6 @@ HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_001, testing::ext::TestSize.Le ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); } -HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_003, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); -} - HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_004, testing::ext::TestSize.Level0) { int32_t cmdCode = UNPUBLISH_DEVICE_DISCOVER; @@ -280,6 +272,42 @@ HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_028, testing::ext::TestSize.Le ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); } +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_029, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SET_DN_POLICY; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_030, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SET_DN_POLICY; + ASSERT_EQ(TestReadResponseRspNotNull(cmdCode), DM_OK); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_031, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SHIFT_LNN_GEAR; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_032, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_SAME_ACCOUNT; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_033, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_ACCESS_CONTROL; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_034, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_API_PERMISSION; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + HWTEST_F(IpcCmdParserClientTest, SetIpcRequestFunc_002, testing::ext::TestSize.Level0) { int32_t cmdCode = GET_NETWORKTYPE_BY_NETWORK; @@ -505,6 +533,23 @@ HWTEST_F(IpcCmdParserClientTest, SetIpcRequestFunc_014, testing::ext::TestSize.L ASSERT_EQ(DM_OK, ret); } +HWTEST_F(IpcCmdParserClientTest, SetIpcRequestFunc_015, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SET_DN_POLICY; + MessageParcel data; + std::shared_ptr req = std::make_shared(); + std::string pkgName = "ohos.dm.test"; + std::string policy = "DM_POLICY_STRATEGY_FOR_BLE:100"; + req->SetPkgName(pkgName); + req->SetFirstParam(policy); + int ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(DM_OK, ret); +} + HWTEST_F(IpcCmdParserClientTest, OnIpcCmdFunc_001, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DEVICE_DISCOVERY; @@ -663,6 +708,25 @@ HWTEST_F(IpcCmdParserClientTest, OnIpcCmdFunc_008, testing::ext::TestSize.Level0 } ASSERT_EQ(ret, DM_OK); } + +HWTEST_F(IpcCmdParserClientTest, OnIpcCmdFunc_009, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = REMOTE_DEVICE_TRUST_CHANGE; + int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; + MessageParcel data; + MessageParcel reply; + std::string pkgName = "ohos.dm.test"; + std::string deviceId = "xxx"; + int32_t authForm = 1; + data.WriteString(pkgName); + data.WriteString(deviceId); + data.WriteInt32(authForm); + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 323b4fd43782188763b42b0169cb2e859f2b8207..e8bd5e2a709bf18b91559b023b3afa14b4c530fb 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -18,32 +18,37 @@ #include #include "device_manager_ipc_interface_code.h" +#include "device_manager_notify.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_device_info.h" #include "ipc_client_manager.h" #include "ipc_cmd_register.h" -#include "ipc_register_listener_req.h" -#include "ipc_get_trustdevice_rsp.h" -#include "ipc_get_info_by_network_rsp.h" +#include "ipc_create_pin_holder_req.h" +#include "ipc_credential_auth_status_req.h" +#include "ipc_destroy_pin_holder_req.h" #include "ipc_get_info_by_network_req.h" -#include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_publish_req.h" -#include "ipc_unpublish_req.h" -#include "ipc_set_useroperation_req.h" -#include "ipc_unauthenticate_device_req.h" -#include "ipc_authenticate_device_req.h" +#include "ipc_get_info_by_network_rsp.h" #include "ipc_get_local_device_info_rsp.h" -#include "ipc_set_credential_req.h" -#include "ipc_set_credential_rsp.h" +#include "ipc_get_trustdevice_req.h" +#include "ipc_get_trustdevice_rsp.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" +#include "ipc_notify_credential_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_dmfa_result_req.h" #include "ipc_notify_event_req.h" -#include "device_manager_notify.h" +#include "ipc_notify_pin_holder_event_req.h" +#include "ipc_notify_publish_result_req.h" +#include "ipc_publish_req.h" +#include "ipc_register_listener_req.h" #include "ipc_req.h" -#include "dm_device_info.h" -#include "dm_constants.h" +#include "ipc_set_credential_req.h" +#include "ipc_set_credential_rsp.h" +#include "ipc_set_useroperation_req.h" +#include "ipc_unauthenticate_device_req.h" +#include "ipc_unpublish_req.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { @@ -270,7 +275,20 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_014, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_008, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_CREDENTIAL_RESULT; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_015, testing::ext::TestSize.Level0) @@ -324,7 +342,22 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_020, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_011, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_CREATE_PIN_HOLDER; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + req->SetPkgName(pkgName); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_021, testing::ext::TestSize.Level0) @@ -342,7 +375,22 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_022, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_012, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DESTROY_PIN_HOLDER; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + req->SetPkgName(pkgName); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_023, testing::ext::TestSize.Level0) @@ -360,7 +408,22 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_024, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_013, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_CREATE_PIN_HOLDER_RESULT; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + req->SetPkgName(pkgName); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_025, testing::ext::TestSize.Level0) @@ -378,7 +441,22 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_026, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_014, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DESTROY_PIN_HOLDER_RESULT; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + req->SetPkgName(pkgName); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_027, testing::ext::TestSize.Level0) @@ -791,79 +869,41 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_025, testing::ext::TestSize.Level int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; MessageParcel data; MessageParcel reply; - std::string pkgName = "ohos.dm.test"; + std::string pkgName = "pkgName"; data.WriteString(pkgName); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); if (ptr) { ret = ptr(data, reply); } ASSERT_EQ(ret, ERR_DM_POINT_NULL); -} -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_026, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = UNREGISTER_DEVICE_MANAGER_LISTENER; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; data.WriteString(pkgName); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); - if (ptr) { - ret = ptr(data, reply); - } - ASSERT_EQ(ret, DM_OK); -} + sptr remoteObject = nullptr; + data.WriteRemoteObject(remoteObject); -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_027, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - std::string extra = ""; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 100; - data.WriteString(pkgName); - data.WriteString(extra); - data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo)); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); if (ptr) { ret = ptr(data, reply); } - ASSERT_EQ(ret, DM_OK); -} + ASSERT_EQ(ret, ERR_DM_POINT_NULL); -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_028, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVERY; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - std::string extra = ""; - uint16_t subscribeId = 100; data.WriteString(pkgName); - data.WriteString(extra); - data.WriteUint16(subscribeId); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + remoteObject = sptr(new IpcClientStub()); + data.WriteRemoteObject(remoteObject); + if (ptr) { ret = ptr(data, reply); } ASSERT_EQ(ret, DM_OK); } -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_029, testing::ext::TestSize.Level0) +HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_026, testing::ext::TestSize.Level0) { - int32_t cmdCode = STOP_DEVICE_DISCOVER; + int32_t cmdCode = UNREGISTER_DEVICE_MANAGER_LISTENER; int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; MessageParcel data; MessageParcel reply; std::string pkgName = "ohos.dm.test"; - uint16_t subscribeId = 100; data.WriteString(pkgName); - data.WriteUint16(subscribeId); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); if (ptr) { ret = ptr(data, reply); @@ -1200,6 +1240,82 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_052, testing::ext::TestSize.Level ASSERT_EQ(ret, DM_OK); } +HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_053, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = IMPORT_CREDENTIAL; + int32_t ret = DM_OK; + MessageParcel data; + MessageParcel reply; + std::string pkgName = "ohos.dm.test"; + nlohmann::json jsonObject; + jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_OH; + jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; + std::string credentialInfo = SafetyDump(jsonObject); + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = DELETE_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr1 = GetIpcCmdFunc(cmdCode); + if (ptr1) { + ret = ptr1(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = REQUEST_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr2 = GetIpcCmdFunc(cmdCode); + if (ptr2) { + ret = ptr2(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_054, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = IMPORT_CREDENTIAL; + int32_t ret = DM_OK; + MessageParcel data; + MessageParcel reply; + std::string pkgName = "ohos.dm.test"; + nlohmann::json jsonObject; + jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_MINE; + jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; + std::string credentialInfo = SafetyDump(jsonObject); + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = DELETE_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr1 = GetIpcCmdFunc(cmdCode); + if (ptr1) { + ret = ptr1(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = REQUEST_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr2 = GetIpcCmdFunc(cmdCode); + if (ptr2) { + ret = ptr2(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} + HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_016, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DEVICE_DISCOVERY; @@ -1302,6 +1418,93 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_020, testing::ext::TestSize. } ASSERT_EQ(DM_OK, ret); } + +HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_021, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVER_ON_PIN_HOLDER_EVENT; + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + req->SetPkgName(pkgName); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_029, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVER_ON_PIN_HOLDER_EVENT; + ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); +} + +HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_055, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_ACCESS_CONTROL; + int32_t ret = DM_OK; + MessageParcel data; + MessageParcel reply; + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = CHECK_SAME_ACCOUNT; + OnIpcCmdFunc ptr1 = GetIpcCmdFunc(cmdCode); + if (ptr1) { + ret = ptr1(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = SHIFT_LNN_GEAR; + OnIpcCmdFunc ptr2 = GetIpcCmdFunc(cmdCode); + if (ptr2) { + ret = ptr2(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY; + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + std::string deviceList = "test"; + uint16_t deviceTypeId = 0x00; + int32_t errcode = -1; + req->SetPkgName(pkgName); + req->SetDeviceList(deviceList); + req->SetDeviceTypeId(deviceTypeId); + req->SetErrCode(errcode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_030, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY; + ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_ipc_cmd_register.cpp b/test/unittest/UTTest_ipc_cmd_register.cpp index 6e20ac4c5a00a5a8f581f049e6e44eda74761a18..912b90eeb69a50eed0aa11fa9725b5864299a7e9 100644 --- a/test/unittest/UTTest_ipc_cmd_register.cpp +++ b/test/unittest/UTTest_ipc_cmd_register.cpp @@ -24,8 +24,6 @@ #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_set_useroperation_req.h" @@ -280,44 +278,6 @@ HWTEST_F(IpcCmdRegisterTest, SetRequest_010, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -/** - * @tc.name: SetRequest_011 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, SetRequest_011, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - MessageParcel data; - std::shared_ptr req = std::make_shared(); - std::string pkgName = "ohos.test"; - std::string extra = "1234"; - DmSubscribeInfo dmSubscribeInfo; - req->SetPkgName(pkgName); - req->SetExtra(extra); - req->SetSubscribeInfo(dmSubscribeInfo); - int ret = IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data); - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: SetRequest_012 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, SetRequest_012, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - MessageParcel data; - std::shared_ptr req = std::make_shared(); - std::string pkgName = "ohos.test"; - uint16_t subscribeId = 12; - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int ret = IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data); - ASSERT_EQ(ret, DM_OK); -} - /** * @tc.name: SetRequest_013 * @tc.type: FUNC @@ -643,34 +603,6 @@ HWTEST_F(IpcCmdRegisterTest, ReadResponse_008, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -/** - * @tc.name: ReadResponse_009 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, ReadResponse_009, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - MessageParcel reply; - std::shared_ptr rsp = std::make_shared(); - int ret = IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: ReadResponse_010 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, ReadResponse_010, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - MessageParcel reply; - std::shared_ptr rsp = std::make_shared(); - int ret = IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); - ASSERT_EQ(ret, DM_OK); -} - /** * @tc.name: ReadResponse_011 * @tc.type: FUNC diff --git a/test/unittest/UTTest_ipc_server_client_proxy.cpp b/test/unittest/UTTest_ipc_server_client_proxy.cpp index d987321e3e64fdda68b780e5ee70a38d23e6799f..f37d754c0a3594112360fc20e97847d5dc44dee6 100644 --- a/test/unittest/UTTest_ipc_server_client_proxy.cpp +++ b/test/unittest/UTTest_ipc_server_client_proxy.cpp @@ -95,12 +95,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_002, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null int deviceState = 1; DmDeviceInfo deviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -135,12 +138,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_003, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DEVICE_FOUND; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null uint16_t subscribeId = 1; DmDeviceInfo dmDeviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -175,12 +181,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_004, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DISCOVER_FINISH; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null uint16_t subscribeId = 1; int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -215,12 +224,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_005, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_PUBLISH_FINISH; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null int32_t publishId = 1; int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null diff --git a/test/unittest/UTTest_ipc_server_listener.cpp b/test/unittest/UTTest_ipc_server_listener.cpp index 60d60f42fcf12bedcc019fd4f40637c8e6e74ba8..dfe72c781c2818aa6e08f9929b8e59700dd3957b 100644 --- a/test/unittest/UTTest_ipc_server_listener.cpp +++ b/test/unittest/UTTest_ipc_server_listener.cpp @@ -79,7 +79,7 @@ HWTEST_F(IpcServerListenerTest, SendRequest_001, testing::ext::TestSize.Level0) std::shared_ptr ipcServerListener = std::make_shared(); int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); // 4. check ret is ERR_DM_POINT_NULL - ASSERT_EQ(ret, ERR_DM_POINT_NULL); + ASSERT_NE(ret, DM_OK); } /** @@ -129,9 +129,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_003, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -162,10 +165,13 @@ HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) int32_t cmdCode = 999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); remoteObject = nullptr; - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -176,7 +182,7 @@ HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); // 4. check ret is ERR_DM_INPUT_PARA_INVALID ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); } /** @@ -197,9 +203,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_005, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -230,9 +239,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_006, testing::ext::TestSize.Level0) int32_t cmdCode = 0; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null @@ -263,9 +275,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) int32_t cmdCode = -1; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null @@ -279,87 +294,14 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) } /** - * @tc.name: SendAll_001 - * @tc.desc: 1. set cmdCode -1 - * set req not null - * set rsp not null - * check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_001, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = -1; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); -} - -/** - * @tc.name: SendAll_002 - * @tc.desc: 1. set cmdCode 999 - * set req not null - * set rsp not null - * check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_002, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = 999; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); -} - -/** - * @tc.name: SendAll_003 - * @tc.desc: 1. set cmdCode SERVER_DEVICE_STATE_NOTIFY - * set req not null - * set rsp not null - * check ret is DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_003, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - std::string pkgName = "com.ohos.test"; - sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); - IpcServerStub::GetInstance().dmListener_.clear(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is DM_OK - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GetAllPkgName_001 + * @tc.name: GetAllProcessInfo_001 * @tc.type: FUNC */ -HWTEST_F(IpcServerListenerTest, GetAllPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(IpcServerListenerTest, GetAllProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr ipcServerListener = std::make_shared(); - std::vector pkgName = ipcServerListener->GetAllPkgName(); - ASSERT_NE(pkgName.empty(), false); + std::vector processInfo = ipcServerListener->GetAllProcessInfo(); + ASSERT_NE(processInfo.empty(), true); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp index 587d3dc85d7d8ac4e981f4b42e15f3b709d07143..b4f842e98fe61da8ee172adb5cc28c4ca095f40e 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -87,6 +87,23 @@ HWTEST_F(IpcServerStubTest, OnStart_001, testing::ext::TestSize.Level0) ASSERT_EQ(ServiceRunningState::STATE_RUNNING, IpcServerStub::GetInstance().state_); } +/** + * @tc.name: OnStart_002 + * @tc.desc: 1. Set initial state to STATE_NOT_START + * 2. Call OnStart to start the service + * 3. Call OnStop to stop the service + * 4. Check the final state is STATE_NOT_START + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, OnStart_002, testing::ext::TestSize.Level0) +{ + IpcServerStub::GetInstance().state_ = ServiceRunningState::STATE_NOT_START; + IpcServerStub::GetInstance().OnStart(); + IpcServerStub::GetInstance().OnStop(); + ASSERT_EQ(ServiceRunningState::STATE_NOT_START, IpcServerStub::GetInstance().state_); +} + /** * @tc.name: Init_001 * @tc.desc: 1. Call IpcServerStub OnStart @@ -210,9 +227,12 @@ HWTEST_F(IpcServerStubTest, QueryServiceState_001, testing::ext::TestSize.Level0 HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) { std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = nullptr; - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -226,9 +246,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, DM_OK); } @@ -242,9 +265,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_003, testing::ext::TestSize.Level0) { std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -260,10 +286,13 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_004, testing::ext::Tes { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -275,6 +304,8 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_004, testing::ext::Tes * 3. check ret is DM_OK * 4. Call IpcServerStub RegisterDeviceManagerListener with same pkgName another listener * 5. check result is DM_OK + * 6. earse pkgName for appRecipient_ + * 7. check result is DM_OK * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -282,18 +313,27 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); sptr listener2 = sptr(new IpcClientStub()); // 4. Call IpcServerStub RegisterDeviceManagerListener with same pkgName another listener - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener2); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener2); // 5. check result is DM_OK ASSERT_EQ(result, DM_OK); + sptr listener3 = sptr(new IpcClientStub()); + // 6. earse pkgName for appRecipient_ + IpcServerStub::GetInstance().appRecipient_.erase(processInfo); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener3); + // 7. check result is DM_OK + ASSERT_EQ(result, DM_OK); } /** @@ -305,9 +345,9 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes */ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) { - std::string pkgName; + ProcessInfo processInfo; int ret = 0; - ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -325,15 +365,18 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_002, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); } @@ -350,9 +393,12 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_003, testing::ext::T { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -371,18 +417,21 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_004, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test1"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); - sptr dmListener = IpcServerStub::GetInstance().dmListener_[pkgName]; + sptr dmListener = IpcServerStub::GetInstance().dmListener_[processInfo]; ASSERT_EQ(dmListener, nullptr); } @@ -393,6 +442,8 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_004, testing::ext::T * 3. check ret is DM_OK * 4. Call IpcServerStub UnRegisterDeviceManagerListener * 5. check ret is DM_OK + * 6. Call IpcServerStub UnRegisterDeviceManagerListener + * 7. check ret is DM_OK * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -400,20 +451,26 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_005, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test2"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener std::string testPkgName = "com.test"; - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(testPkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); - sptr dmListener = IpcServerStub::GetInstance().dmListener_[pkgName]; - ASSERT_NE(dmListener, nullptr); + IpcServerStub::GetInstance().appRecipient_.erase(processInfo); + // 6. Call IpcServerStub UnRegisterDeviceManagerListener + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); + // 7. check ret is DM_OK + ASSERT_EQ(result, DM_OK); } /** @@ -427,10 +484,11 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_005, testing::ext::T HWTEST_F(IpcServerStubTest, GetDmListener_001, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test - std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.test"; sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, nullptr); } @@ -447,15 +505,17 @@ HWTEST_F(IpcServerStubTest, GetDmListener_002, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_NE(ret, nullptr); } @@ -472,18 +532,19 @@ HWTEST_F(IpcServerStubTest, GetDmListener_003, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - std::string testPkgName = "test"; - ret = IpcServerStub::GetInstance().GetDmListener(testPkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK - ASSERT_EQ(ret, nullptr); + ASSERT_NE(ret, nullptr); } /** @@ -498,15 +559,17 @@ HWTEST_F(IpcServerStubTest, GetDmListener_004, testing::ext::TestSize.Level0) { // 1. Set pkgName is null std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is ERR_DM_POINT_NULL ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); } @@ -523,15 +586,17 @@ HWTEST_F(IpcServerStubTest, GetDmListener_005, testing::ext::TestSize.Level0) { // 1. Set pkgName is null std::string pkgName = "com.test.ohos"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = nullptr; // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is ERR_DM_POINT_NULL ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); } @@ -554,7 +619,7 @@ HWTEST_F(IpcServerStubTest, OnRemoveSystemAbility_001, testing::ext::TestSize.Le */ HWTEST_F(IpcServerStubTest, OnRemoveSystemAbility_002, testing::ext::TestSize.Level0) { - int32_t systemAbilityId = 9999; + int32_t systemAbilityId = DISTRIBUTED_HARDWARE_SA_ID; std::string deviceId; IpcServerStub::GetInstance().OnRemoveSystemAbility(systemAbilityId, deviceId); ASSERT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); @@ -569,7 +634,8 @@ HWTEST_F(IpcServerStubTest, OnAddSystemAbility_001, testing::ext::TestSize.Level int32_t systemAbilityId = SOFTBUS_SERVER_SA_ID; std::string deviceId; IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); - ASSERT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + ASSERT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + IpcServerStub::GetInstance().OnRemoveSystemAbility(systemAbilityId, deviceId); } /** @@ -581,18 +647,32 @@ HWTEST_F(IpcServerStubTest, OnAddSystemAbility_002, testing::ext::TestSize.Level int32_t systemAbilityId = 9999; std::string deviceId; IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); - ASSERT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + + systemAbilityId = SOFTBUS_SERVER_SA_ID; + IpcServerStub::GetInstance().registerToService_ = false; + IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + systemAbilityId = SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN; + IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + + systemAbilityId = SCREENLOCK_SERVICE_ID; + IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } /** - * @tc.name: GetAllPkgName_001 + * @tc.name: GetAllProcessInfo_001 * @tc.type: FUNC */ -HWTEST_F(IpcServerStubTest, GetAllPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(IpcServerStubTest, GetAllProcessInfo_001, testing::ext::TestSize.Level0) { - std::vector pkgName; - pkgName = IpcServerStub::GetInstance().GetAllPkgName(); - ASSERT_EQ(pkgName.empty(), false); + std::vector processInfo; + processInfo = IpcServerStub::GetInstance().GetAllProcessInfo(); + ASSERT_EQ(processInfo.empty(), false); } /** diff --git a/test/unittest/UTTest_relationship_sync_mgr.cpp b/test/unittest/UTTest_relationship_sync_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de25ec0f67facccfc7adc58dcdc5bcf3c51d5af9 --- /dev/null +++ b/test/unittest/UTTest_relationship_sync_mgr.cpp @@ -0,0 +1,393 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "UTTest_relationship_sync_mgr.h" + +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +void ReleationShipSyncMgrTest::SetUp() +{ +} + +void ReleationShipSyncMgrTest::TearDown() +{ +} + +void ReleationShipSyncMgrTest::SetUpTestCase() +{ +} + +void ReleationShipSyncMgrTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_001, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = UINT32_MAX; + msg.peerUdids = peerUdids; + msg.accountId = "1"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_002, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_003, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_NE(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_004, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEVICE_UNBIND; + msg.userId = UINT32_MAX; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_005, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEVICE_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_NE(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_006, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = UINT32_MAX; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_007, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + msg.tokenId = UINT64_MAX; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_008, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + msg.tokenId = 1; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_NE(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_009, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SERVICE_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + msg.tokenId = 1; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + msg.type = RelationShipChangeType::DEL_USER; + broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + msg.type = RelationShipChangeType::APP_UNINSTALL; + broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + msg.type = RelationShipChangeType::TYPE_MAX; + broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_001, testing::ext::TestSize.Level0) +{ + std::string msg = ""; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_002, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "xx": "xx" + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_003, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "TYPE": "xx" + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_004, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "TYPE": 0 + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + msg = R"( + { + "TYPE": 1 + } + )"; + relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + msg = R"( + { + "TYPE": 2 + } + )"; + relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + msg = R"( + { + "TYPE": 3 + } + )"; + relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_005, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "TYPE": 0, + "VALUE": "" + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToSyncFrontOrBackUserIdPayLoad_ValidInput, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.userIdInfos.push_back({12345, true}); + msg.userIdInfos.push_back({67890, false}); + + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + + bool result = msg.ToSyncFrontOrBackUserIdPayLoad(msgPtr, len); + + ASSERT_TRUE(result); + ASSERT_EQ(len, 5); + ASSERT_EQ(msgPtr[0], 2); + + delete[] msgPtr; + msg.userIdInfos.clear(); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToDelUserPayLoad_ValidInput, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.userId = 12345; + + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + + msg.ToDelUserPayLoad(msgPtr, len); + + ASSERT_EQ(len, DEL_USER_PAYLOAD_LEN); + ASSERT_EQ(msgPtr[0], 0x39); + + delete[] msgPtr; + msg.userIdInfos.clear(); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToSyncFrontOrBackUserIdPayLoad_TooManyUserIds, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + for (int i = 0; i < MAX_USER_ID_NUM + 1; ++i) { + msg.userIdInfos.push_back({i, true}); + } + + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + + bool result = msg.ToSyncFrontOrBackUserIdPayLoad(msgPtr, len); + + ASSERT_FALSE(result); + ASSERT_EQ(msgPtr, nullptr); + msg.userIdInfos.clear(); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToSyncFrontOrBackUserIdPayLoad_LengthExceedsLimit, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.userIdInfos.push_back({12345, true}); + msg.userIdInfos.push_back({67890, false}); + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + bool result = msg.ToSyncFrontOrBackUserIdPayLoad(msgPtr, len); + ASSERT_TRUE(result); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToString_ValidData, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = 12345; + msg.accountId = "account_123"; + msg.tokenId = 67890; + msg.peerUdids = {"udid1", "udid2"}; + msg.peerUdid = "peer_udid"; + msg.accountName = "test_account"; + msg.syncUserIdFlag = true; + msg.userIdInfos = {{true, 111}, {false, 222}}; + + std::string expected = "{ MsgType: " + std::to_string(static_cast(msg.type)) + + ", userId: 12345, accountId: a******3, tokenId: 67890, " + + "peerUdids: [ u******1, u******2 ], peerUdid: p******d, " + + "accountName: t******t, syncUserIdFlag: 1, " + + "userIds: [ { 1, userId: 111 }, { 0, userId: 222 } ] }"; + + EXPECT_EQ(msg.ToString(), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToString_ValidData02, testing::ext::TestSize.Level0) +{ + bool isForeground = true; + std::uint16_t userId = 123; + UserIdInfo userIdInfo(isForeground, userId); + std::string expected = "{ 1, userId: 123 }"; + EXPECT_EQ(userIdInfo.ToString(), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToString_ZeroUserId, testing::ext::TestSize.Level0) +{ + bool isForeground = false; + std::uint16_t userId = 0; + UserIdInfo userIdInfo(isForeground, userId); + + std::string expected = "{ 0, userId: 0 }"; + EXPECT_EQ(userIdInfo.ToString(), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ValidList, testing::ext::TestSize.Level0) +{ + std::vector list = {{true, 1}, {false, 2}}; + std::string expected = "[ { 1, userId: 1 }, { 0, userId: 2 } ]"; + + EXPECT_EQ(GetUserIdInfoList(list), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, EmptyList, testing::ext::TestSize.Level0) +{ + std::vector list; + std::string expected = "[ ]"; + + EXPECT_EQ(GetUserIdInfoList(list), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ValidData, testing::ext::TestSize.Level0) +{ + std::vector remoteUserIdInfos = {{true, 1}, {false, 2}, {true, 3}}; + std::vector foregroundUserIdInfos; + std::vector backgroundUserIdInfos; + + GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos); + + EXPECT_EQ(foregroundUserIdInfos.size(), 2); + EXPECT_EQ(backgroundUserIdInfos.size(), 1); + EXPECT_EQ(foregroundUserIdInfos[0].userId, 1); + EXPECT_EQ(foregroundUserIdInfos[1].userId, 3); + EXPECT_EQ(backgroundUserIdInfos[0].userId, 2); +} + +HWTEST_F(ReleationShipSyncMgrTest, EmptyRemoteList, testing::ext::TestSize.Level0) +{ + std::vector remoteUserIdInfos; + std::vector foregroundUserIdInfos; + std::vector backgroundUserIdInfos; + + GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos); + + EXPECT_TRUE(foregroundUserIdInfos.empty()); + EXPECT_TRUE(backgroundUserIdInfos.empty()); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_relationship_sync_mgr.h b/test/unittest/UTTest_relationship_sync_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..60422d537166821b2fc7f434a12bfbd0ab12a078 --- /dev/null +++ b/test/unittest/UTTest_relationship_sync_mgr.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_RELEATION_SHIP_SYNC_MGR_TEST_H +#define OHOS_RELEATION_SHIP_SYNC_MGR_TEST_H + +#include +#include + +#include "relationship_sync_mgr.h" + +namespace OHOS { +namespace DistributedHardware { +class ReleationShipSyncMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + int32_t FRONT_OR_BACK_USER_FLAG_OFFSET = 7; + int32_t DEL_USER_PAYLOAD_LEN = 2; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_RELEATION_SHIP_SYNC_MGR_TEST_H diff --git a/test/unittest/mock/app_manager_mock.cpp b/test/unittest/mock/app_manager_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02d2abd44583c6e7b52f863886687bc02d4f9072 --- /dev/null +++ b/test/unittest/mock/app_manager_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "app_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(AppManager); +const std::string AppManager::GetAppId() +{ + return DmAppManager::dmAppManager->GetAppId(); +} + +bool AppManager::IsSystemSA() +{ + return DmAppManager::dmAppManager->IsSystemSA(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/app_manager_mock.h b/test/unittest/mock/app_manager_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..7439494b4ff143a030fd27b533cc8732459c8bb1 --- /dev/null +++ b/test/unittest/mock/app_manager_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_APP_MANAGER_MOCK_H +#define OHOS_APP_MANAGER_MOCK_H + +#include +#include + +#include "app_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAppManager { +public: + virtual ~DmAppManager() = default; +public: + virtual std::string GetAppId() = 0; + virtual bool IsSystemSA() = 0; +public: + static inline std::shared_ptr dmAppManager = nullptr; +}; + +class AppManagerMock : public DmAppManager { +public: + MOCK_METHOD(std::string, GetAppId, ()); + MOCK_METHOD(bool, IsSystemSA, ()); +}; +} +} +#endif diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9fccf3ac2d20e138b36775660911e8ce66d0df26 --- /dev/null +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_service_impl_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->StopAuthenticateDevice(pkgName); +} + +int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetBindLevel(pkgName, localUdid, udid, tokenId); +} + +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->UnBindDevice(pkgName, udid, bindLevel); +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetDeviceIdAndUserId(userId, accountId); +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetDeviceIdAndUserId(userId); +} +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t localUserId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetDeviceIdAndBindLevel(localUserId); +} + +std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList(std::string pkgname) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetAppTrustDeviceIdList(pkgname); +} + +int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->UnAuthenticateDevice(pkgName, udid, bindLevel); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..b996fab884ef69456b92422112f84c8c3bb41281 --- /dev/null +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_MANAGER_SERVICE_IMPL_MOCK_H +#define OHOS_DEVICE_MANAGER_SERVICE_IMPL_MOCK_H + +#include +#include + +#include "device_manager_service_impl.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceManagerServiceImpl { +public: + virtual ~DmDeviceManagerServiceImpl() = default; +public: + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; + virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) = 0; + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId) = 0; + virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; + virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname) = 0; + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; +public: + static inline std::shared_ptr dmDeviceManagerServiceImpl = nullptr; +}; + +class DeviceManagerServiceImplMock : public DmDeviceManagerServiceImpl { +public: + MOCK_METHOD(int32_t, StopAuthenticateDevice, (const std::string &)); + MOCK_METHOD(int32_t, GetBindLevel, (const std::string &, const std::string &, const std::string &, uint64_t &)); + MOCK_METHOD(int32_t, UnBindDevice, (const std::string &, const std::string &, int32_t)); + MOCK_METHOD((std::multimap), GetDeviceIdAndUserId, (int32_t, const std::string &)); + MOCK_METHOD((std::multimap), GetDeviceIdAndUserId, (int32_t)); + MOCK_METHOD((std::map), GetDeviceIdAndBindLevel, (int32_t)); + MOCK_METHOD((std::unordered_map), GetAppTrustDeviceIdList, (std::string)); + MOCK_METHOD(int32_t, UnAuthenticateDevice, (const std::string &, const std::string &, int32_t)); +}; +} +} +#endif diff --git a/test/unittest/mock/device_manager_service_mock.cpp b/test/unittest/mock/device_manager_service_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb31d8b4798d2491811f407a3c27ee4ab9bb749f --- /dev/null +++ b/test/unittest/mock/device_manager_service_mock.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_service_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); +bool DeviceManagerService::IsDMServiceImplReady() +{ + return DmDeviceManagerService::dmDeviceManagerService->IsDMServiceImplReady(); +} + +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList) +{ + return DmDeviceManagerService::dmDeviceManagerService->GetTrustedDeviceList(pkgName, deviceList); +} + +bool DeviceManagerService::IsDMServiceAdapterLoad() +{ + return DmDeviceManagerService::dmDeviceManagerService->IsDMServiceAdapterLoad(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_mock.h b/test/unittest/mock/device_manager_service_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..3339012e6317a82802624d296d85570154e61639 --- /dev/null +++ b/test/unittest/mock/device_manager_service_mock.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICE_MANAGER_SERVICE_MOCK_H +#define OHOS_DEVICE_MANAGER_SERVICE_MOCK_H + +#include +#include + +#include "device_manager_service.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceManagerService { +public: + virtual ~DmDeviceManagerService() = default; +public: + virtual bool IsDMServiceImplReady() = 0; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList) = 0; + virtual bool IsDMServiceAdapterLoad() = 0; +public: + static inline std::shared_ptr dmDeviceManagerService = nullptr; +}; + +class DeviceManagerServiceMock : public DmDeviceManagerService { +public: + MOCK_METHOD(bool, IsDMServiceImplReady, ()); + MOCK_METHOD(int32_t, GetTrustedDeviceList, (const std::string &, std::vector &)); + MOCK_METHOD(bool, IsDMServiceAdapterLoad, ()); +}; +} +} +#endif diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f7136e2ec82e379dee2cecc818e44d62a035fdfb --- /dev/null +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "deviceprofile_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DeviceProfileConnector); +std::vector DeviceProfileConnector::GetAllAccessControlProfile() +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->GetAllAccessControlProfile(); +} + +int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleDevUnBindEvent(remoteUserId, remoteUdid, + localUdid); +} + +int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid, const std::string &localUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, + remoteUdid, localUdid); +} + +uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::string requestDeviceId) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->CheckBindType(trustDeviceId, requestDeviceId); +} + +std::map DeviceProfileConnector::GetUserIdAndBindLevel(const std::string &localUdid, + const std::string &peerUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->GetUserIdAndBindLevel(localUdid, peerUdid); +} + +bool DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); +} + +OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAppUnBindEvent(remoteUserId, remoteUdid, + tokenId, localUdid); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..97e22cde69ed73106323139b191a0e51002737cf --- /dev/null +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DEVICEPROFILE_CONNECTOR_MOCK_H +#define OHOS_DEVICEPROFILE_CONNECTOR_MOCK_H + +#include +#include + +#include "deviceprofile_connector.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceProfileConnector { +public: + virtual ~DmDeviceProfileConnector() = default; +public: + virtual std::vector GetAllAccessControlProfile() = 0; + virtual int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid) = 0; + virtual int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid, const std::string &localUdid) = 0; + virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; + virtual std::map GetUserIdAndBindLevel(const std::string &localUdid, + const std::string &peerUdid) = 0; + virtual bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) = 0; + virtual OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) = 0; +public: + static inline std::shared_ptr dmDeviceProfileConnector = nullptr; +}; + +class DeviceProfileConnectorMock : public DmDeviceProfileConnector { +public: + MOCK_METHOD(std::vector, GetAllAccessControlProfile, ()); + MOCK_METHOD(int32_t, HandleDevUnBindEvent, (int32_t, const std::string &, const std::string &)); + MOCK_METHOD(int32_t, HandleAccountLogoutEvent, (int32_t, const std::string &, const std::string &, + const std::string &)); + MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); + MOCK_METHOD((std::map), GetUserIdAndBindLevel, (const std::string &, const std::string &)); + MOCK_METHOD(bool, DeleteAclForAccountLogOut, (const std::string &, int32_t, const std::string &, int32_t)); + MOCK_METHOD((OHOS::DistributedHardware::ProcessInfo), HandleAppUnBindEvent, (int32_t, const std::string &, + int32_t, const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/distributed_device_profile_client_mock.cpp b/test/unittest/mock/distributed_device_profile_client_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f76c9d45142a42348a9c75ed6d8b7b137e8d1141 --- /dev/null +++ b/test/unittest/mock/distributed_device_profile_client_mock.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "distributed_device_profile_client_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedDeviceProfile { +IMPLEMENT_SINGLE_INSTANCE(DistributedDeviceProfileClient); +int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map params, + std::vector& accessControlProfiles) +{ + return DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient->GetAccessControlProfile(params, + accessControlProfiles); +} + +int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) +{ + return DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient->PutAccessControlProfile( + accessControlProfile); +} + +int32_t DistributedDeviceProfileClient::GetAllAccessControlProfile( + std::vector& accessControlProfiles) +{ + return DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient->GetAllAccessControlProfile( + accessControlProfiles); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/distributed_device_profile_client_mock.h b/test/unittest/mock/distributed_device_profile_client_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..740d8ef08d77f75904b16be9915ebdd642bd132c --- /dev/null +++ b/test/unittest/mock/distributed_device_profile_client_mock.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DISTRIBUTED_DEVICE_PROFILE_CLIENT_MOCK_H +#define OHOS_DISTRIBUTED_DEVICE_PROFILE_CLIENT_MOCK_H + +#include +#include + +#include "distributed_device_profile_client.h" + +namespace OHOS { +namespace DistributedDeviceProfile { +class DpDistributedDeviceProfileClient { +public: + virtual ~DpDistributedDeviceProfileClient() = default; +public: + virtual int32_t GetAccessControlProfile(std::map params, + std::vector& accessControlProfiles) = 0; + virtual int32_t PutAccessControlProfile(const AccessControlProfile& accessControlProfile) = 0; + virtual int32_t GetAllAccessControlProfile(std::vector& accessControlProfiles) = 0; +public: + static inline std::shared_ptr dpDistributedDeviceProfileClient = nullptr; +}; + +class DistributedDeviceProfileClientMock : public DpDistributedDeviceProfileClient { +public: + MOCK_METHOD(int32_t, GetAccessControlProfile, ((std::map), + std::vector&)); + MOCK_METHOD(int32_t, PutAccessControlProfile, (const AccessControlProfile&)); + MOCK_METHOD(int32_t, GetAllAccessControlProfile, (std::vector&)); +}; +} +} +#endif diff --git a/test/unittest/mock/dm_crypto_mock.cpp b/test/unittest/mock/dm_crypto_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8b1775e2718255b3249bac31e0230d84571a51e --- /dev/null +++ b/test/unittest/mock/dm_crypto_mock.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_crypto_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t Crypto::GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) +{ + return DmCrypto::dmCrypto->GetAccountIdHash(accountId, accountIdHash); +} + +int32_t Crypto::ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + return DmCrypto::dmCrypto->ConvertUdidHashToAnoyAndSave(appId, udidHash, kvValue); +} + +int32_t Crypto::GetUdidHash(const std::string &udid, unsigned char *udidHash) +{ + return DmCrypto::dmCrypto->GetUdidHash(udid, udidHash); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_crypto_mock.h b/test/unittest/mock/dm_crypto_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..187af59dce65fcfcc9ca09f0f59cf8ad2fe9cf3d --- /dev/null +++ b/test/unittest/mock/dm_crypto_mock.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_CRYPTO_MOCK_H +#define OHOS_DM_CRYPTO_MOCK_H + +#include +#include + +#include "dm_crypto.h" + +namespace OHOS { +namespace DistributedHardware { +class DmCrypto { +public: + virtual ~DmCrypto() = default; +public: + virtual int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) = 0; + virtual int32_t ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) = 0; + virtual int32_t GetUdidHash(const std::string &udid, unsigned char *udidHash) = 0; +public: + static inline std::shared_ptr dmCrypto = nullptr; +}; + +class CryptoMock : public DmCrypto { +public: + MOCK_METHOD(int32_t, GetAccountIdHash, (const std::string &, unsigned char *)); + MOCK_METHOD(int32_t, ConvertUdidHashToAnoyAndSave, (const std::string &, const std::string &, DmKVValue &)); + MOCK_METHOD(int32_t, GetUdidHash, (const std::string &, unsigned char *)); +}; +} +} +#endif diff --git a/test/unittest/mock/dm_device_state_manager_mock.cpp b/test/unittest/mock/dm_device_state_manager_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1625eea98a593a59b55dbeff59de7300c72a411 --- /dev/null +++ b/test/unittest/mock/dm_device_state_manager_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_device_state_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { + +std::string DmDeviceStateManager::GetUdidByNetWorkId(std::string networkId) +{ + return DmDmDeviceStateManager::dmDeviceStateManager->GetUdidByNetWorkId(networkId); +} + +int32_t DmDeviceStateManager::ProcNotifyEvent(const int32_t eventId, const std::string &deviceId) +{ + return DmDmDeviceStateManager::dmDeviceStateManager->ProcNotifyEvent(eventId, deviceId); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_device_state_manager_mock.h b/test/unittest/mock/dm_device_state_manager_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..cc90c2647553434490f0ea70062ac2067ce09eff --- /dev/null +++ b/test/unittest/mock/dm_device_state_manager_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_DEVICE_STATE_MANAGER_MOCK_H +#define OHOS_DM_DEVICE_STATE_MANAGER_MOCK_H + +#include +#include + +#include "dm_device_state_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDmDeviceStateManager { +public: + virtual ~DmDmDeviceStateManager() = default; +public: + virtual std::string GetUdidByNetWorkId(std::string networkId) = 0; + virtual int32_t ProcNotifyEvent(const int32_t eventId, const std::string &deviceId) = 0; +public: + static inline std::shared_ptr dmDeviceStateManager = nullptr; +}; + +class DmDeviceStateManagerMock : public DmDmDeviceStateManager { +public: + MOCK_METHOD(std::string, GetUdidByNetWorkId, (std::string)); + MOCK_METHOD(int32_t, ProcNotifyEvent, (const int32_t, const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/dm_softbus_cache_mock.cpp b/test/unittest/mock/dm_softbus_cache_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7fb8312d1e9dbd2b548c565f01d3e186d2e29c47 --- /dev/null +++ b/test/unittest/mock/dm_softbus_cache_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_softbus_cache_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusCache); +int32_t SoftbusCache::GetUdidByUdidHash(const std::string &udidHash, std::string &udid) +{ + return DmSoftbusCache::dmSoftbusCache->GetUdidByUdidHash(udidHash, udid); +} + +int32_t SoftbusCache::GetUdidFromCache(const char *networkId, std::string &udid) +{ + return DmSoftbusCache::dmSoftbusCache->GetUdidFromCache(networkId, udid); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_softbus_cache_mock.h b/test/unittest/mock/dm_softbus_cache_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..c3df4c21be5d92575a5ffff59930f4dea5f4d51e --- /dev/null +++ b/test/unittest/mock/dm_softbus_cache_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_SOFTBUS_CACHE_MOCK_H +#define OHOS_DM_SOFTBUS_CACHE_MOCK_H + +#include +#include + +#include "dm_softbus_cache.h" + +namespace OHOS { +namespace DistributedHardware { +class DmSoftbusCache { +public: + virtual ~DmSoftbusCache() = default; +public: + virtual int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid) = 0; + virtual int32_t GetUdidFromCache(const char *networkId, std::string &udid) = 0; +public: + static inline std::shared_ptr dmSoftbusCache = nullptr; +}; + +class SoftbusCacheMock : public DmSoftbusCache { +public: + MOCK_METHOD(int32_t, GetUdidByUdidHash, (const std::string &, std::string &)); + MOCK_METHOD(int32_t, GetUdidFromCache, (const char *, std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ead3818e01cc7e26f25fd6da2b55c9671822108a --- /dev/null +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "hichain_auth_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..18df9b831e8c377a4bdc795c48a2b205a82b48e9 --- /dev/null +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_HICHAIN_AUTH_CONNECTOR_MOCK_H +#define OHOS_HICHAIN_AUTH_CONNECTOR_MOCK_H + +#include +#include + +#include "hichain_auth_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmHiChainAuthConnector { +public: + virtual ~DmHiChainAuthConnector() = default; +public: + virtual bool QueryCredential(std::string &localUdid, int32_t osAccountId) = 0; +public: + static inline std::shared_ptr dmHiChainAuthConnector = nullptr; +}; + +class HiChainAuthConnectorMock : public DmHiChainAuthConnector { +public: + MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t)); +}; +} +} +#endif diff --git a/test/unittest/mock/hichain_connector_mock.cpp b/test/unittest/mock/hichain_connector_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..467c16fab414da345c560826cb5d36c84d17d0a0 --- /dev/null +++ b/test/unittest/mock/hichain_connector_mock.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "hichain_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +bool HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &queryParams, + std::vector &groupList) +{ + GroupInfo groupInfo; + groupInfo.groupName = "group1"; + groupInfo.groupId = "123456"; + groupInfo.groupOwner = "sdsd"; + groupInfo.groupType = 1; + groupInfo.groupVisibility = 0; + groupInfo.userId = "82898"; + + GroupInfo groupInfo2; + groupInfo2.groupName = "group2"; + groupInfo2.groupId = "123456"; + groupInfo2.groupOwner = "sdsd"; + groupInfo2.groupType = 1; + groupInfo2.groupVisibility = 0; + groupInfo2.userId = "82898"; + + GroupInfo groupInfo3; + groupInfo3.groupName = "group3"; + groupInfo3.groupId = "123456"; + groupInfo3.groupOwner = "sdsd"; + groupInfo3.groupType = 1; + groupInfo3.groupVisibility = 0; + groupInfo3.userId = "82898"; + + groupList.push_back(groupInfo); + groupList.push_back(groupInfo2); + groupList.push_back(groupInfo3); + return DmHiChainConnector::dmHiChainConnector->GetGroupInfo(userId, queryParams, groupList); +} + +bool HiChainConnector::IsDevicesInP2PGroup(const std::string &hostDevice, const std::string &peerDevice) +{ + return DmHiChainConnector::dmHiChainConnector->IsDevicesInP2PGroup(hostDevice, peerDevice); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/hichain_connector_mock.h b/test/unittest/mock/hichain_connector_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..88b3d1c597980a516680bb395bb038fa75b63d0e --- /dev/null +++ b/test/unittest/mock/hichain_connector_mock.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_HICHAIN_CONNECTOR_MOCK_H +#define OHOS_HICHAIN_CONNECTOR_MOCK_H + +#include +#include + +#include "hichain_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmHiChainConnector { +public: + virtual ~DmHiChainConnector() = default; +public: + virtual bool GetGroupInfo(const int32_t userId, const std::string &queryParams, + std::vector &groupList) = 0; + virtual bool IsDevicesInP2PGroup(const std::string &hostDevice, const std::string &peerDevice) = 0; +public: + static inline std::shared_ptr dmHiChainConnector = nullptr; +}; + +class HiChainConnectorMock : public DmHiChainConnector { +public: + MOCK_METHOD(bool, GetGroupInfo, (const int32_t, const std::string &, std::vector &)); + MOCK_METHOD(bool, IsDevicesInP2PGroup, (const std::string &, const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/ipc_cmd_register_mock.cpp b/test/unittest/mock/ipc_cmd_register_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0094b2a875d842b1f6daab11aa7cd6add21093ce --- /dev/null +++ b/test/unittest/mock/ipc_cmd_register_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_cmd_register_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); +int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) +{ + return DmIpcCmdRegister::dmIpcCmdRegister->SetRequest(cmdCode, pBaseReq, data); +} + +int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply) +{ + return DmIpcCmdRegister::dmIpcCmdRegister->OnIpcCmd(cmdCode, data, reply); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/ipc_cmd_register_mock.h b/test/unittest/mock/ipc_cmd_register_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..499b0b62bd00c50153c27a4075fff52126f9773a --- /dev/null +++ b/test/unittest/mock/ipc_cmd_register_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_IPC_CMD_REGISTER_MOCK_H +#define OHOS_IPC_CMD_REGISTER_MOCK_H + +#include +#include + +#include "ipc_cmd_register.h" + +namespace OHOS { +namespace DistributedHardware { +class DmIpcCmdRegister { +public: + virtual ~DmIpcCmdRegister() = default; +public: + virtual int32_t SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) = 0; + virtual int32_t OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply) = 0; +public: + static inline std::shared_ptr dmIpcCmdRegister = nullptr; +}; + +class IpcCmdRegisterMock : public DmIpcCmdRegister { +public: + MOCK_METHOD(int32_t, SetRequest, (int32_t, std::shared_ptr, MessageParcel &)); + MOCK_METHOD(int32_t, OnIpcCmd, (int32_t, MessageParcel &, MessageParcel &)); +}; +} +} +#endif diff --git a/test/unittest/mock/ipc_server_listener.cpp b/test/unittest/mock/ipc_server_listener.cpp index 0c70d88ae3fc91240cf0d0bdfc622a50a0ff2f4d..4db0579fd045df0da1efd4e3da1164e02ff80d58 100644 --- a/test/unittest/mock/ipc_server_listener.cpp +++ b/test/unittest/mock/ipc_server_listener.cpp @@ -22,13 +22,5 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req_ = req; return 0; } - -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - (void)cmdCode; - req_ = req; - std::cout << req_->GetPkgName() << "\n"; - return 0; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/ipc_server_listener.h b/test/unittest/mock/ipc_server_listener.h index b3c8e04b948610e1336fd8ef9442628a8aa1a283..74d538f59202a640203cf91336f442f4dbddcf1a 100644 --- a/test/unittest/mock/ipc_server_listener.h +++ b/test/unittest/mock/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,8 @@ #include #include +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -35,18 +37,14 @@ public: * @tc.type: FUNC */ int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Ipc server listener send messages - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); + std::set GetSystemSA(); std::shared_ptr req_; }; } // namespace DistributedHardware diff --git a/test/unittest/mock/kv_adapter_manager_mock.cpp b/test/unittest/mock/kv_adapter_manager_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05de0d040ceff37c8f39bde1e0d813e2efcccf0a --- /dev/null +++ b/test/unittest/mock/kv_adapter_manager_mock.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "kv_adapter_manager_mock.h" +#include "app_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(KVAdapterManager); +int32_t KVAdapterManager::Get(const std::string &key, DmKVValue &value) +{ + return DmKVAdapterManager::dmKVAdapterManager->Get(key, value); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/kv_adapter_manager_mock.h b/test/unittest/mock/kv_adapter_manager_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..f88b89b1f9cb7af5cdae2b43b2843cf7a36d1267 --- /dev/null +++ b/test/unittest/mock/kv_adapter_manager_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_KV_ADAPTER_MANAGER_MOCK_H +#define OHOS_KV_ADAPTER_MANAGER_MOCK_H + +#include +#include + +#include "kv_adapter_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmKVAdapterManager { +public: + virtual ~DmKVAdapterManager() = default; +public: + virtual int32_t Get(const std::string &key, DmKVValue &value) = 0; +public: + static inline std::shared_ptr dmKVAdapterManager = nullptr; +}; + +class KVAdapterManagerMock : public DmKVAdapterManager { +public: + MOCK_METHOD(int32_t, Get, (const std::string &, DmKVValue &)); +}; +} +} +#endif diff --git a/test/unittest/mock/mine_hichain_connector_mock.cpp b/test/unittest/mock/mine_hichain_connector_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3b6e9f17e56868b6bad4abdaa8740c65877f61f --- /dev/null +++ b/test/unittest/mock/mine_hichain_connector_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "mine_hichain_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int MineHiChainConnector::ImportCredential(std::string reqJsonStr, std::string &returnJsonStr) +{ + return DmMineHiChainConnector::dmMineHiChainConnector->ImportCredential(reqJsonStr, returnJsonStr); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/mine_hichain_connector_mock.h b/test/unittest/mock/mine_hichain_connector_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..01aabe9ef3a40031ed58a2c73f55ea497abbb1f1 --- /dev/null +++ b/test/unittest/mock/mine_hichain_connector_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_MINE_HICHAIN_CONNECTOR_MOCK_H +#define OHOS_MINE_HICHAIN_CONNECTOR_MOCK_H + +#include +#include + +#include "mine_hichain_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmMineHiChainConnector { +public: + virtual ~DmMineHiChainConnector() = default; +public: + virtual int ImportCredential(std::string reqJsonStr, std::string &returnJsonStr) = 0; +public: + static inline std::shared_ptr dmMineHiChainConnector = nullptr; +}; + +class MineHiChainConnectorMock : public DmMineHiChainConnector { +public: + MOCK_METHOD(int, ImportCredential, (std::string, std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index 2b2c4e314b905a06b96d1d3df8532d65fc9ed3f8..b2d2b28e6909777c19ee94e5c3b732b9d070ac41 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -273,6 +273,1350 @@ void AddAccessControlProfileFifth(std::vector& accessContr accessControlProfiles.push_back(profileFifth); } +void AddAccessControlProfileSixth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 2; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileSeventh(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 2; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(oldAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileEighth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileNinth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileEleventh(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwelfth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlprofileThirteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileFourteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileFifteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileSixteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceId"; + + std::string deviceIdee = "deviceIdee"; + int32_t userIdee = 456; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdee); + accessee.SetAccesseeUserId(userIdee); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileSeventeenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 0; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIdee"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileEightteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceId"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileNineteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 2; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIder"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileTwentieth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIder"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileTwentyfirst(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIdacce"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileTwentysecond(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 0; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIdacce"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlProfileTwentythree(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(0); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentyForth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentyFifth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentySixth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 0; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentySeventh(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 0; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceId = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentyEighth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 3; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentyNinth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 3; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1002; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileThirtieth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1002; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(0); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfilethirtyfirst(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1002; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -302,12 +1646,57 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map& accessControlProfiles) { + AddAccessControlProfileTwelfth(accessControlProfiles); + AddAccessControlprofileThirteenth(accessControlProfiles); + AddAccessControlprofileFourteenth(accessControlProfiles); + AddAccessControlprofileFifteenth(accessControlProfiles); + AddAccessControlprofileSixteenth(accessControlProfiles); + AddAccessControlprofileSeventeenth(accessControlProfiles); + AddAccessControlprofileEightteenth(accessControlProfiles); + AddAccessControlprofileNineteenth(accessControlProfiles); + AddAccessControlprofileTwentieth(accessControlProfiles); + AddAccessControlprofileTwentyfirst(accessControlProfiles); + AddAccessControlprofileTwentysecond(accessControlProfiles); + AddAccessControlProfileTwentythree(accessControlProfiles); + AddAccessControlProfileTwentyForth(accessControlProfiles); + AddAccessControlProfileTwentyFifth(accessControlProfiles); + AddAccessControlProfileTwentySixth(accessControlProfiles); + AddAccessControlProfileTwentySeventh(accessControlProfiles); + AddAccessControlProfileTwentyEighth(accessControlProfiles); + AddAccessControlProfileTwentyNinth(accessControlProfiles); + AddAccessControlProfileThirtieth(accessControlProfiles); + AddAccessControlProfilethirtyfirst(accessControlProfiles); return 0; } @@ -358,13 +1747,13 @@ int32_t DistributedDeviceProfileClient::GetCharacteristicProfile(const std::stri } int32_t DistributedDeviceProfileClient::DeleteServiceProfile(const std::string& deviceId, - const std::string& serviceName) + const std::string& serviceName, bool isMultiUser, int32_t userId) { return 0; } int32_t DistributedDeviceProfileClient::DeleteCharacteristicProfile(const std::string& deviceId, - const std::string& serviceName, const std::string& characteristicKey) + const std::string& serviceName, const std::string& characteristicKey, bool isMultiUser, int32_t userId) { return 0; } diff --git a/test/unittest/mock/multiple_user_connector_mock.cpp b/test/unittest/mock/multiple_user_connector_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..480c1c93748d0cb94d63b08b5e06c0cfc88745ce --- /dev/null +++ b/test/unittest/mock/multiple_user_connector_mock.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "multiple_user_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t MultipleUserConnector::GetCurrentAccountUserID(void) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetCurrentAccountUserID(); +} + +int32_t MultipleUserConnector::GetFirstForegroundUserId(void) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetFirstForegroundUserId(); +} + +DMAccountInfo MultipleUserConnector::GetAccountInfoByUserId(int32_t userId) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetAccountInfoByUserId(userId); +} + +int32_t MultipleUserConnector::GetBackgroundUserIds(std::vector &userIdVec) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetBackgroundUserIds(userIdVec); +} + +int32_t MultipleUserConnector::GetForegroundUserIds(std::vector &userVec) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetForegroundUserIds(userVec); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/multiple_user_connector_mock.h b/test/unittest/mock/multiple_user_connector_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..e29fa2e0e2bffc82c51015e2862a7fd7bbee243f --- /dev/null +++ b/test/unittest/mock/multiple_user_connector_mock.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_MULTIPLE_USER_CONNECTOR_MOCK_H +#define OHOS_MULTIPLE_USER_CONNECTOR_MOCK_H + +#include +#include + +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmMultipleUserConnector { +public: + virtual ~DmMultipleUserConnector() = default; +public: + virtual int32_t GetCurrentAccountUserID(void) = 0; + virtual int32_t GetFirstForegroundUserId(void) = 0; + virtual DMAccountInfo GetAccountInfoByUserId(int32_t userId) = 0; + virtual int32_t GetBackgroundUserIds(std::vector &userIdVec) = 0; + virtual int32_t GetForegroundUserIds(std::vector &userVec) = 0; +public: + static inline std::shared_ptr dmMultipleUserConnector = nullptr; +}; + +class MultipleUserConnectorMock : public DmMultipleUserConnector { +public: + MOCK_METHOD(int32_t, GetCurrentAccountUserID, ()); + MOCK_METHOD(int32_t, GetFirstForegroundUserId, ()); + MOCK_METHOD(DMAccountInfo, GetAccountInfoByUserId, (int32_t)); + MOCK_METHOD(int32_t, GetBackgroundUserIds, (std::vector &)); + MOCK_METHOD(int32_t, GetForegroundUserIds, (std::vector &)); +}; +} +} +#endif diff --git a/test/unittest/mock/permission_manager_mock.cpp b/test/unittest/mock/permission_manager_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df84d7a83949602f527e99583a7b5f30e249b5cb --- /dev/null +++ b/test/unittest/mock/permission_manager_mock.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "permission_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(PermissionManager); +bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &processName) +{ + return DmPermissionManager::dmPermissionManager->CheckProcessNameValidOnPinHolder(processName); +} + +bool PermissionManager::CheckProcessNameValidOnAuthCode(const std::string &processName) +{ + return DmPermissionManager::dmPermissionManager->CheckProcessNameValidOnAuthCode(processName); +} + +int32_t PermissionManager::GetCallerProcessName(std::string &processName) +{ + return DmPermissionManager::dmPermissionManager->GetCallerProcessName(processName); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/permission_manager_mock.h b/test/unittest/mock/permission_manager_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..b5c061e69b7ad9f1fd3b4e3f811e25edd9c4a839 --- /dev/null +++ b/test/unittest/mock/permission_manager_mock.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_PERMISSION_MANAGER_MOCK_H +#define OHOS_PERMISSION_MANAGER_MOCK_H + +#include +#include + +#include "permission_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmPermissionManager { +public: + virtual ~DmPermissionManager() = default; +public: + virtual bool CheckProcessNameValidOnPinHolder(const std::string &processName) = 0; + virtual bool CheckProcessNameValidOnAuthCode(const std::string &processName) = 0; + virtual int32_t GetCallerProcessName(std::string &processName) = 0; +public: + static inline std::shared_ptr dmPermissionManager = nullptr; +}; + +class PermissionManagerMock : public DmPermissionManager { +public: + MOCK_METHOD(bool, CheckProcessNameValidOnPinHolder, (const std::string &)); + MOCK_METHOD(bool, CheckProcessNameValidOnAuthCode, (const std::string &)); + MOCK_METHOD(int32_t, GetCallerProcessName, (std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70351519e868ff9aaaf7bf236db189a510ddf0c8 --- /dev/null +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "softbus_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string &udid) +{ + return DmSoftbusConnector::dmSoftbusConnector->GetUdidByNetworkId(networkId, udid); +} +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +{ + return DmSoftbusConnector::dmSoftbusConnector->CheckIsOnline(targetDeviceId); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..10145e8c52c49506a07f76824e07824f43ae39db --- /dev/null +++ b/test/unittest/mock/softbus_connector_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_SOFTBUS_CONNECTOR_MOCK_H +#define OHOS_SOFTBUS_CONNECTOR_MOCK_H + +#include +#include + +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmSoftbusConnector { +public: + virtual ~DmSoftbusConnector() = default; +public: + virtual int32_t GetUdidByNetworkId(const char *networkId, std::string &udid) = 0; + virtual bool CheckIsOnline(const std::string &targetDeviceId) = 0; +public: + static inline std::shared_ptr dmSoftbusConnector = nullptr; +}; + +class SoftbusConnectorMock : public DmSoftbusConnector { +public: + MOCK_METHOD(int32_t, GetUdidByNetworkId, (const char *, std::string &)); + MOCK_METHOD(bool, CheckIsOnline, (const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/softbus_listener_mock.cpp b/test/unittest/mock/softbus_listener_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16c67e46f269b71aeda0303877b0a6e13c28c5d1 --- /dev/null +++ b/test/unittest/mock/softbus_listener_mock.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "softbus_listener_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId) +{ + return DmSoftbusListener::dmSoftbusListener->ShiftLNNGear(isWakeUp, callerId); +} + +int32_t SoftbusListener::GetUdidByNetworkId(const char *networkId, std::string &udid) +{ + return DmSoftbusListener::dmSoftbusListener->GetUdidByNetworkId(networkId, udid); +} + +int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) +{ + return DmSoftbusListener::dmSoftbusListener->GetDeviceSecurityLevel(networkId, securityLevel); +} + +int32_t SoftbusListener::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info) +{ + return DmSoftbusListener::dmSoftbusListener->GetDeviceInfo(networkId, info); +} + +int32_t SoftbusListener::GetUuidByNetworkId(const char *networkId, std::string &uuid) +{ + return DmSoftbusListener::dmSoftbusListener->GetUuidByNetworkId(networkId, uuid); +} + +int32_t SoftbusListener::GetTargetInfoFromCache(const std::string &deviceId, PeerTargetId &targetId, + ConnectionAddrType &addrType) +{ + return DmSoftbusListener::dmSoftbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); +} + +int32_t SoftbusListener::GetTrustedDeviceList(std::vector &deviceInfoList) +{ + return DmSoftbusListener::dmSoftbusListener->GetTrustedDeviceList(deviceInfoList); +} + +int32_t SoftbusListener::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) +{ + return DmSoftbusListener::dmSoftbusListener->GetLocalDeviceInfo(deviceInfo); +} + +int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) +{ + return DmSoftbusListener::dmSoftbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); +} + +int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus) +{ + return DmSoftbusListener::dmSoftbusListener->GetDeviceScreenStatus(networkId, screenStatus); +} + +int32_t SoftbusListener::GetIPAddrTypeFromCache(const std::string &deviceId, const std::string &ip, + ConnectionAddrType &addrType) +{ + return DmSoftbusListener::dmSoftbusListener->GetIPAddrTypeFromCache(deviceId, ip, addrType); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..81ca4db728176d9d5cdbdb453b6d6e530c89e14b --- /dev/null +++ b/test/unittest/mock/softbus_listener_mock.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_SOFTBUS_LISTENER_MOCK_H +#define OHOS_SOFTBUS_LISTENER_MOCK_H + +#include +#include + +#include "softbus_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DmSoftbusListener { +public: + virtual ~DmSoftbusListener() = default; +public: + virtual int32_t ShiftLNNGear(bool isWakeUp, const std::string &callerId) = 0; + virtual int32_t GetUdidByNetworkId(const char *networkId, std::string &udid) = 0; + virtual int32_t GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) = 0; + virtual int32_t GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info) = 0; + virtual int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid) = 0; + virtual int32_t GetTargetInfoFromCache(const std::string &deviceId, PeerTargetId &targetId, + ConnectionAddrType &addrType) = 0; + virtual int32_t GetTrustedDeviceList(std::vector &deviceInfoList) = 0; + virtual int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) = 0; + virtual int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) = 0; + virtual int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus) = 0; + virtual int32_t GetIPAddrTypeFromCache(const std::string &deviceId, const std::string &ip, + ConnectionAddrType &addrType) = 0; +public: + static inline std::shared_ptr dmSoftbusListener = nullptr; +}; + +class SoftbusListenerMock : public DmSoftbusListener { +public: + MOCK_METHOD(int32_t, ShiftLNNGear, (bool, const std::string &)); + MOCK_METHOD(int32_t, GetUdidByNetworkId, (const char *, std::string &)); + MOCK_METHOD(int32_t, GetDeviceSecurityLevel, (const char *, int32_t &)); + MOCK_METHOD(int32_t, GetDeviceInfo, (const std::string &, DmDeviceInfo &)); + MOCK_METHOD(int32_t, GetUuidByNetworkId, (const char *, std::string &)); + MOCK_METHOD(int32_t, GetTargetInfoFromCache, (const std::string &, PeerTargetId &, ConnectionAddrType &addrType)); + MOCK_METHOD(int32_t, GetTrustedDeviceList, (std::vector &)); + MOCK_METHOD(int32_t, GetLocalDeviceInfo, (DmDeviceInfo &)); + MOCK_METHOD(int32_t, SetLocalDeviceName, (const std::string &, const std::string &)); + MOCK_METHOD(int32_t, GetDeviceScreenStatus, (const char *, int32_t &)); + MOCK_METHOD(int32_t, GetIPAddrTypeFromCache, (const std::string &, const std::string &, ConnectionAddrType &)); +}; +} +} +#endif diff --git a/test/unittest/mock/softbus_session_mock.cpp b/test/unittest/mock/softbus_session_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c657174e59e2ded6d5ea21c61fae41db0927732 --- /dev/null +++ b/test/unittest/mock/softbus_session_mock.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "softbus_session_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) +{ + return DmSoftbusSession::dmSoftbusSession->GetPeerDeviceId(sessionId, peerDevId); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_session_mock.h b/test/unittest/mock/softbus_session_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..732174ef40b77da80c5bd2633e77ab078772c198 --- /dev/null +++ b/test/unittest/mock/softbus_session_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_SOFTBUS_SESSION_MOCK_H +#define OHOS_SOFTBUS_SESSION_MOCK_H + +#include +#include + +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +class DmSoftbusSession { +public: + virtual ~DmSoftbusSession() = default; +public: + virtual int32_t GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) = 0; +public: + static inline std::shared_ptr dmSoftbusSession = nullptr; +}; + +class SoftbusSessionMock : public DmSoftbusSession { +public: + MOCK_METHOD(int32_t, GetPeerDeviceId, (int32_t, std::string &)); +}; +} +} +#endif diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 433c613c5c28d05f2e1204266601e335ac4d7cc5..b3b56d22189334c87df50fdc02472493a7159cf6 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -73,6 +73,7 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "include/crypto", + "include/kvadapter", "include/fwkload/standard", "include/appInfo/standard", "include/timer", @@ -94,9 +95,13 @@ if (defined(ohos_lite)) { } sources = [ + "${common_path}/src/dm_anonymous.cpp", "src/appInfo/standard/app_manager.cpp", "src/crypto/dm_crypto.cpp", "src/dm_random.cpp", + "src/kvadapter/dm_kv_info.cpp", + "src/kvadapter/kv_adapter.cpp", + "src/kvadapter/kv_adapter_manager.cpp", "src/timer/dm_timer.cpp", ] @@ -116,16 +121,23 @@ if (defined(ohos_lite)) { "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "cJSON:cjson", "c_utils:utils", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "ipc:ipc_core", "ipc:ipc_single", "openssl:libcrypto_shared", + "os_account:os_account_innerkits", "samgr:samgr_proxy", ] - public_external_deps = [ "json:nlohmann_json_static" ] + public_external_deps = [ + "bundle_framework:appexecfwk_core", + "json:nlohmann_json_static", + "kv_store:distributeddata_inner", + ] if (support_jsapi) { external_deps += [ "bundle_framework:appexecfwk_core" ] diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index 25e5137003700f46adb05fc04b5f34cd4b965a94..52dc07f81f46dc4b1dd31c525d688e92d1aed12b 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -16,8 +16,8 @@ #ifndef OHOS_DM_LITE_APP_MANAGER_H #define OHOS_DM_LITE_APP_MANAGER_H -#include "dm_single_instance.h" #include +#include "dm_single_instance.h" namespace OHOS { namespace DistributedHardware { @@ -26,6 +26,13 @@ class AppManager { public: const std::string GetAppId(); + void RegisterCallerAppId(const std::string &pkgName); + void UnRegisterCallerAppId(const std::string &pkgName); + int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); + bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t &tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 68feab27a0499ef0601af231010fda16baa5fb58..8f19166a6ac0814eae9da3f72b8a39000933d4d5 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -16,7 +16,13 @@ #ifndef OHOS_DM_APP_MANAGER_H #define OHOS_DM_APP_MANAGER_H +#include +#include #include + +#include "bundle_mgr_interface.h" +#include "event_handler.h" + #include "dm_single_instance.h" namespace OHOS { @@ -26,6 +32,17 @@ class AppManager { public: const std::string GetAppId(); + void RegisterCallerAppId(const std::string &pkgName); + void UnRegisterCallerAppId(const std::string &pkgName); + int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); + bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t &tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId); +private: + bool GetBundleManagerProxy(sptr &bundleManager); + std::mutex appIdMapLock_; + std::map appIdMap_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/crypto/dm_crypto.h b/utils/include/crypto/dm_crypto.h index 0ac12466c847c9b625cb7993a5af539653be314f..52d6f2badffce223177b9f984a803468d1ef99f0 100644 --- a/utils/include/crypto/dm_crypto.h +++ b/utils/include/crypto/dm_crypto.h @@ -16,6 +16,9 @@ #ifndef OHOS_DM_CRYPTO_H #define OHOS_DM_CRYPTO_H #include +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_kv_info.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -27,6 +30,19 @@ public: const char *inBuf, uint32_t inLen); static int32_t GetUdidHash(const std::string &udid, unsigned char *udidHash); static std::string GetGroupIdHash(const std::string &groupId); + static int32_t GetSecRandom(uint8_t *out, size_t outLen); + static std::string GetSecSalt(); + static std::string GetHashWithSalt(const std::string &text, const std::string &salt); + static int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + static int32_t ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue); + static int32_t ConvertUdidHashToAnoyDeviceId(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue); + static int32_t GetAnoyDeviceInfo(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue); + static int32_t ConvertUdidHashToAnoyGenerate(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue); +#endif }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/kvadapter/dm_kv_info.h b/utils/include/kvadapter/dm_kv_info.h new file mode 100644 index 0000000000000000000000000000000000000000..fd96cffcbe015671bcb014503ac38994d82d5b35 --- /dev/null +++ b/utils/include/kvadapter/dm_kv_info.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_KV_INFO_H +#define OHOS_DM_KV_INFO_H + +#include + +namespace OHOS { +namespace DistributedHardware { +const std::string DB_KEY_DELIMITER = "###"; +const std::string UDID_HASH_KEY = "udidHash"; +const std::string APP_ID_KEY = "appID"; +const std::string ANOY_DEVICE_ID_KEY = "anoyDeviceId"; +const std::string SALT_KEY = "salt"; +const std::string LAST_MODIFY_TIME_KEY = "lastModifyTime"; + +typedef struct DmKVValue { + std::string udidHash; + std::string appID; + std::string anoyDeviceId; + std::string salt; + int64_t lastModifyTime; + explicit DmKVValue() : udidHash(""), appID(""), anoyDeviceId(""), salt(""), lastModifyTime(0) {} +} DmKVValue; +void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result); +void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue); +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_KV_INFO_H diff --git a/utils/include/kvadapter/kv_adapter.h b/utils/include/kvadapter/kv_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..0e116398ec70e8c130e46907752490b6345b22f4 --- /dev/null +++ b/utils/include/kvadapter/kv_adapter.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_KV_ADAPTER_H +#define OHOS_DM_KV_ADAPTER_H + +#include +#include +#include +#include +#include +#include +#include + +#include "dm_kv_info.h" +#include "distributed_kv_data_manager.h" +#include "kvstore_death_recipient.h" +#include "kvstore_observer.h" + +namespace OHOS { +namespace DistributedHardware { +class KVAdapter : public DistributedKv::KvStoreDeathRecipient, public std::enable_shared_from_this { +public: + KVAdapter() = default; + virtual ~KVAdapter() = default; + int32_t Init(); + void UnInit(); + int32_t ReInit(); + int32_t Put(const std::string &key, const std::string &value); + int32_t Get(const std::string &key, std::string &value); + int32_t DeleteKvStore(); + int32_t DeleteByAppId(const std::string &appId, const std::string &prefix); + int32_t DeleteBatch(const std::vector &keys); + void OnRemoteDied() override; + +private: + DistributedKv::Status GetLocalKvStorePtr(); + void RegisterKvStoreDeathListener(); + void UnregisterKvStoreDeathListener(); + +private: + DistributedKv::AppId appId_; + DistributedKv::StoreId storeId_; + DistributedKv::DistributedKvDataManager kvDataMgr_; + DistributedKv::DataType dataType_ = DistributedKv::DataType::TYPE_STATICS; + std::shared_ptr kvStorePtr_ = nullptr; + std::mutex kvAdapterMutex_; + std::atomic isInited_ = false; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_KV_ADAPTER_H diff --git a/utils/include/kvadapter/kv_adapter_manager.h b/utils/include/kvadapter/kv_adapter_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..8dacc074cb384dba9268c396280d143fa332ea98 --- /dev/null +++ b/utils/include/kvadapter/kv_adapter_manager.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_KV_ADAPTER_MANAGER_H +#define OHOS_DM_KV_ADAPTER_MANAGER_H + +#include +#include +#include +#include + +#include "dm_single_instance.h" + +#include "kv_adapter.h" + +namespace OHOS { +namespace DistributedHardware { + +class KVAdapterManager { + DM_DECLARE_SINGLE_INSTANCE_BASE(KVAdapterManager); +public: + int32_t Init(); + void UnInit(); + void ReInit(); + int32_t PutByAnoyDeviceId(const std::string &key, const DmKVValue &value); + int32_t Get(const std::string &key, DmKVValue &value); + int32_t DeleteAgedEntry(); + int32_t AppUnintall(const std::string &appId); + +private: + KVAdapterManager() = default; + ~KVAdapterManager() = default; + inline bool IsTimeOut(int64_t sourceTime, int64_t targetTime, int64_t timeOut); + +private: + std::shared_ptr deathRecipient_ = nullptr; + std::shared_ptr kvAdapter_ = nullptr; + std::mutex idCacheMapMtx_; + std::map idCacheMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_KV_ADAPTER_MANAGER_H diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index 950f96fd2a12a2960bfc7e2231389992223cad67..30f9b5c70af49b35f86d212f69faf193e7a30997 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,11 +22,9 @@ #include #include #include -#include -#include -#include +#include -#include "event_handler.h" +#include "ffrt.h" namespace OHOS { namespace DistributedHardware { @@ -39,20 +37,10 @@ constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNego constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* STATE_TIMER_PREFIX = "deviceManagerTimer:stateTimer_"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* SYNC_DELETE_TIMEOUT_TASK = "deviceManagerTimer:syncDelete_"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; using TimerCallback = std::function; -class CommonEventHandler : public AppExecFwk::EventHandler { - public: - CommonEventHandler(const std::shared_ptr &runner); - ~CommonEventHandler() override = default; - - bool PostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); - void RemoveTask(const std::string &name); -}; - class DmTimer { public: DmTimer(); @@ -81,8 +69,8 @@ public: private: mutable std::mutex timerMutex_; - std::unordered_set timerVec_ = {}; - std::shared_ptr eventHandler_; + std::unordered_map timerVec_ = {}; + std::shared_ptr queue_; }; } } diff --git a/utils/include/timer/lite/dm_timer.h b/utils/include/timer/lite/dm_timer.h index 25cd34ba78f0faf648ec1c658f940e497f4bdf79..2718734e2642d21bc14d32aaf28977db87c7dfc5 100644 --- a/utils/include/timer/lite/dm_timer.h +++ b/utils/include/timer/lite/dm_timer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -36,10 +36,8 @@ constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNego constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* STATE_TIMER_PREFIX = "deviceManagerTimer:stateTimer_"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* SYNC_DELETE_TIMEOUT_TASK = "deviceManagerTimer:syncDelete_"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; - constexpr int32_t DELAY_TICK_MILLSECONDS = 1000; typedef std::chrono::steady_clock::time_point timerPoint; typedef std::chrono::steady_clock steadyClock; diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index 4882c3193297259ccefea7379d13977f3c668e59..fd2aeb7680224d250e52d968ad1a809f712d3a05 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -14,6 +14,7 @@ */ #include "app_manager.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { @@ -23,5 +24,49 @@ const std::string AppManager::GetAppId() { return ""; } + +void AppManager::RegisterCallerAppId(const std::string &pkgName) +{ + (void)pkgName; +} + +void AppManager::UnRegisterCallerAppId(const std::string &pkgName) +{ + (void)pkgName; +} + +int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &appId) +{ + (void)pkgName; + (void)appId; + return DM_OK; +} + +bool AppManager::IsSystemSA() +{ + return true; +} + +int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) +{ + (void)isSystemSA; + (void)callerName; + return DM_OK; +} +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t &tokenId) +{ + (void)processName; + (void)tokenId; + return DM_OK; +} + +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId) +{ + (void)userId; + (void)bundleName; + (void)instIndex; + (void)tokenId; + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 188f2fc3eb3e400a414f636838a6ce7ca66bf1ce..11d857f3a67a53987a0104211d040ce7b2028249 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -16,7 +16,15 @@ #include "app_manager.h" #include "accesstoken_kit.h" +#include "if_system_ability_manager.h" #include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "os_account_manager.h" +#include "system_ability_definition.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" using namespace OHOS::Security::AccessToken; @@ -26,17 +34,175 @@ DM_IMPLEMENT_SINGLE_INSTANCE(AppManager); const std::string AppManager::GetAppId() { + std::string appId = ""; AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) { - return ""; + LOGD("The caller is not token_hap."); + return appId; + } + sptr bundleManager = nullptr; + if (!GetBundleManagerProxy(bundleManager)) { + LOGE("get bundleManager failed."); + return appId; + } + if (bundleManager == nullptr) { + LOGE("bundleManager is nullptr."); + return appId; + } + int32_t userId = -1; + if (AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId) != ERR_OK) { + LOGE("GetAppIdByCallingUid QueryActiveOsAccountIds failed."); + return appId; + } + std::string BundleName = ""; + bundleManager->GetNameForUid(IPCSkeleton::GetCallingUid(), BundleName); + AppExecFwk::BundleInfo bundleInfo; + int32_t ret = bundleManager->GetBundleInfoV9( + BundleName, static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO), + bundleInfo, userId); + if (ret != 0) { + LOGE(" GetBundleInfoV9 failed %{public}d.", ret); + return appId; + } + appId = bundleInfo.appId; + return appId; +} + +void AppManager::RegisterCallerAppId(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::string appId = GetAppId(); + if (appId.empty()) { + LOGE("PkgName %{public}s get appid failed.", pkgName.c_str()); + return; + } + LOGI("PkgName %{public}s, appId %{public}s.", pkgName.c_str(), GetAnonyString(appId).c_str()); + std::lock_guard lock(appIdMapLock_); + appIdMap_[pkgName] = appId; +} + +void AppManager::UnRegisterCallerAppId(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + LOGI("PkgName %{public}s.", pkgName.c_str()); + std::lock_guard lock(appIdMapLock_); + if (appIdMap_.find(pkgName) == appIdMap_.end()) { + LOGE("AppIdMap not find pkgName."); + return; + } + appIdMap_.erase(pkgName); +} + +int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &appId) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGD("PkgName %{public}s.", pkgName.c_str()); + std::lock_guard lock(appIdMapLock_); + if (appIdMap_.find(pkgName) == appIdMap_.end()) { + LOGD("AppIdMap not find pkgName."); + return ERR_DM_FAILED; + } + appId = appIdMap_[pkgName]; + return DM_OK; +} + +bool AppManager::GetBundleManagerProxy(sptr &bundleManager) +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + LOGE("GetBundleManagerProxy Failed to get system ability mgr."); + return false; } - HapTokenInfo tokenInfo; - auto result = AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); - if (result != RET_SUCCESS) { - return ""; + sptr remoteObject = + systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + LOGE("GetBundleManagerProxy Failed to get bundle manager service."); + return false; } + bundleManager = iface_cast(remoteObject); + if (bundleManager == nullptr) { + LOGE("bundleManager is nullptr"); + return false; + } + return true; +} - return tokenInfo.appID; +bool AppManager::IsSystemSA() +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("IsSystemSA GetCallingTokenID error."); + return false; + } + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + return true; + } + return false; +} + +int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("GetCallingTokenID error."); + return ERR_DM_FAILED; + } + LOGI("tokenCaller ID == %{public}s", GetAnonyInt32(tokenCaller).c_str()); + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_HAP) { + isSystemSA = false; + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenCaller, tokenInfo) != EOK) { + LOGE("GetHapTokenInfo failed."); + return ERR_DM_FAILED; + } + callerName = std::move(tokenInfo.bundleName); + } else if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + isSystemSA = true; + NativeTokenInfo tokenInfo; + if (AccessTokenKit::GetNativeTokenInfo(tokenCaller, tokenInfo) != EOK) { + LOGE("GetNativeTokenInfo failed."); + return ERR_DM_FAILED; + } + callerName = std::move(tokenInfo.processName); + } else { + LOGE("failed, unsupported process."); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t &tokenId) +{ + AccessTokenID nativeTokenId = AccessTokenKit::GetNativeTokenId(processName); + if (nativeTokenId == INVALID_TOKENID) { + LOGE("GetNativeTokenId failed."); + return ERR_DM_FAILED; + } + tokenId = static_cast(nativeTokenId); + return DM_OK; +} + +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId) +{ + auto hapTokenId = AccessTokenKit::GetHapTokenID(userId, bundleName, instIndex); + if (hapTokenId == 0) { + LOGE("GetHapTokenId failed."); + return ERR_DM_FAILED; + } + tokenId = static_cast(hapTokenId); + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/crypto/dm_crypto.cpp b/utils/src/crypto/dm_crypto.cpp index 3e707b21fc32a8c7a38650f89eeef19eb142740f..59bf08e3c1f093a96591b45b3c9eb8821d67616a 100644 --- a/utils/src/crypto/dm_crypto.cpp +++ b/utils/src/crypto/dm_crypto.cpp @@ -14,9 +14,14 @@ */ #include "dm_crypto.h" #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "datetime_ex.h" +#include "kv_adapter_manager.h" +#endif #include #include +#include #include "openssl/sha.h" namespace OHOS { @@ -29,9 +34,16 @@ constexpr int DEC_MAX_NUM = 10; constexpr int HEX_MAX_BIT_NUM = 4; constexpr uint32_t ERR_DM_FAILED = 96929744; constexpr int32_t DM_OK = 0; +constexpr int32_t DM_ERR = -1; constexpr int32_t ERR_DM_INPUT_PARA_INVALID = 96929749; constexpr int HEX_DIGIT_MAX_NUM = 16; constexpr int SHORT_DEVICE_ID_HASH_LENGTH = 16; +constexpr int32_t SALT_LENGTH = 8; +const std::string SALT_DEFAULT = "salt_defsalt_def"; +constexpr int SHORT_ACCOUNTID_ID_HASH_LENGTH = 6; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#define DM_MAX_DEVICE_ID_LEN (97) +#endif uint32_t HexifyLen(uint32_t len) { @@ -161,5 +173,112 @@ std::string Crypto::GetGroupIdHash(const std::string &groupId) } return ss.str().substr(0, SHORT_DEVICE_ID_HASH_LENGTH); } + +int32_t Crypto::GetSecRandom(uint8_t *out, size_t outLen) +{ + if (out == NULL) { + return DM_ERR; + } + + if (outLen == 0) { + return DM_ERR; + } + + RAND_poll(); + RAND_bytes(out, outLen); + return DM_OK; +} + +std::string Crypto::GetSecSalt() +{ + uint8_t out[SALT_LENGTH] = {0}; + if (Crypto::GetSecRandom(out, SALT_LENGTH) != DM_OK) { + return SALT_DEFAULT; + } + + char outHex[SALT_LENGTH * HEX_TO_UINT8 + 1] = {0}; + if (ConvertBytesToHexString(outHex, SALT_LENGTH * HEX_TO_UINT8 + 1, out, SALT_LENGTH) != DM_OK) { + return SALT_DEFAULT; + } + + return std::string(outHex); +} + +std::string Crypto::GetHashWithSalt(const std::string &text, const std::string &salt) +{ + std::string rawText = text + salt; + return Crypto::Sha256(rawText); +} + +int32_t Crypto::GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) +{ + unsigned char hash[SHA256_DIGEST_LENGTH] = ""; + DmGenerateStrHash(accountId.data(), accountId.size(), hash, SHA256_DIGEST_LENGTH, 0); + if (ConvertBytesToHexString(reinterpret_cast(accountIdHash), SHORT_ACCOUNTID_ID_HASH_LENGTH + 1, + reinterpret_cast(hash), SHORT_ACCOUNTID_ID_HASH_LENGTH / HEX_TO_UINT8) != DM_OK) { + LOGE("ConvertBytesToHexString failed."); + return ERR_DM_FAILED; + } + return DM_OK; +} + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +int32_t Crypto::ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + if (GetAnoyDeviceInfo(appId, udidHash, kvValue) == DM_OK) { + kvValue.lastModifyTime = GetSecondsSince1970ToNow(); + KVAdapterManager::GetInstance().PutByAnoyDeviceId(kvValue.anoyDeviceId, kvValue); + return DM_OK; + } + int32_t ret = ConvertUdidHashToAnoyGenerate(appId, udidHash, kvValue); + if (ret != DM_OK) { + LOGE("failed"); + return ERR_DM_FAILED; + } + KVAdapterManager::GetInstance().PutByAnoyDeviceId(kvValue.anoyDeviceId, kvValue); + return DM_OK; +} + +int32_t Crypto::ConvertUdidHashToAnoyDeviceId(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + LOGI("start."); + if (GetAnoyDeviceInfo(appId, udidHash, kvValue) == DM_OK) { + return DM_OK; + } + return ConvertUdidHashToAnoyGenerate(appId, udidHash, kvValue); +} + +int32_t Crypto::GetAnoyDeviceInfo(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue) +{ + LOGI("start"); + std::string udidPrefix = appId + DB_KEY_DELIMITER + udidHash; + if (KVAdapterManager::GetInstance().Get(udidPrefix, kvValue) != DM_OK) { + LOGI("Get kv value from DB failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t Crypto::ConvertUdidHashToAnoyGenerate(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + LOGI("start."); + std::string salt = GetSecSalt(); + std::string udidTemp = appId + DB_KEY_DELIMITER + udidHash + DB_KEY_DELIMITER + salt; + char anoyDeviceId[DM_MAX_DEVICE_ID_LEN] = {0}; + if (GetUdidHash(udidTemp, reinterpret_cast(anoyDeviceId)) != DM_OK) { + LOGE("get anoyDeviceId by udidTemp failed."); + return ERR_DM_FAILED; + } + kvValue.udidHash = udidHash; + kvValue.anoyDeviceId = std::string(anoyDeviceId); + kvValue.appID = appId; + kvValue.salt = salt; + kvValue.lastModifyTime = GetSecondsSince1970ToNow(); + return DM_OK; +} +#endif } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/kvadapter/dm_kv_info.cpp b/utils/src/kvadapter/dm_kv_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3197f74d3a612bc5b2b8cf7fda204b6d2cc5be9 --- /dev/null +++ b/utils/src/kvadapter/dm_kv_info.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_kv_info.h" + +#include "cJSON.h" +#include "dm_anonymous.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) +{ + nlohmann::json jsonObj; + jsonObj[UDID_HASH_KEY] = kvValue.udidHash; + jsonObj[APP_ID_KEY] = kvValue.appID; + jsonObj[ANOY_DEVICE_ID_KEY] = kvValue.anoyDeviceId; + jsonObj[SALT_KEY] = kvValue.salt; + jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; + result = SafetyDump(jsonObj); +} + +void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) +{ + if (result.empty()) { + return; + } + nlohmann::json resultJson = nlohmann::json::parse(result, nullptr, false); + if (resultJson.is_discarded()) { + return; + } + if (IsString(resultJson, UDID_HASH_KEY)) { + kvValue.udidHash = resultJson[UDID_HASH_KEY].get(); + } + if (IsString(resultJson, APP_ID_KEY)) { + kvValue.appID = resultJson[APP_ID_KEY].get(); + } + if (IsString(resultJson, ANOY_DEVICE_ID_KEY)) { + kvValue.anoyDeviceId = resultJson[ANOY_DEVICE_ID_KEY].get(); + } + if (IsString(resultJson, SALT_KEY)) { + kvValue.salt = resultJson[SALT_KEY].get(); + } + if (IsInt64(resultJson, LAST_MODIFY_TIME_KEY)) { + kvValue.lastModifyTime = resultJson[LAST_MODIFY_TIME_KEY].get(); + } +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/src/kvadapter/kv_adapter.cpp b/utils/src/kvadapter/kv_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ecb6e2a2bbf9ac749299655284cae968660fb09 --- /dev/null +++ b/utils/src/kvadapter/kv_adapter.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "kv_adapter.h" + +#include +#include +#include + +#include "cJSON.h" +#include "datetime_ex.h" +#include "string_ex.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ffrt.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::DistributedKv; +namespace { + const std::string APP_ID = "distributed_device_manager_service"; + const std::string STORE_ID = "dm_kv_store"; + const std::string DATABASE_DIR = "/data/service/el1/public/database/distributed_device_manager_service"; + const std::string KV_REINIT_THREAD = "reinit_kv_store"; + constexpr uint32_t MAX_BATCH_SIZE = 128; + constexpr int32_t MAX_STRING_LEN = 4096; + constexpr int32_t MAX_INIT_RETRY_TIMES = 20; + constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms +} + +int32_t KVAdapter::Init() +{ + LOGI("Init local DB, dataType: %{public}d", static_cast(dataType_)); + if (isInited_.load()) { + LOGI("Local DB already inited."); + return DM_OK; + } + this->appId_.appId = APP_ID; + this->storeId_.storeId = STORE_ID; + std::lock_guard lock(kvAdapterMutex_); + int32_t tryTimes = MAX_INIT_RETRY_TIMES; + while (tryTimes > 0) { + DistributedKv::Status status = GetLocalKvStorePtr(); + if (status == DistributedKv::Status::SUCCESS && kvStorePtr_) { + LOGI("Init KvStorePtr Success"); + RegisterKvStoreDeathListener(); + isInited_.store(true); + return DM_OK; + } + LOGE("CheckKvStore, left times: %{public}d, status: %{public}d", tryTimes, status); + if (status == DistributedKv::Status::STORE_META_CHANGED || + status == DistributedKv::Status::SECURITY_LEVEL_ERROR || + status == DistributedKv::Status::DATA_CORRUPTED) { + LOGE("init db error, remove and rebuild it"); + DeleteKvStore(); + } + usleep(INIT_RETRY_SLEEP_INTERVAL); + tryTimes--; + } + CHECK_NULL_RETURN(kvStorePtr_, ERR_DM_INIT_FAILED); + isInited_.store(true); + return DM_OK; +} + +void KVAdapter::UnInit() +{ + LOGI("KVAdapter Uninted"); + if (isInited_.load()) { + std::lock_guard lock(kvAdapterMutex_); + CHECK_NULL_VOID(kvStorePtr_); + UnregisterKvStoreDeathListener(); + kvStorePtr_.reset(); + isInited_.store(false); + } +} + +int32_t KVAdapter::ReInit() +{ + LOGI("KVAdapter ReInit"); + UnInit(); + return Init(); +} + +int32_t KVAdapter::Put(const std::string &key, const std::string &value) +{ + if (key.empty() || key.size() > MAX_STRING_LEN || value.empty() || value.size() > MAX_STRING_LEN) { + LOGE("Param is invalid!"); + return ERR_DM_FAILED; + } + DistributedKv::Status status; + { + std::lock_guard lock(kvAdapterMutex_); + CHECK_NULL_RETURN(kvStorePtr_, ERR_DM_POINT_NULL); + + DistributedKv::Key kvKey(key); + DistributedKv::Value kvValue(value); + status = kvStorePtr_->Put(kvKey, kvValue); + } + if (status != DistributedKv::Status::SUCCESS) { + LOGE("Put kv to db failed, ret: %{public}d", status); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t KVAdapter::Get(const std::string &key, std::string &value) +{ + LOGI("Get data by key: %{public}s", GetAnonyString(key).c_str()); + DistributedKv::Key kvKey(key); + DistributedKv::Value kvValue; + DistributedKv::Status status; + { + std::lock_guard lock(kvAdapterMutex_); + CHECK_NULL_RETURN(kvStorePtr_, ERR_DM_POINT_NULL); + status = kvStorePtr_->Get(kvKey, kvValue); + } + if (status != DistributedKv::Status::SUCCESS) { + LOGE("Get data from kv failed, key: %{public}s", GetAnonyString(key).c_str()); + return ERR_DM_FAILED; + } + value = kvValue.ToString(); + return DM_OK; +} + +void KVAdapter::OnRemoteDied() +{ + LOGI("OnRemoteDied, recover db begin"); + auto reInitTask = [this]() { + LOGI("ReInit, storeId:%{public}s", storeId_.storeId.c_str()); + ReInit(); + }; + ffrt::submit(reInitTask); +} + +DistributedKv::Status KVAdapter::GetLocalKvStorePtr() +{ + DistributedKv::Options options = { + .createIfMissing = true, + .encrypt = false, + .autoSync = false, + .securityLevel = DistributedKv::SecurityLevel::S1, + .area = DistributedKv::EL1, + .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION, + .baseDir = DATABASE_DIR + }; + DistributedKv::Status status = kvDataMgr_.GetSingleKvStore(options, appId_, storeId_, kvStorePtr_); + return status; +} + +void KVAdapter::RegisterKvStoreDeathListener() +{ + LOGI("Register syncCompleted listener"); + kvDataMgr_.RegisterKvStoreServiceDeathRecipient(shared_from_this()); +} + +void KVAdapter::UnregisterKvStoreDeathListener() +{ + LOGI("UnRegister death listener"); + kvDataMgr_.UnRegisterKvStoreServiceDeathRecipient(shared_from_this()); +} + +int32_t KVAdapter::DeleteKvStore() +{ + LOGI("Delete KvStore!"); + kvDataMgr_.CloseKvStore(appId_, storeId_); + kvDataMgr_.DeleteKvStore(appId_, storeId_, DATABASE_DIR); + return DM_OK; +} + +int32_t KVAdapter::DeleteByAppId(const std::string &appId, const std::string &prefix) +{ + if (appId.empty()) { + LOGE("appId is empty"); + return ERR_DM_FAILED; + } + std::vector localEntries; + { + std::lock_guard lock(kvAdapterMutex_); + if (kvStorePtr_ == nullptr) { + LOGE("kvStoragePtr_ is null"); + return ERR_DM_POINT_NULL; + } + if (kvStorePtr_->GetEntries(prefix + appId, localEntries) != DistributedKv::Status::SUCCESS) { + LOGE("Get entrys from DB failed."); + return ERR_DM_FAILED; + } + } + std::vector delKeys; + for (const auto &entry : localEntries) { + delKeys.emplace_back(entry.key.ToString()); + DmKVValue kvValue; + ConvertJsonToDmKVValue(entry.value.ToString(), kvValue); + delKeys.emplace_back(prefix + kvValue.anoyDeviceId); + } + return DeleteBatch(delKeys); +} + +int32_t KVAdapter::DeleteBatch(const std::vector &keys) +{ + if (keys.empty()) { + LOGE("keys size(%{public}zu) is invalid!", keys.size()); + return ERR_DM_FAILED; + } + uint32_t keysSize = static_cast(keys.size()); + std::vector> delKeyBatches; + for (uint32_t i = 0; i < keysSize; i += MAX_BATCH_SIZE) { + uint32_t end = (i + MAX_BATCH_SIZE) > keysSize ? keysSize : (i + MAX_BATCH_SIZE); + auto batch = std::vector(keys.begin() + i, keys.begin() + end); + std::vector delKeys; + for (auto item : batch) { + DistributedKv::Key key(item); + delKeys.emplace_back(key); + } + delKeyBatches.emplace_back(delKeys); + } + + { + std::lock_guard lock(kvAdapterMutex_); + if (kvStorePtr_ == nullptr) { + LOGE("kvStorePtr is nullptr!"); + return ERR_DM_POINT_NULL; + } + for (auto delKeys : delKeyBatches) { + DistributedKv::Status status = kvStorePtr_->DeleteBatch(delKeys); + if (status != DistributedKv::Status::SUCCESS) { + LOGE("DeleteBatch failed!"); + return ERR_DM_FAILED; + } + } + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/src/kvadapter/kv_adapter_manager.cpp b/utils/src/kvadapter/kv_adapter_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..617b2e4501e44d6996b15e107067a6f80ee689f1 --- /dev/null +++ b/utils/src/kvadapter/kv_adapter_manager.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "kv_adapter_manager.h" + +#include +#include + +#include "datetime_ex.h" +#include "string_ex.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const std::string DM_KV_STORE_PREFIX = "DM2_"; +constexpr int64_t DM_KV_STORE_REFRESH_TIME = 24 * 60 * 60; // one day +constexpr int64_t MAX_SUPPORTED_EXIST_TIME = 3 * 24 * 60 * 60; // 3days +} + +DM_IMPLEMENT_SINGLE_INSTANCE(KVAdapterManager); + +int32_t KVAdapterManager::Init() +{ + LOGI("Init Kv-Adapter manager"); + { + std::lock_guard lock(idCacheMapMtx_); + idCacheMap_.clear(); + } + kvAdapter_ = std::make_shared(); + return kvAdapter_->Init(); +} + +void KVAdapterManager::UnInit() +{ + LOGI("Uninit Kv-Adapter manager"); + CHECK_NULL_VOID(kvAdapter_); + kvAdapter_->UnInit(); + kvAdapter_ = nullptr; +} + +void KVAdapterManager::ReInit() +{ + LOGI("Re init kv adapter"); + CHECK_NULL_VOID(kvAdapter_); + kvAdapter_->ReInit(); +} + +int32_t KVAdapterManager::PutByAnoyDeviceId(const std::string &key, const DmKVValue &value) +{ + std::string dmKey = DM_KV_STORE_PREFIX + key; + std::lock_guard lock(idCacheMapMtx_); + auto idIter = idCacheMap_.find(dmKey); + if (idIter != idCacheMap_.end() && !IsTimeOut(idIter->second.lastModifyTime, value.lastModifyTime, + DM_KV_STORE_REFRESH_TIME)) { + LOGD("Kv value is existed"); + return DM_OK; + } + idCacheMap_[dmKey] = value; + std::string prefixKey = DM_KV_STORE_PREFIX + value.appID + DB_KEY_DELIMITER + value.udidHash; + idCacheMap_[prefixKey] = value; + std::string valueStr = ""; + ConvertDmKVValueToJson(value, valueStr); + CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); + if (kvAdapter_->Put(dmKey, valueStr) != DM_OK) { + LOGE("Insert value to DB for dmKey failed"); + return ERR_DM_FAILED; + } + if (kvAdapter_->Put(prefixKey, valueStr) != DM_OK) { + LOGE("Insert value to DB for prefixKey failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t KVAdapterManager::Get(const std::string &key, DmKVValue &value) +{ + std::string dmKey = DM_KV_STORE_PREFIX + key; + std::lock_guard lock(idCacheMapMtx_); + auto idIter = idCacheMap_.find(dmKey); + if (idIter != idCacheMap_.end()) { + value = idIter->second; + return DM_OK; + } + CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); + std::string valueStr; + if (kvAdapter_->Get(dmKey, valueStr) != DM_OK) { + LOGE("Get kv value failed, dmKey: %{public}s", GetAnonyString(dmKey).c_str()); + return ERR_DM_FAILED; + } + ConvertJsonToDmKVValue(valueStr, value); + idCacheMap_[dmKey] = value; + std::string prefixKey = DM_KV_STORE_PREFIX + value.appID + DB_KEY_DELIMITER + value.udidHash; + idCacheMap_[prefixKey] = value; + return DM_OK; +} + +int32_t KVAdapterManager::DeleteAgedEntry() +{ + int64_t nowTime = GetSecondsSince1970ToNow(); + std::lock_guard lock(idCacheMapMtx_); + for (auto it = idCacheMap_.begin(); it != idCacheMap_.end();) { + if (IsTimeOut(it->second.lastModifyTime, nowTime, MAX_SUPPORTED_EXIST_TIME)) { + it = idCacheMap_.erase(it); + } else { + ++it; + } + } + return DM_OK; +} + +inline bool KVAdapterManager::IsTimeOut(int64_t sourceTime, int64_t targetTime, int64_t timeOut) +{ + return targetTime - sourceTime >= timeOut ? true : false; +} + +int32_t KVAdapterManager::AppUnintall(const std::string &appId) +{ + LOGI("appId %{public}s.", GetAnonyString(appId).c_str()); + std::lock_guard lock(idCacheMapMtx_); + for (auto it = idCacheMap_.begin(); it != idCacheMap_.end();) { + if (it->second.appID == appId) { + it = idCacheMap_.erase(it); + } else { + ++it; + } + } + CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); + if (kvAdapter_->DeleteByAppId(appId, DM_KV_STORE_PREFIX) != DM_OK) { + LOGE("DeleteByAppId failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index e4288e03de265c8b9bbea511769f132b87748c64..14d87537def4aa15ec360a710a861936269d3b3f 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,31 +19,21 @@ namespace OHOS { namespace DistributedHardware { +namespace { const int32_t MIN_TIME_OUT = 0; const int32_t MAX_TIME_OUT = 300; -const int32_t MILLISECOND_TO_SECOND = 1000; - -CommonEventHandler::CommonEventHandler(const std::shared_ptr &runner) - : AppExecFwk::EventHandler(runner) -{ - LOGI("CommonEventHandler constructor"); -} - -bool CommonEventHandler::PostTask(const Callback &callback, const std::string &name, int64_t delayTime) -{ - return AppExecFwk::EventHandler::PostTask(callback, name, delayTime); -} - -void CommonEventHandler::RemoveTask(const std::string &name) -{ - AppExecFwk::EventHandler::RemoveTask(name); +const int64_t MICROSECOND_TO_SECOND = 1000000L; +constexpr const char* TIMER_TASK = "TimerTask"; } DmTimer::DmTimer() { LOGI("DmTimer constructor"); - std::shared_ptr runner = AppExecFwk::EventRunner::Create(true); - eventHandler_ = std::make_shared(runner); + if (queue_ != nullptr) { + LOGI("Timer is already init."); + return; + } + queue_ = std::make_shared(TIMER_TASK); } DmTimer::~DmTimer() @@ -55,17 +45,20 @@ DmTimer::~DmTimer() int32_t DmTimer::StartTimer(std::string name, int32_t timeOut, TimerCallback callback) { if (name.empty() || timeOut <= MIN_TIME_OUT || timeOut > MAX_TIME_OUT || callback == nullptr) { - LOGI("DmTimer StartTimer input value invalid"); + LOGE("DmTimer StartTimer input value invalid"); return ERR_DM_INPUT_PARA_INVALID; } + CHECK_NULL_RETURN(queue_, ERR_DM_POINT_NULL); LOGI("DmTimer StartTimer start name: %{public}s", name.c_str()); std::lock_guard locker(timerMutex_); - timerVec_.insert(name); auto taskFunc = [callback, name] () { callback(name); }; - if (eventHandler_ != nullptr) { - eventHandler_->PostTask(taskFunc, name, timeOut * MILLISECOND_TO_SECOND); + ffrt::task_handle handle = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MICROSECOND_TO_SECOND)); + if (handle == nullptr) { + LOGE("handle is nullptr."); + return ERR_DM_FAILED; } + timerVec_[name] = std::move(handle); return DM_OK; } @@ -77,14 +70,18 @@ int32_t DmTimer::DeleteTimer(std::string timerName) } LOGI("DmTimer DeleteTimer start name: %{public}s", timerName.c_str()); std::lock_guard locker(timerMutex_); - if (!timerVec_.empty() && timerVec_.find(timerName) == timerVec_.end()) { - LOGI("DmTimer DeleteTimer is not exist."); + auto item = timerVec_.find(timerName); + if (item == timerVec_.end()) { + LOGI("Invalid task."); return ERR_DM_FAILED; } - timerVec_.erase(timerName); - if (eventHandler_ != nullptr) { - eventHandler_->RemoveTask(timerName); + if (item->second != nullptr && queue_ != nullptr) { + int32_t ret = queue_->cancel(item->second); + if (ret != 0) { + LOGE("Cancel failed, errCode: %{public}d.", ret); + } } + timerVec_.erase(timerName); return DM_OK; } @@ -92,15 +89,13 @@ int32_t DmTimer::DeleteAll() { LOGI("DmTimer DeleteAll start"); std::lock_guard locker(timerMutex_); - if (eventHandler_ == nullptr) { - return ERR_DM_FAILED; - } - if (timerVec_.empty()) { - LOGI("DmTimer is empty"); - return DM_OK; - } - for (auto name : timerVec_) { - eventHandler_->RemoveTask(name); + for (const auto &name : timerVec_) { + if (name.second != nullptr && queue_ != nullptr) { + int32_t ret = queue_->cancel(name.second); + if (ret != 0) { + LOGE("Cancel failed, errCode: %{public}d.", ret); + } + } } timerVec_.clear(); return DM_OK; diff --git a/utils/src/timer/lite/dm_timer.cpp b/utils/src/timer/lite/dm_timer.cpp index 931e692d017cb4f76a7107666722c11d4fcd3f4e..19ba9cbccdc1faf2b6ea8c8b511a3c479faed66d 100644 --- a/utils/src/timer/lite/dm_timer.cpp +++ b/utils/src/timer/lite/dm_timer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,10 +21,11 @@ namespace OHOS { namespace DistributedHardware { - +namespace { constexpr const char* TIMER_RUNNING = "TimerRunning"; constexpr int32_t ERR_DM_INPUT_PARA_INVALID = -20006; constexpr int32_t DM_OK = 0; +} Timer::Timer(std::string name, int32_t time, TimerCallback callback) : timerName_(name), expire_(steadyClock::now()), state_(true), timeOut_(time), callback_(callback) {};