From 3995f206a10cbbadf5b97bf512b20b3f1356aead Mon Sep 17 00:00:00 2001 From: wenfei Date: Tue, 15 Mar 2022 11:18:21 +0800 Subject: [PATCH] =?UTF-8?q?add:=E6=96=B0=E5=A2=9EL0=E8=AE=BE=E5=A4=87DM?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wenfei --- BUILD.gn | 19 +- interfaces/inner_kits/native_cpp/BUILD.gn | 42 +- .../native_cpp/include/device_manager_impl.h | 4 + .../include/notify/device_manager_notify.h | 2 + .../native_cpp/src/mini/device_manager.cpp | 27 + .../src/mini/device_manager_impl.cpp | 436 ++++++ .../src/mini/device_manager_notify.cpp | 260 ++++ interfaces/kits/js_mini/BUILD.gn | 56 + .../kits/js_mini/include/dm_native_event.h | 54 + .../js_mini/include/native_devicemanager_js.h | 188 +++ .../kits/js_mini/src/dm_native_event.cpp | 102 ++ .../js_mini/src/native_devicemanager_js.cpp | 1191 +++++++++++++++++ services/devicemanagerservice/BUILD.gn | 104 +- .../include/authentication/auth_ui.h | 2 +- .../include/config/dm_config_manager.h | 4 + .../dependency/hichain/hichain_connector.h | 6 +- .../include/dependency/mini/dm_mutex.h | 32 + .../include/dependency/mini/dm_thread.h | 49 + .../dependency/softbus/softbus_connector.h | 8 +- .../dependency/softbus/softbus_session.h | 6 +- .../include/dependency/timer/dm_timer.h | 10 +- .../include/device_manager_service_listener.h | 5 + .../devicestate/dm_device_state_manager.h | 7 +- .../dispatch/authenticate_device_req.h | 65 + .../include/dispatch/command_dispatch.h | 74 + .../include/dispatch/get_dmfaparam_rsp.h | 43 + .../dispatch/get_info_by_network_req.h | 42 + .../dispatch/get_info_by_network_rsp.h | 54 + .../dispatch/get_local_device_info_rsp.h | 43 + .../include/dispatch/get_trustdevice_req.h | 40 + .../include/dispatch/get_trustdevice_rsp.h | 44 + .../include/dispatch/get_useroperation_req.h | 41 + .../include/dispatch/message_def.h | 60 + .../include/dispatch/message_req.h | 42 + .../include/dispatch/message_rsp.h | 40 + .../include/dispatch/server_stub.h | 21 + .../include/dispatch/start_discovery_req.h | 53 + .../include/dispatch/stop_discovery_req.h | 40 + .../dispatch/unauthenticate_device_req.h | 43 + .../dispatch/verify_authenticate_req.h | 40 + .../src/authentication/dm_auth_manager.cpp | 8 +- .../src/config/mini/dm_config_manager.cpp | 65 + .../src/config/mini/pin_auth.cpp | 83 ++ .../dependency/hichain/hichain_connector.cpp | 6 +- .../src/dependency/mini/dm_mutex.cpp | 41 + .../src/dependency/mini/dm_thread.cpp | 52 + .../multipleuser/multiple_user_connector.cpp | 7 +- .../dependency/softbus/softbus_connector.cpp | 40 +- .../dependency/softbus/softbus_session.cpp | 6 +- .../src/dependency/timer/mini/dm_timer.cpp | 112 ++ .../src/device_manager_service.cpp | 14 +- .../devicestate/dm_device_state_manager.cpp | 78 +- .../src/dispatch/command_dispatch.cpp | 239 ++++ .../device_manager_service_listener_mini.cpp | 98 ++ .../src/dispatch/server_stub.cpp | 110 ++ utils/BUILD.gn | 46 +- utils/src/dm_random.cpp | 5 + 57 files changed, 4340 insertions(+), 69 deletions(-) create mode 100644 interfaces/inner_kits/native_cpp/src/mini/device_manager.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/mini/device_manager_impl.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/mini/device_manager_notify.cpp create mode 100644 interfaces/kits/js_mini/BUILD.gn create mode 100644 interfaces/kits/js_mini/include/dm_native_event.h create mode 100644 interfaces/kits/js_mini/include/native_devicemanager_js.h create mode 100644 interfaces/kits/js_mini/src/dm_native_event.cpp create mode 100644 interfaces/kits/js_mini/src/native_devicemanager_js.cpp create mode 100644 services/devicemanagerservice/include/dependency/mini/dm_mutex.h create mode 100644 services/devicemanagerservice/include/dependency/mini/dm_thread.h create mode 100644 services/devicemanagerservice/include/dispatch/authenticate_device_req.h create mode 100644 services/devicemanagerservice/include/dispatch/command_dispatch.h create mode 100644 services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_info_by_network_req.h create mode 100644 services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_trustdevice_req.h create mode 100644 services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_useroperation_req.h create mode 100644 services/devicemanagerservice/include/dispatch/message_def.h create mode 100644 services/devicemanagerservice/include/dispatch/message_req.h create mode 100644 services/devicemanagerservice/include/dispatch/message_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/server_stub.h create mode 100644 services/devicemanagerservice/include/dispatch/start_discovery_req.h create mode 100644 services/devicemanagerservice/include/dispatch/stop_discovery_req.h create mode 100644 services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h create mode 100644 services/devicemanagerservice/include/dispatch/verify_authenticate_req.h create mode 100644 services/devicemanagerservice/src/config/mini/dm_config_manager.cpp create mode 100644 services/devicemanagerservice/src/config/mini/pin_auth.cpp create mode 100644 services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp create mode 100644 services/devicemanagerservice/src/dependency/mini/dm_thread.cpp create mode 100644 services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp create mode 100644 services/devicemanagerservice/src/dispatch/command_dispatch.cpp create mode 100644 services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp create mode 100644 services/devicemanagerservice/src/dispatch/server_stub.cpp diff --git a/BUILD.gn b/BUILD.gn index 7e5dfc76c..6ca7f3707 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -14,10 +14,21 @@ import("//build/lite/config/component/lite_component.gni") if (defined(ohos_lite)) { - lite_component("devicemanager_lite") { - if (ohos_kernel_type == "liteos_m") { - } else { - features = [] + if (ohos_kernel_type == "liteos_m") { + lite_component("devicemanager_mini") { + features = [ + "utils:devicemanagerutils_mini", + "services/devicemanagerservice:devicemanagerservice_mini", + "interfaces/inner_kits/native_cpp:devicemanagersdk_mini", + "interfaces/kits/js_mini:devicemanager_native_js", + ] + } + } else { + lite_component("devicemanager_lite") { + if (ohos_kernel_type == "liteos_m") { + } else { + features = [] + } } } } diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index a842f4b22..fa8e4b3f3 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -19,7 +19,47 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - shared_library("devicemanagersdk") { + if (ohos_kernel_type == "liteos_m") { + static_library("devicemanagersdk_mini") { + include_dirs = [ + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/notify", + "${utils_path}/include", + "${common_path}/include", + "${services_path}/include/dispatch", + ] + include_dirs += [ + "//utils/native/lite/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + "//third_party/json/include", + ] + + sources = [ + "${innerkits_path}/native_cpp/src/mini/device_manager.cpp", + "${innerkits_path}/native_cpp/src/mini/device_manager_impl.cpp", + "${innerkits_path}/native_cpp/src/mini/device_manager_notify.cpp", + ] + + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + "${utils_path}:devicemanagerutils_mini", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//foundation/distributedschedule/samgr_lite/samgr", + "//third_party/bounds_checking_function:libsec_static", + "//utils/native/lite:utils", + ] + } + } else { + shared_library("devicemanagersdk") { + } } } else { config("devicemanagersdk_config") { 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 805d6640f..aee93d643 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -17,8 +17,10 @@ #define OHOS_DEVICE_MANAGER_IMPL_H #include "device_manager.h" +#if !defined(__LITEOS_M__) #include "ipc_client_manager.h" #include "ipc_client_proxy.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -67,8 +69,10 @@ private: DeviceManagerImpl &operator=(DeviceManagerImpl &&) = delete; private: +#if !defined(__LITEOS_M__) std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); +#endif }; } // namespace DistributedHardware } // namespace OHOS 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 2f882bb12..6aef7a4d8 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 @@ -65,7 +65,9 @@ public: void OnFaCall(std::string &pkgName, std::string ¶mJson); private: +#if !defined(__LITEOS_M__) std::mutex lock_; +#endif std::map> deviceStateCallback_; std::map>> deviceDiscoveryCallbacks_; std::map>> authenticateCallback_; diff --git a/interfaces/inner_kits/native_cpp/src/mini/device_manager.cpp b/interfaces/inner_kits/native_cpp/src/mini/device_manager.cpp new file mode 100644 index 000000000..e9a3b456d --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/mini/device_manager.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager.h" + +#include "device_manager_impl.h" + +namespace OHOS { +namespace DistributedHardware { +DeviceManager &DeviceManager::GetInstance() +{ + return DeviceManagerImpl::GetInstance(); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl.cpp new file mode 100644 index 000000000..38d460f69 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl.cpp @@ -0,0 +1,436 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "command_dispatch.h" +#include "dm_log.h" +#include "device_manager_notify.h" +#include "dm_constants.h" +#include "message_def.h" +#include "get_trustdevice_req.h" +#include "get_trustdevice_rsp.h" +#include "start_discovery_req.h" +#include "stop_discovery_req.h" +#include "get_useroperation_req.h" +#include "authenticate_device_req.h" +#include "verify_authenticate_req.h" +#include "get_local_device_info_rsp.h" +#include "get_info_by_network_rsp.h" +#include "get_info_by_network_req.h" +#include "unauthenticate_device_req.h" +#include "get_dmfaparam_rsp.h" +#include "device_manager_impl.h" + +namespace OHOS { +namespace DistributedHardware { +DeviceManagerImpl &DeviceManagerImpl::GetInstance() +{ + static DeviceManagerImpl instance; + return instance; +} + +int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) +{ + LOGI("DeviceManager::InitDeviceManager start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty() || dmInitCallback == nullptr) { + LOGE("InitDeviceManager error: Invalid parameter"); + return DM_INVALID_VALUE; + } + + CommandDispatch::GetInstance().AddPkgName(pkgName); + DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); + LOGI("InitDeviceManager success"); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) +{ + LOGI("DeviceManager::UnInitDeviceManager start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("InitDeviceManager error: Invalid parameter"); + return DM_INVALID_VALUE; + } + + CommandDispatch::GetInstance().DeletePkgName(pkgName); + DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); + LOGI("UnInitDeviceManager success"); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) +{ + LOGI("DeviceManager::GetTrustedDeviceList start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("GetTrustedDeviceList error: Invalid para"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_TRUST_DEVICE_LIST, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("GetTrustedDeviceList error: failed ret: %d", ret); + return ret; + } + + deviceList = rsp->GetDeviceVec(); + LOGI("GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) +{ + LOGI("DeviceManager::GetLocalDeviceInfo start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("GetLocalDeviceInfo error: Invalid para"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_LOCAL_DEVICE_INFO, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + if (rsp->GetErrCode() != DM_OK) { + LOGE("GetLocalDeviceInfo error: failed ret: %d", rsp->GetErrCode()); + return DM_IPC_RESPOND_ERROR; + } + + info = rsp->GetLocalDeviceInfo(); + LOGI("GetLocalDeviceInfo completed,pkgname%s", req->GetPkgName().c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) +{ + LOGI("DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty() || callback == nullptr) { + LOGE("RegisterDevStateCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); + LOGI("RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) +{ + LOGI("DeviceManager::UnRegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("UnRegisterDevStateCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); + LOGI("UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} +int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra, std::shared_ptr callback) +{ + LOGI("DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty() || callback == nullptr) { + LOGE("StartDeviceDiscovery error: Invalid para"); + return DM_INVALID_VALUE; + } + + LOGI("DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); + 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); + + if (CommandDispatch::GetInstance().MessageSendCmd(START_DEVICE_DISCOVER, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StartDeviceDiscovery error: Failed with ret %d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + LOGI("DeviceManager::StopDeviceDiscovery start , pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("StopDeviceDiscovery error: Invalid para"); + return DM_INVALID_VALUE; + } + + LOGI("StopDeviceDiscovery in, pkgName %s", pkgName.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + + if (CommandDispatch::GetInstance().MessageSendCmd(STOP_DEVICE_DISCOVER, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StopDeviceDiscovery error: Failed with ret %d", ret); + return ret; + } + + DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + LOGI("StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const DmDeviceInfo &deviceInfo, const std::string &extra, + std::shared_ptr callback) +{ + LOGI("DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("AuthenticateDevice error: Invalid para"); + return DM_INVALID_VALUE; + } + + std::string strDeviceId = deviceInfo.deviceId; + DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, strDeviceId, callback); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + req->SetAuthType(authType); + req->SetDeviceInfo(deviceInfo); + + if (CommandDispatch::GetInstance().MessageSendCmd(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("AuthenticateDevice error: Failed with ret %d", ret); + return ret; + } + + LOGI("DeviceManager::AuthenticateDevice completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s, deviceId: %s", pkgName.c_str(), deviceId.c_str()); + if (deviceId.empty()) { + LOGE("UnAuthenticateDevice error: Invalid para"); + return DM_INVALID_VALUE; + } + + DmDeviceInfo deviceInfo; + strcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, deviceId.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetDeviceInfo(deviceInfo); + + if (CommandDispatch::GetInstance().MessageSendCmd(UNAUTHENTICATE_DEVICE, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("UnAuthenticateDevice error: Failed with ret %d", ret); + return ret; + } + + LOGI("UnAuthenticateDevice completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &packageName, + std::shared_ptr callback) +{ + LOGI("DeviceManager::RegisterDeviceManagerFaCallback start, pkgName: %s", packageName.c_str()); + if (packageName.empty() || callback == nullptr) { + LOGE("RegisterDeviceManagerFaCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(packageName, callback); + LOGI("DeviceManager::RegisterDevStateCallback completed, pkgName: %s", packageName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) +{ + LOGI("DeviceManager::UnRegisterDeviceManagerFaCallback start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("UnRegisterDeviceManagerFaCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); + LOGI("DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} +int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) +{ + LOGI("DeviceManager::VerifyAuthentication start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("VerifyAuthentication error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetAuthPara(authPara); + + if (CommandDispatch::GetInstance().MessageSendCmd(VERIFY_AUTHENTICATION, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("VerifyAuthentication error: Failed with ret %d", ret); + return ret; + } + + LOGI("VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &dmFaParam) +{ + LOGI("DeviceManager::GetFaParam start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("GetFaParam failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + + if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + dmFaParam = rsp->GetDmAuthParam(); + LOGI("GetFaParam completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action) +{ + LOGI("DeviceManager::SetUserOperation start, pkgName: %s", pkgName.c_str()); + + if (pkgName.empty()) { + LOGE("VerifyAuthentication failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + + req->SetPkgName(pkgName); + req->SetOperation(action); + + if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_USER_AUTH_OPERATION, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("SetUserOperation Failed with ret %d", ret); + return ret; + } + + LOGI("SetUserOperation completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) +{ + if (pkgName.empty()) { + LOGE("GetUdidByNetworkId failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetNetWorkId(netWorkId); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_UDID_BY_NETWORK, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("DeviceManager::GetUdidByNetworkId Failed with ret %d", ret); + return ret; + } + + udid = rsp->GetUdid(); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) +{ + if (pkgName.empty()) { + LOGE("GetUuidByNetworkId failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetNetWorkId(netWorkId); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_UUID_BY_NETWORK, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("GetUuidByNetworkId Failed with ret %d", ret); + return ret; + } + uuid = rsp->GetUuid(); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ +} + +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/mini/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/mini/device_manager_notify.cpp new file mode 100644 index 000000000..02eeb2392 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/mini/device_manager_notify.cpp @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_notify.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" +#include "dm_constants.h" +#include "device_manager.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); + +void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, + std::shared_ptr dmInitCallback) +{ + dmInitCallback_[pkgName] = dmInitCallback; +} + +void DeviceManagerNotify::UnRegisterDeathRecipientCallback(const std::string &pkgName) +{ + dmInitCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDeviceStateCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + deviceStateCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceStateCallback(const std::string &pkgName) +{ + deviceStateCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId, + std::shared_ptr callback) +{ + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + deviceDiscoveryCallbacks_[pkgName] = std::map>(); + } + deviceDiscoveryCallbacks_[pkgName][subscribeId] = callback; +} + +void DeviceManagerNotify::UnRegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId) +{ + if (deviceDiscoveryCallbacks_.count(pkgName) > 0) { + deviceDiscoveryCallbacks_[pkgName].erase(subscribeId); + if (deviceDiscoveryCallbacks_[pkgName].empty()) { + deviceDiscoveryCallbacks_.erase(pkgName); + } + } +} + +void DeviceManagerNotify::RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback) +{ + if (authenticateCallback_.count(pkgName) == 0) { + authenticateCallback_[pkgName] = std::map>(); + } + authenticateCallback_[pkgName][deviceId] = callback; +} + +void DeviceManagerNotify::UnRegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId) +{ + if (authenticateCallback_.count(pkgName) > 0) { + authenticateCallback_[pkgName].erase(deviceId); + if (authenticateCallback_[pkgName].empty()) { + authenticateCallback_.erase(pkgName); + } + } +} + +void DeviceManagerNotify::UnRegisterPackageCallback(const std::string &pkgName) +{ + deviceStateCallback_.erase(pkgName); + deviceDiscoveryCallbacks_.erase(pkgName); + authenticateCallback_.erase(pkgName); + dmInitCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterVerifyAuthenticationCallback(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) +{ + verifyAuthCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::string &pkgName) +{ + verifyAuthCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + dmFaCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) +{ + if (dmFaCallback_.count(pkgName) == 0) { + LOGE("DeviceManager UnRegisterDeviceManagerFaCallback not register"); + return; + } + dmFaCallback_.erase(pkgName); +} + + +void DeviceManagerNotify::OnRemoteDied() +{ + LOGW("DeviceManager : OnRemoteDied"); + for (auto iter : dmInitCallback_) { + iter.second->OnRemoteDied(); + } +} + +void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceOnline pkgName:%s", pkgName.c_str()); + if (deviceStateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceOnlinecallback not register"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceOnline(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceOffline pkgName:%s", pkgName.c_str()); + + if (deviceStateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceOfflinecallback not register"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceOffline(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceChanged pkgName:%s", pkgName.c_str()); + + if (deviceStateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceChangedcallback not register"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceChanged(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, + const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceFound pkgName:%s, subscribeId:%d.", pkgName.c_str(), (int32_t)subscribeId); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for this package"); + return; + } + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for subscribeId %d", subscribeId); + return; + } + iter->second->OnDeviceFound(subscribeId, deviceInfo); +} + +void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) +{ + LOGI("DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", pkgName.c_str(), subscribeId, + failedReason); + + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for this package"); + return; + } + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for subscribeId %d", subscribeId); + return; + } + iter->second->OnDiscoveryFailed(subscribeId, failedReason); +} + +void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId) +{ + LOGI("DeviceManager OnDiscoverySuccess pkgName:%s, subscribeId:%d.", pkgName.c_str(), subscribeId); + + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for this package"); + return; + } + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for subscribeId %d", subscribeId); + return; + } + iter->second->OnDiscoverySuccess(subscribeId); +} + +void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::string &deviceId, + const std::string &token, uint32_t status, uint32_t reason) +{ + LOGI("DeviceManagerNotify::OnAuthResult pkgName:%s, status:%d, reason:%d", pkgName.c_str(), status, reason); + + if (authenticateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnAuthResult: no register authCallback for this package"); + return; + } + std::map> &authCallMap = authenticateCallback_[pkgName]; + auto iter = authCallMap.find(deviceId); + if (iter == authCallMap.end()) { + LOGE("DeviceManager OnAuthResult: no register authCallback for deviceID "); + return; + } + iter->second->OnAuthResult(deviceId, token, status, reason); + authenticateCallback_[pkgName].erase(deviceId); + if (authenticateCallback_[pkgName].empty()) { + authenticateCallback_.erase(pkgName); + } +} + +void DeviceManagerNotify::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, int32_t flag) +{ + LOGI("DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", pkgName.c_str(), resultCode, + flag); + + if (verifyAuthCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnCheckAuthResult: no register authCallback for this package"); + return; + } + verifyAuthCallback_[pkgName]->OnVerifyAuthResult(deviceId, resultCode, flag); + verifyAuthCallback_.erase(pkgName); +} + +void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) +{ + LOGI("DeviceManager OnFaCallback pkgName:%s", pkgName.c_str()); + + if (dmFaCallback_.count(pkgName) == 0) { + LOGE("DeviceManager DmFaCallback not register"); + return; + } + dmFaCallback_[pkgName]->OnCall(paramJson); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/kits/js_mini/BUILD.gn b/interfaces/kits/js_mini/BUILD.gn new file mode 100644 index 000000000..b26e7b1cc --- /dev/null +++ b/interfaces/kits/js_mini/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} + +import("//foundation/distributedhardware/devicemanager/devicemanager.gni") +innerkits_path_mini = "${devicemanager_path}/interfaces/inner_kits" +kits_path = "${devicemanager_path}/interfaces/kits" + +if (ohos_kernel_type == "liteos_m") { + static_library("devicemanager_native_js") { + include_dirs = [ + "//third_party/node/src", + "//third_party/json/include", + "${common_path}/include", + "//utils/native/base/include", + "${kits_path}/js_mini/include", + "${utils_path}/include", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/base", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/jsi", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/async", + "//foundation/ace/ace_engine_lite/frameworks/include/context", + "${innerkits_path_mini}/native_cpp/include", + ] + + sources = [ + "${kits_path}/js_mini/src/dm_native_event.cpp", + "${kits_path}/js_mini/src/native_devicemanager_js.cpp", + ] + + deps = [ + "${innerkits_path_mini}/native_cpp:devicemanagersdk_mini", + "${utils_path}:devicemanagerutils_mini", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit_js\"", + "LOG_DOMAIN=0xD004100", + ] + } +} diff --git a/interfaces/kits/js_mini/include/dm_native_event.h b/interfaces/kits/js_mini/include/dm_native_event.h new file mode 100644 index 000000000..c5987b3bf --- /dev/null +++ b/interfaces/kits/js_mini/include/dm_native_event.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICE_MANAGER_NATIVE_EVENT_H +#define OHOS_DEVICE_MANAGER_NATIVE_EVENT_H + +#include +#include +#include +#include "jsi.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace ACELite { +struct DmEventListener { + std::string eventType; + JSIValue handlerRef = JSI::CreateUndefined(); + JSIValue thisVarRef_ = JSI::CreateUndefined(); +}; + +struct FuncParams { + JSIValue handlerRef = JSI::CreateUndefined(); + JSIValue thisVarRef_ = JSI::CreateUndefined(); + const JSIValue *args = nullptr; + uint8_t argsSize = 0; +}; + +class DmNativeEvent { +public: + DmNativeEvent(); + DmNativeEvent(JSIValue thisVar); + virtual ~DmNativeEvent(); + virtual void On(std::string &eventType, JSIValue handler, JSIValue thisVal); + virtual void Off(std::string &eventType); + virtual void OnEvent(const std::string &eventType, uint8_t argsSize, const JSIValue *data); + static void OnEventAsyncWorkFunc(void *data); +protected: + static std::map> eventMap_; +}; +} +} + +#endif /* OHOS_DEVICE_MANAGER_NATIVE_EVENT_H */ \ No newline at end of file diff --git a/interfaces/kits/js_mini/include/native_devicemanager_js.h b/interfaces/kits/js_mini/include/native_devicemanager_js.h new file mode 100644 index 000000000..752f68102 --- /dev/null +++ b/interfaces/kits/js_mini/include/native_devicemanager_js.h @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_NATIVE_DEVICEMANAGER_JS_H +#define OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H + +#include +#include +#include +#include "device_manager_callback.h" +#include "dm_native_event.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "nlohmann/json.hpp" +#include "dm_device_info.h" +#include "jsi.h" +#include "js_ability.h" +#include "dm_app_image_info.h" + +namespace OHOS { +namespace ACELite { +#define DM_JSI_BUF_LENGTH (256) +#define DM_JSI_AUTH_REQUEST_FINISH (8) + +struct AuthFuncParams { + JSIValue handlerRef = JSI::CreateUndefined(); + JSIValue thisVarRef_ = JSI::CreateUndefined(); + const JSIValue *args = nullptr; + uint8_t argsSize = 0; +}; + +struct AuthAsyncCallbackInfo { + JSIValue thisVal_ = JSI::CreateUndefined(); + + char bundleName[DM_JSI_BUF_LENGTH] = {0}; + + JSIValue callback = JSI::CreateUndefined(); + int32_t authType = -1; +}; + +enum DmJSIDevStateChangeAction { + ONLINE = 0, + READY = 1, + OFFLINE = 2, + CHANGE = 3 +}; + +class DmJSIInitCallback : public OHOS::DistributedHardware::DmInitCallback { +public: + explicit DmJSIInitCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIInitCallback() {} + void OnRemoteDied() override; + +private: + std::string bundleName_; +}; + +class DmJSIDeviceStateCallback : public OHOS::DistributedHardware::DeviceStateCallback { +public: + explicit DmJSIDeviceStateCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIDeviceStateCallback() {}; + void OnDeviceOnline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceReady(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceOffline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceChanged(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + +private: + std::string bundleName_; +}; + +class DmJSIDiscoverCallback : public OHOS::DistributedHardware::DiscoveryCallback { +public: + explicit DmJSIDiscoverCallback(std::string &bundleName) : refCount_(0), bundleName_(bundleName) {} + virtual ~DmJSIDiscoverCallback() {}; + void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; + void OnDiscoverySuccess(uint16_t subscribeId) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); +private: + int32_t refCount_ = 0; + pthread_mutex_t lock_; + std::string bundleName_; +}; + +class DmJSIAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { +public: + explicit DmJSIAuthenticateCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIAuthenticateCallback() {}; + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override; + +private: + std::string bundleName_; +}; + +class DmJSICheckAuthCallback : public OHOS::DistributedHardware::VerifyAuthCallback { +public: + explicit DmJSICheckAuthCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSICheckAuthCallback() {}; + void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) override; + +private: + std::string bundleName_; +}; + +class DmJSIDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceManagerFaCallback { +public: + explicit DmJSIDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIDeviceManagerFaCallback() {}; + void OnCall(const std::string ¶mJson) override; + +private: + std::string bundleName_; +}; + +class DeviceManagerModule final : public MemoryHeap, DmNativeEvent { +public: + explicit DeviceManagerModule(); + virtual ~DeviceManagerModule(); + static JSIValue CreateDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue ReleaseDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue GetTrustedDeviceListSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue StartDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue StopDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue AuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue VerifyAuthInfo(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue JsOn(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue JsOff(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue SetUserOperationSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue GetAuthenticationParamSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue GetLocalDeviceInfoSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue UnAuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static DeviceManagerModule *GetDeviceManagerJSI(std::string &bundleName); + static void AuthRsultVerifyInfoAsyncWorkFunc(void *data); + static char *GetJSIAppBundleName(); + static void DmAuthParamToJsAuthParamy(const OHOS::DistributedHardware::DmAuthParam &authParam, + JSIValue ¶mResult); + void OnDmfaCall(const std::string ¶mJson); + void OnVerifyResult(const std::string &deviceId, int32_t resultCode, int32_t flag); + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason); + void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason); + void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); + void OnDeviceStateChange(DmJSIDevStateChangeAction action, + const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); + void OnRemoteDied(); + static void JsToDmAuthExtra(const JSIValue ¶m, nlohmann::json &jsonObj); + static void JsToDmTokenInfo(const JSIValue &object, const std::string &fieldStr, nlohmann::json &jsonObj); + static void JsToJsonObject(const JSIValue &object, const std::string &fieldStr, nlohmann::json &jsonObj); + static void JsToDmBuffer(const JSIValue &object, + const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen); + static void JsToDmAuthInfo(const JSIValue &object, std::string &extra); + static void JsToDmAppImageInfoAndDmExtra(const JSIValue &object, + OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, + std::string &extra, int32_t &authType); + static void JsToDmDeviceInfo(const JSIValue &object, OHOS::DistributedHardware::DmDeviceInfo& info); + static int32_t JsToDmSubscribeInfo(const JSIValue &object, OHOS::DistributedHardware::DmSubscribeInfo& info); + static char *JsObjectToString(const JSIValue &object, const std::string &fieldStr); + static bool JsObjectToBool(const JSIValue &object, const std::string &fieldStr); + static int32_t JsObjectToInt(const JSIValue &object, const std::string &fieldStr); + static void DmAuthParamToJsAuthParam(const OHOS::DistributedHardware::DmAuthParam &authParam, + JSIValue ¶mResult); + static void CreateDmCallback(std::string &bundleName, std::string &eventType); + static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); + static void DeviceInfoToJsArray(const std::vector &vecDevInfo, + const int32_t idx, JSIValue &arrayResult); +private: + std::string bundleName_; + static AuthAsyncCallbackInfo authAsyncCallbackInfo_; + static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; +}; +void InitDeviceManagerModule(JSIValue exports); +} +} + +#endif // OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H diff --git a/interfaces/kits/js_mini/src/dm_native_event.cpp b/interfaces/kits/js_mini/src/dm_native_event.cpp new file mode 100644 index 000000000..c63e0a9f7 --- /dev/null +++ b/interfaces/kits/js_mini/src/dm_native_event.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_native_event.h" +#include "jsi.h" +#include "dm_log.h" +#include "js_async_work.h" + +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace ACELite { +std::map> DmNativeEvent::eventMap_; + +DmNativeEvent::DmNativeEvent() +{ + LOGI("DmNativeEvent::DmNativeEvent() in"); +} + +DmNativeEvent::DmNativeEvent(JSIValue thisVar) +{ + LOGI("DmNativeEvent::DmNativeEvent(JSIValue thisVar) in"); +} + +DmNativeEvent::~DmNativeEvent() +{ + LOGI("DmNativeEvent::~DmNativeEvent() in"); +} + +void DmNativeEvent::On(std::string &eventType, JSIValue handle, JSIValue thisVal) +{ + LOGI("DmNativeEvent On in for event: %s", eventType.c_str()); + std::shared_ptr listener= std::make_shared(); + + listener->eventType = eventType; + listener->handlerRef = JSI::AcquireValue(handle); + + listener->thisVarRef_ = JSI::AcquireValue(thisVal); + eventMap_[eventType] = listener; +} + +void DmNativeEvent::Off(std::string &eventType) +{ + LOGI("DmNativeEvent Off in for event: %s", eventType.c_str()); + auto iter = eventMap_.find(eventType); + if (iter == eventMap_.end()) { + LOGE("eventType %s not find", eventType.c_str()); + return; + } + std::shared_ptr listener = iter->second; + JSI::ReleaseValue(listener->handlerRef); + + JSI::ReleaseValue(listener->thisVarRef_); + eventMap_.erase(eventType); +} + +void DmNativeEvent::OnEvent(const std::string &eventType, uint8_t argsSize, const JSIValue *data) +{ + LOGI("OnEvent for %s", eventType.c_str()); + + auto iter = eventMap_.find(eventType); + if (iter == eventMap_.end()) { + LOGE("eventType %s not find", eventType.c_str()); + return; + } + auto listener = iter->second; + if (!JSI::ValueIsFunction(listener->handlerRef)) { + LOGI("OnEvent for %s handlerRef is null", eventType.c_str()); + return; + } + + FuncParams* params = new FuncParams(); + params->handlerRef = listener->handlerRef; + params->thisVarRef_ = listener->thisVarRef_; + params->args = data; + params->argsSize = argsSize; + + LOGI("OnEventAsyncWorkFunc for %s in", eventType.c_str()); + JsAsyncWork::DispatchAsyncWork(OnEventAsyncWorkFunc, reinterpret_cast(params)); +} + +void DmNativeEvent::OnEventAsyncWorkFunc(void *data) +{ + LOGI("OnEventAsyncWorkFunc in "); + FuncParams* params = reinterpret_cast(data); + JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); +} +} +} \ No newline at end of file diff --git a/interfaces/kits/js_mini/src/native_devicemanager_js.cpp b/interfaces/kits/js_mini/src/native_devicemanager_js.cpp new file mode 100644 index 000000000..ef9aa14cd --- /dev/null +++ b/interfaces/kits/js_mini/src/native_devicemanager_js.cpp @@ -0,0 +1,1191 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "native_devicemanager_js.h" +#include +#include "nlohmann/json.hpp" +#include "device_manager.h" +#include "dm_constants.h" +#include "jsi_types.h" +#include "js_async_work.h" +#include "dm_log.h" +#include "dm_device_info.h" + +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace ACELite { +const std::string DM_JSI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange"; +const std::string DM_JSI_EVENT_DEVICE_FOUND = "deviceFound"; +const std::string DM_JSI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFail"; +const std::string DM_JSI_EVENT_DMFA_CALLBACK = "dmFaCallback"; +const std::string DM_JSI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; + +const std::string DEVICE_MANAGER_JSI_CLASS_NAME = "DeviceManager"; +const uint8_t DM_JSI_ARGS_ONE = 1; +const uint8_t DM_JSI_ARGS_TWO = 2; +const uint8_t DM_JSI_ARGS_THREE = 3; +const int32_t DM_JSI_SUB_ID_MAX = 65535; + +const int32_t DM_AUTH_TYPE_PINCODE = 1; +const int32_t DM_AUTH_DIRECTION_CLIENT = 1; + +const int32_t DM_JSI_SUBSCRIBE_CAPABILITY_DDMP = 0; +const int32_t DM_JSI_SUBSCRIBE_CAPABILITY_OSD = 1; +const char *DM_CAPABILITY_OSD = "osdCapability"; + +std::map g_deviceManagerMap; +std::map> g_initCallbackMap; +std::map> g_deviceStateCallbackMap; +std::map> g_discoverCallbackMap; +std::map> g_authCallbackMap; +std::map> g_checkAuthCallbackMap; +std::map> g_dmfaCallbackMap; + +AuthAsyncCallbackInfo DeviceManagerModule::authAsyncCallbackInfo_; +AuthAsyncCallbackInfo DeviceManagerModule::verifyAsyncCallbackInfo_; + +DeviceManagerModule *DeviceManagerModule::GetDeviceManagerJSI(std::string &bundleName) +{ + auto iter = g_deviceManagerMap.find(bundleName); + if (iter == g_deviceManagerMap.end()) { + return nullptr; + } + return iter->second; +} + +DeviceManagerModule::DeviceManagerModule() : DmNativeEvent() +{ + LOGI("new DeviceManagerModule is success"); +} + +DeviceManagerModule::~DeviceManagerModule() +{ +} + +void DmJSIInitCallback::OnRemoteDied() +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnRemoteDied, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnRemoteDied(); +} + +void DeviceManagerModule::OnRemoteDied() +{ + OnEvent("serviceDie", 0, nullptr); +} + +void DmJSIDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceOnline, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::ONLINE, deviceInfo); +} + +void DmJSIDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceOnline, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::READY, deviceInfo); +} + +void DmJSIDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceOffline, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::OFFLINE, deviceInfo); +} + +void DmJSIDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceChanged, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::CHANGE, deviceInfo); +} + +void DmJSIDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceFound, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + + LOGI("OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); + deviceManagerJSI->OnDeviceFound(subscribeId, deviceInfo); +} + +void DmJSIDiscoverCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDiscoverFailed, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + + deviceManagerJSI->OnDiscoverFailed(subscribeId, failedReason); +} + +void DmJSIDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDiscoverySuccess, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + LOGI("DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); +} + +void DmJSIAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnAuthResult, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnAuthResult(deviceId, token, status, reason); +} + +void DmJSICheckAuthCallback::OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnCheckAuthResult, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnVerifyResult(deviceId, resultCode, flag); +} + +void DmJSIDeviceManagerFaCallback::OnCall(const std::string ¶mJson) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnCall, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDmfaCall(paramJson); +} + +void DmJSIDiscoverCallback::IncreaseRefCount() +{ + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGE("init mutex lock failed: %d.", ret); + } + pthread_mutex_lock(&lock_); + refCount_++; + pthread_mutex_unlock(&lock_); + LOGI("IncreaseRefCount: refCount_:%d.", refCount_); + ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGE("destroy mutex lock failed: %d.", ret); + } +} + +void DmJSIDiscoverCallback::DecreaseRefCount() +{ + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGE("init mutex lock failed: %d.", ret); + } + pthread_mutex_lock(&lock_); + refCount_--; + pthread_mutex_unlock(&lock_); + + LOGI("DecreaseRefCount: refCount_:%d.", refCount_); + ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGE("destroy mutex lock failed: %d.", ret); + } +} + +int32_t DmJSIDiscoverCallback::GetRefCount() +{ + return refCount_; +} + +void DeviceManagerModule::OnDeviceStateChange(DmJSIDevStateChangeAction action, const DmDeviceInfo &deviceInfo) +{ + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "action", (double)action); + + JSIValue device = JSI::CreateObject(); + JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId); + JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName); + JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId); + + JSIValue param[2] = {result, device}; + OnEvent("deviceStateChange", DM_JSI_ARGS_TWO, param); + JSI::ReleaseValueList(result, device, ARGS_END); +} + +void DeviceManagerModule::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +{ + LOGI("OnDeviceFound for subscribeId %d", (int32_t)subscribeId); + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "subscribeId", (double)subscribeId); + + JSIValue device = JSI::CreateObject(); + JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId); + JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName); + JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId); + LOGI("OnDeviceFound subscribeId %ld ", subscribeId); + LOGI("OnDeviceFound deviceId %s ", deviceInfo.deviceId); + LOGI("OnDeviceFound deviceName %s ", deviceInfo.deviceName); + LOGI("OnDeviceFound deviceTypeId %x ", deviceInfo.deviceTypeId); + + JSIValue param[2] = {result, device}; + OnEvent("deviceFound", DM_JSI_ARGS_TWO, param); + JSI::ReleaseValueList(result, device, ARGS_END); +} + +void DeviceManagerModule::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) +{ + LOGI("OnDiscoverFailed for subscribeId %d", (int32_t)subscribeId); + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "subscribeId", (double)subscribeId); + JSIValue reason = JSI::CreateObject(); + JSI::SetNumberProperty(reason, "reason", (double)failedReason); + + JSIValue param[2] = {result, reason}; + OnEvent("discoverFail", DM_JSI_ARGS_TWO, param); + JSI::ReleaseValueList(result, reason, ARGS_END); +} + +void DeviceManagerModule::OnDmfaCall(const std::string ¶mJson) +{ + LOGI("OnCall for paramJson"); + JSIValue result = JSI::CreateObject(); + JSI::SetStringProperty(result, "param", paramJson.c_str()); + + JSIValue param[1] = {result}; + OnEvent("dmFaCallback", DM_JSI_ARGS_ONE, param); + JSI::ReleaseValueList(result, ARGS_END); +} + +void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) +{ + LOGI("OnAuthResult for status: %d, reason: %d", status, reason); + JSIValue thisVar = authAsyncCallbackInfo_.thisVal_; + JSIValue success = JSI::GetNamedProperty(authAsyncCallbackInfo_.callback, CB_SUCCESS); + JSIValue fail = JSI::GetNamedProperty(authAsyncCallbackInfo_.callback, CB_FAIL); + + JSIValue errOne = JSI::CreateObject(); + JSIValue errTwo = JSI::CreateObject(); + JSIValue successOne = JSI::CreateObject(); + JSIValue successTwo = JSI::CreateObject(); + + if (status == DM_JSI_AUTH_REQUEST_FINISH) { + LOGI("OnAuthResult success"); + JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str()); + JSIValue param[1] = {successOne}; + AuthFuncParams* params = new AuthFuncParams(); + params->handlerRef = success; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_ONE; + LOGI("OnAuthResult SuccessCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + } else { + LOGI("OnAuthResult failed"); + JSI::SetNumberProperty(errOne, "code", (double)status); + JSI::SetNumberProperty(errTwo, "reason", (double)reason); + JSIValue param[2] = {errOne, errTwo}; + AuthFuncParams* params = new AuthFuncParams(); + params->handlerRef = fail; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_TWO; + LOGI("OnAuthResult FailCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + } + g_authCallbackMap.erase(bundleName_); + JSI::ReleaseValueList(thisVar, success, fail, errOne, errTwo, successOne, successTwo, + authAsyncCallbackInfo_.thisVal_, authAsyncCallbackInfo_.callback, ARGS_END); +} + +void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t resultCode, int32_t flag) +{ + LOGI("OnVerifyResult for resultCode: %d, flag: %d", resultCode, flag); + JSIValue thisVar = verifyAsyncCallbackInfo_.thisVal_; + JSIValue success = JSI::GetNamedProperty(verifyAsyncCallbackInfo_.callback, CB_SUCCESS); + JSIValue fail = JSI::GetNamedProperty(verifyAsyncCallbackInfo_.callback, CB_FAIL); + + JSIValue successOne = JSI::CreateObject(); + JSIValue successTwo = JSI::CreateObject(); + JSIValue errOne = JSI::CreateObject(); + + if (resultCode == 0) { + LOGI("OnVerifyResult success"); + JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str()); + JSI::SetNumberProperty(successTwo, "level", (double)flag); + JSIValue param[2] = {successOne, successTwo}; + AuthFuncParams* params = new AuthFuncParams(); + params->handlerRef = success; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_TWO; + LOGI("OnVerifyResult SuccessCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + } else { + LOGI("OnVerifyResult failed"); + JSI::SetNumberProperty(errOne, "code", (double)resultCode); + JSIValue param[1] = {errOne}; + AuthFuncParams* params = new AuthFuncParams(); + params->handlerRef = fail; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_ONE; + LOGI("OnVerifyResult FailCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + } + + g_checkAuthCallbackMap.erase(bundleName_); + JSI::ReleaseValueList(thisVar, success, fail, successOne, successTwo, errOne, + verifyAsyncCallbackInfo_.thisVal_, verifyAsyncCallbackInfo_.callback, ARGS_END); +} + +void DeviceManagerModule::DeviceInfoToJsArray(const std::vector &vecDevInfo, + const int32_t idx, JSIValue &arrayResult) +{ + bool status = false; + JSIValue result = JSI::CreateObject(); + char *deviceId = const_cast(vecDevInfo[idx].deviceId); + char *deviceName = const_cast(vecDevInfo[idx].deviceName); + + JSI::SetStringProperty(result, "deviceId", deviceId); + JSI::SetStringProperty(result, "deviceName", deviceName); + JSI::SetNumberProperty(result, "deviceTypeId", (double)vecDevInfo[idx].deviceTypeId); + + status = JSI::SetPropertyByIndex(arrayResult, idx, result); + if (status == false) { + LOGE("DmDeviceInfo To JsArray set element error"); + } + JSI::ReleaseValue(result); +} + +void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam, JSIValue ¶mResult) +{ + LOGI("DmAuthParamToJsAuthParamy in"); + JSI::SetNumberProperty(paramResult, "authType", (double)authParam.authType); + + JSIValue extraInfo = JSI::CreateObject(); + JSI::SetNumberProperty(extraInfo, "direction", (double)authParam.direction); + JSI::SetNumberProperty(extraInfo, "pinToken", (double)authParam.pinToken); + if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { + JSI::SetNamedProperty(paramResult, "extraInfo", extraInfo); + return; + } + JSI::SetStringProperty(extraInfo, "packageName", authParam.packageName.c_str()); + JSI::SetStringProperty(extraInfo, "appName", authParam.appName.c_str()); + JSI::SetStringProperty(extraInfo, "appDescription", authParam.appDescription.c_str()); + JSI::SetNumberProperty(extraInfo, "business", (double)authParam.business); + JSI::SetNumberProperty(extraInfo, "pincode", (double)authParam.pincode); + JSI::SetNamedProperty(paramResult, "extraInfo", extraInfo); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, packageName: %s", authParam.packageName.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appName: %s", authParam.appName.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appDescription: %s", authParam.appDescription.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, business: %d", authParam.business); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pincode: %d", authParam.pincode); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pinToken: %d", authParam.pinToken); + + size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); + if (appIconLen > 0) { + uint8_t *appIcon = nullptr; + JSIValue appIconBuffer = JSI::CreateArrayBuffer(appIconLen, appIcon); + if (appIcon != nullptr && + memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), + appIconLen) == 0) { + JSIValue appIconArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, + appIconLen, appIconBuffer, 0); + JSI::SetNamedProperty(paramResult, "appIcon", appIconArray); + } + } + + size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); + if (appThumbnailLen > 0) { + uint8_t *appThumbnail = nullptr; + JSIValue appThumbnailBuffer = JSI::CreateArrayBuffer(appThumbnailLen, appThumbnail); + if (appThumbnail != nullptr && memcpy_s(appThumbnail, appThumbnailLen, + reinterpret_cast(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) { + JSIValue appThumbnailArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, + appThumbnailLen, + appThumbnailBuffer, 0); + JSI::SetNamedProperty(paramResult, "appThumbnail", appThumbnailArray); + } + } +} + +int32_t DeviceManagerModule::JsObjectToInt(const JSIValue &object, + const std::string &fieldStr) +{ + double result = JSI::GetNumberProperty(object, fieldStr.c_str()); + return (int32_t)result; +} + +bool DeviceManagerModule::JsObjectToBool(const JSIValue &object, + const std::string &fieldStr) +{ + bool result = JSI::GetBooleanProperty(object, fieldStr.c_str()); + return result; +} + +char *DeviceManagerModule::JsObjectToString(const JSIValue &object, + const std::string &fieldStr) +{ + char* str = JSI::GetStringProperty(object, fieldStr.c_str()); + return str; +} + +int32_t DeviceManagerModule::JsToDmSubscribeInfo(const JSIValue &object, DmSubscribeInfo &info) +{ + int32_t subscribeId = -1; + subscribeId = JsObjectToInt(object, "subscribeId"); + if (subscribeId < 0 || subscribeId > DM_JSI_SUB_ID_MAX) { + LOGE("DeviceManagerModule::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId); + return -1; + } + info.subscribeId = (uint16_t)subscribeId; + + int32_t mode = -1; + mode = JsObjectToInt(object, "mode"); + info.mode = (DmDiscoverMode)mode; + + int32_t medium = -1; + medium = JsObjectToInt(object, "medium"); + info.medium = (DmExchangeMedium)medium; + + int32_t freq = -1; + freq = JsObjectToInt(object, "freq"); + info.freq = (DmExchangeFreq)freq; + + info.isSameAccount = JsObjectToBool(object, "isSameAccount"); + info.isWakeRemote = JsObjectToBool(object, "isWakeRemote"); + + int32_t capability = -1; + capability = JsObjectToInt(object, "capability"); + if (capability == DM_JSI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_JSI_SUBSCRIBE_CAPABILITY_OSD) { + (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); + } + return 0; +} + +void DeviceManagerModule::JsToDmDeviceInfo(const JSIValue &object, + DmDeviceInfo &info) +{ + int ret = strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, JsObjectToString(object, "deviceId")); + if (ret != DM_OK) { + LOGE("JsToDmDeviceInfo error: copy deviceId failed %d", ret); + return; + } + ret = strcpy_s(info.deviceName, DM_MAX_DEVICE_NAME_LEN, JsObjectToString(object, "deviceName")); + if (ret != DM_OK) { + LOGE("JsToDmDeviceInfo error: copy deviceName failed %d", ret); + return; + } + uint16_t deviceTypeId = -1; + deviceTypeId = (uint16_t)JsObjectToInt(object, "deviceTypeId"); + info.deviceTypeId = deviceTypeId; +} + +void DeviceManagerModule::JsToDmAppImageInfoAndDmExtra(const JSIValue &object, + DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) +{ + LOGI("JsToDmAppImageInfoAndDmExtra in."); + int32_t authTypeTemp = -1; + authTypeTemp = (int32_t)JsObjectToInt(object, "authType"); + authType = authTypeTemp; + + uint8_t *appIconBufferPtr = nullptr; + int32_t appIconBufferLen = 0; + JsToDmBuffer(object, "appIcon", &appIconBufferPtr, appIconBufferLen); + + uint8_t *appThumbnailBufferPtr = nullptr; + int32_t appThumbnailBufferLen = 0; + JsToDmBuffer(object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); + + appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); + if (appIconBufferPtr != nullptr) { + free(appIconBufferPtr); + appIconBufferPtr = nullptr; + } + if (appThumbnailBufferPtr != nullptr) { + free(appThumbnailBufferPtr); + appThumbnailBufferPtr = nullptr; + } + + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = authType; + std::string extraInfo = "extraInfo"; + + JsToJsonObject(object, "extraInfo", jsonObj); + extra = jsonObj.dump(); + LOGI("appIconLen %d, appThumbnailLen %d", appIconBufferLen, appThumbnailBufferLen); +} + +void DeviceManagerModule::JsToDmBuffer(const JSIValue &object, + const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen) +{ + LOGI("JsToDmBuffer in."); + JSIValue field = JSI::GetNamedProperty(object, fieldStr.c_str()); + if (field == JSI::CreateUndefined() || field == JSI::CreateNull()) { + LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str()); + return; + } + OHOS::ACELite::TypedArrayType type = TypedArrayType::JSI_UINT8_ARRAY; + size_t length = 0; + JSIValue buffer = nullptr; + size_t offset = 0; + uint8_t *data = nullptr; + data = JSI::GetTypedArrayInfo(field, type, length, buffer, offset); + if (type != TypedArrayType::JSI_UINT8_ARRAY || length == 0 || data == nullptr) { + LOGE("Invaild AppIconInfo"); + return; + } + *bufferPtr = (uint8_t*)calloc(sizeof(uint8_t), length); + if (*bufferPtr == nullptr) { + LOGE("low memory, calloc return nullptr, length is %d, filed %s", length, fieldStr.c_str()); + return; + } + if (memcpy_s(*bufferPtr, length, data, length) != 0) { + LOGE("memcpy_s failed, filed %s", fieldStr.c_str()); + free(*bufferPtr); + *bufferPtr = nullptr; + return; + } + bufferLen = length; +} + +void DeviceManagerModule::JsToJsonObject(const JSIValue &object, + const std::string &fieldStr, nlohmann::json &jsonObj) +{ + LOGI("JsToJsonObject in."); + JSIValue jsonField = JSI::GetNamedProperty(object, fieldStr.c_str()); + if (jsonField == JSI::CreateUndefined() || jsonField == JSI::CreateNull()) { + LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str()); + return; + } + + JSIValue jsProNameList = nullptr; + uint32_t jsProCount = 0; + jsProNameList = JSI::GetObjectKeys(jsonField); + jsProCount = JSI::GetArrayLength(jsProNameList); + LOGI("Property size=%d.", jsProCount); + + JSIValue jsProName = nullptr; + JSIValue jsProValue = nullptr; + for (uint32_t index = 0; index < jsProCount; index++) { + jsProName = JSI::GetPropertyByIndex(jsProNameList, index); + std::string strProName = JSI::ValueToString(jsProName); + jsProValue = JSI::GetNamedProperty(jsonField, strProName.c_str()); + if (JSI::ValueIsString(jsProValue)) { + std::string natValue = JSI::ValueToString(jsProValue); + LOGI("Property name=%s, string, value=%s", strProName.c_str(), natValue.c_str()); + jsonObj[strProName] = natValue; + } + if (JSI::ValueIsBoolean(jsProValue)) { + bool elementValue = JSI::ValueToBoolean(jsProValue); + LOGI("Property name=%s, boolean, value=%d.", strProName.c_str(), elementValue); + jsonObj[strProName] = elementValue; + } + if (JSI::ValueIsNumber(jsProValue)) { + int32_t elementValue = 0; + elementValue = (int32_t)JSI::ValueToNumber(jsProValue); + jsonObj[strProName] = elementValue; + LOGI("Property name=%s, number, value=%d.", strProName.c_str(), elementValue); + } + } +} + +void DeviceManagerModule::JsToDmAuthInfo(const JSIValue &object, std::string &extra) +{ + LOGI("%s called.", __func__); + int32_t authType = -1; + int32_t token = -1; + + authType = JsObjectToInt(object, "authType"); + token = JsObjectToInt(object, "token"); + + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = authType; + if (authType == DM_AUTH_TYPE_PINCODE) { + jsonObj[PIN_TOKEN] = token; + } else { + jsonObj[TOKEN] = token; + } + JsToJsonObject(object, "extraInfo", jsonObj); + extra = jsonObj.dump(); +} + +void DeviceManagerModule::CreateDmCallback(std::string &bundleName, std::string &eventType) +{ + LOGE("CreateDmCallback for bunderName %s eventType %s", bundleName.c_str(), eventType.c_str()); + if (eventType == DM_JSI_EVENT_DEVICE_STATE_CHANGE) { + auto iter = g_deviceStateCallbackMap.find(bundleName); + if (iter == g_deviceStateCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + std::string extra = ""; + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback( + bundleName, extra, callback); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_deviceStateCallbackMap[bundleName] = callback; + } + return; + } + + if (eventType == DM_JSI_EVENT_DEVICE_FOUND || eventType == DM_JSI_EVENT_DEVICE_DISCOVER_FAIL) { + std::shared_ptr discoverCallback = nullptr; + auto iter = g_discoverCallbackMap.find(bundleName); + if (iter == g_discoverCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + g_discoverCallbackMap[bundleName] = callback; + discoverCallback = callback; + } else { + discoverCallback = iter->second; + } + + discoverCallback->IncreaseRefCount(); + return; + } + + if (eventType == DM_JSI_EVENT_DMFA_CALLBACK) { + auto iter = g_dmfaCallbackMap.find(bundleName); + if (iter == g_dmfaCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDeviceManagerFaCallback( + bundleName, callback); + if (ret != 0) { + LOGE("RegisterDeviceManagerFaCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_dmfaCallbackMap[bundleName] = callback; + } + return; + } +} + +void DeviceManagerModule::ReleaseDmCallback(std::string &bundleName, std::string &eventType) +{ + if (eventType == DM_JSI_EVENT_DEVICE_STATE_CHANGE) { + auto iter = g_deviceStateCallbackMap.find(bundleName); + if (iter == g_deviceStateCallbackMap.end()) { + LOGE("ReleaseDmCallback: cannot find stateCallback for bunderName %s", bundleName.c_str()); + return; + } + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(bundleName); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_deviceStateCallbackMap.erase(bundleName); + return; + } + + if (eventType == DM_JSI_EVENT_DEVICE_FOUND || eventType == DM_JSI_EVENT_DEVICE_DISCOVER_FAIL) { + std::shared_ptr discoverCallback = nullptr; + auto iter = g_discoverCallbackMap.find(bundleName); + if (iter == g_discoverCallbackMap.end()) { + return; + } + + discoverCallback = iter->second; + discoverCallback->DecreaseRefCount(); + if (discoverCallback->GetRefCount() == 0) { + g_discoverCallbackMap.erase(bundleName); + } + return; + } + + if (eventType == DM_JSI_EVENT_DMFA_CALLBACK) { + auto iter = g_dmfaCallbackMap.find(bundleName); + if (iter == g_dmfaCallbackMap.end()) { + LOGE("cannot find dmFaCallback for bunderName %s", bundleName.c_str()); + return; + } + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback( + bundleName); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_dmfaCallbackMap.erase(bundleName); + return; + } +} + +void DeviceManagerModule::AuthRsultVerifyInfoAsyncWorkFunc(void *data) +{ + LOGI("AuthRsultVerifyInfoAsyncWorkFunc in ............"); + AuthFuncParams* params = reinterpret_cast(data); + JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); +} + +JSIValue DeviceManagerModule::UnAuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("UnAuthenticateDevice in"); + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + if (!JSI::ValueIsObject(args[0])) { + LOGE("a object is required."); + return JSI::CreateNull(); + } + std::string bundleName = GetJSIAppBundleName(); + std::string deviceId = JSI::GetStringProperty(args[0], "deviceId"); + LOGI("UnAuthenticateDevice deviceId=%s", deviceId.c_str()); + int32_t ret = 0; + ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnAuthenticateDevice(bundleName, deviceId); + if (ret != 0) { + LOGI("UnAuthenticateDevice for bunderName %s failed, ret %d", bundleName.c_str(), ret); + } + + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "ret", (double)ret); + return result; +} + +JSIValue DeviceManagerModule::GetLocalDeviceInfoSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("GetLocalDeviceInfoSync in"); + + std::string bundleName = GetJSIAppBundleName(); + DmDeviceInfo deviceInfo; + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo(bundleName, deviceInfo); + if (ret != 0) { + LOGE("GetLocalDeviceInfoSync for failed, ret %d", ret); + return JSI::CreateNull(); + } + LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ", deviceInfo.deviceId, + deviceInfo.deviceName, deviceInfo.deviceTypeId); + JSIValue result = JSI::CreateObject(); + char *deviceId = const_cast(deviceInfo.deviceId); + char *deviceName = const_cast(deviceInfo.deviceName); + + JSI::SetStringProperty(result, "deviceId", deviceId); + JSI::SetStringProperty(result, "deviceName", deviceName); + JSI::SetNumberProperty(result, "deviceTypeId", (double)deviceInfo.deviceTypeId); + return result; +} + +JSIValue DeviceManagerModule::SetUserOperationSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("SetUserOperationSync in"); + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsNumber(args[0])) { + LOGE("a Number is required."); + return JSI::CreateNull(); + } + + std::string bundleName = GetJSIAppBundleName(); + int32_t action = 0; + action = static_cast(JSI::ValueToNumber(args[0])); + + LOGI("SetUserOperation action %d", action); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().SetUserOperation(bundleName, action); + if (ret != 0) { + LOGE("SetUserOperation for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + return JSI::CreateNull(); +} + +JSIValue DeviceManagerModule::GetAuthenticationParamSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("GetAuthenticationParamSync in"); + std::string bundleName = GetJSIAppBundleName(); + JSIValue resultParam = JSI::CreateObject(); + DmAuthParam authParam; + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetFaParam(bundleName, authParam); + if (ret != 0) { + LOGE("GetAuthenticationParam for %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + + DmAuthParamToJsAuthParamy(authParam, resultParam); + return resultParam; +} + +JSIValue DeviceManagerModule::GetTrustedDeviceListSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("GetTrustedDeviceList in"); + JSIValue array = JSI::CreateNull(); + std::string extra = ""; + std::vector devList; + std::string bundleName = GetJSIAppBundleName(); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList( + bundleName, extra, devList); + if (ret != 0) { + LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return array; + } + if (devList.size() > 0) { + bool isArray = false; + array = JSI::CreateArray(devList.size()); + isArray = JSI::ValueIsArray(array); + if (isArray == false) { + LOGE("JSI_create_array fail"); + } + + for (size_t i = 0; i != devList.size(); ++i) { + DeviceInfoToJsArray(devList, i, array); + } + } else { + LOGE("devList is null"); + } + + return array; +} + +JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("StartDeviceDiscoverSync in"); + std::string bundleName = GetJSIAppBundleName(); + + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[0])) { + LOGE("a object is required."); + return JSI::CreateNull(); + } + + std::shared_ptr discoverCallback = nullptr; + auto iter = g_discoverCallbackMap.find(bundleName); + if (iter == g_discoverCallbackMap.end()) { + discoverCallback = std::make_shared(bundleName); + g_discoverCallbackMap[bundleName] = discoverCallback; + } else { + discoverCallback = iter->second; + } + DmSubscribeInfo subInfo; + int32_t res = JsToDmSubscribeInfo(args[0], subInfo); + if (res != 0) { + LOGE("Wrong subscribeId."); + return JSI::CreateNull(); + } + + LOGI("subInfo %d , %d, %d, %d, %d , %d, %s", + subInfo.subscribeId, + subInfo.mode, + subInfo.medium, subInfo.freq, subInfo.isSameAccount, + subInfo.isWakeRemote, subInfo.capability); + std::string extra = ""; + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StartDeviceDiscovery(bundleName, + subInfo, extra, discoverCallback); + if (ret != 0) { + LOGE("StartDeviceDiscovery for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + return JSI::CreateNull(); +} + +JSIValue DeviceManagerModule::StopDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("StopDeviceDiscoverSync in"); + std::string bundleName = GetJSIAppBundleName(); + + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsNumber(args[0])) { + LOGE("a Number is required."); + return JSI::CreateNull(); + } + + int16_t subscribeId = 0; + subscribeId = static_cast(JSI::ValueToNumber(args[0])); + LOGI("subscribeId %d", subscribeId); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StopDeviceDiscovery(bundleName, subscribeId); + if (ret != 0) { + LOGE("StopDeviceDiscovery for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + return JSI::CreateNull(); +} + +JSIValue DeviceManagerModule::AuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("AuthenticateDevice in"); + std::string bundleName = GetJSIAppBundleName(); + if (argsSize < DM_JSI_ARGS_THREE) { + LOGE("3 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[0])) { + LOGE("a object is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[1])) { + LOGE("a object is required."); + return JSI::CreateNull(); + } + + authAsyncCallbackInfo_.thisVal_ = JSI::AcquireValue(thisVal); + authAsyncCallbackInfo_.callback = JSI::AcquireValue(args[DM_JSI_ARGS_TWO]); + + std::shared_ptr authCallback = nullptr; + auto iter = g_authCallbackMap.find(bundleName); + if (iter == g_authCallbackMap.end()) { + authCallback = std::make_shared(bundleName); + g_authCallbackMap[bundleName] = authCallback; + } else { + authCallback = iter->second; + } + DmDeviceInfo deviceInfo; + JsToDmDeviceInfo(args[0], deviceInfo); + + LOGI("deviceInfo %s , %s, %d", deviceInfo.deviceId, + deviceInfo.deviceName, deviceInfo.deviceTypeId); + DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); + std::string extra; + JsToDmAppImageInfoAndDmExtra(args[1], appImageInfo, extra, authAsyncCallbackInfo_.authType); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().AuthenticateDevice( + bundleName, 1, deviceInfo, extra, authCallback); + if (ret != 0) { + LOGE("AuthenticateDevice for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + } + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::VerifyAuthInfo(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("VerifyAuthInfo in"); + std::string bundleName = GetJSIAppBundleName(); + if (argsSize < DM_JSI_ARGS_TWO) { + LOGE("2 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[0])) { + LOGE("a object is required."); + return JSI::CreateNull(); + } + + verifyAsyncCallbackInfo_.thisVal_ = JSI::AcquireValue(thisVal); + verifyAsyncCallbackInfo_.callback = JSI::AcquireValue(args[1]); + + std::shared_ptr verifyCallback = nullptr; + auto iter = g_checkAuthCallbackMap.find(bundleName); + if (iter == g_checkAuthCallbackMap.end()) { + verifyCallback = std::make_shared(bundleName); + g_checkAuthCallbackMap[bundleName] = verifyCallback; + } else { + verifyCallback = iter->second; + } + std::string authParam; + JsToDmAuthInfo(args[0], authParam); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().VerifyAuthentication(bundleName, + authParam, verifyCallback); + if (ret != 0) { + LOGE("VerifyAuthInfo for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + } + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::JsOn(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("JsOn in"); + std::string bundleName = GetJSIAppBundleName(); + if (argsSize < DM_JSI_ARGS_TWO) { + LOGE("2 argument is required."); + return JSI::CreateNull(); + } + if (!JSI::ValueIsString(args[0])) { + LOGE("a string is required."); + return JSI::CreateNull(); + } + if (!JSI::ValueIsFunction(args[1])) { + LOGE("a FUNC is required."); + return JSI::CreateNull(); + } + std::string eventType = JSI::ValueToString(args[0]); + + LOGI("JsOn for bunderName %s, eventType %s ", bundleName.c_str(), + eventType.c_str()); + std::shared_ptr DmNativeEventobj = std::make_shared(thisVal); + DmNativeEventobj->On(eventType, args[1], thisVal); + CreateDmCallback(bundleName, eventType); + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::JsOff(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("JsOff in"); + std::string bundleName = GetJSIAppBundleName(); + + if (!JSI::ValueIsString(args[0])) { + LOGE("a string is required."); + return JSI::CreateNull(); + } + + std::string eventType = JSI::ValueToString(args[0]); + + LOGI("JsOff for bunderName %s, eventType %s ", bundleName.c_str(), + eventType.c_str()); + + DmNativeEvent* DmNativeEventobj = new DmNativeEvent(); + DmNativeEventobj->Off(eventType); + delete(DmNativeEventobj); + ReleaseDmCallback(bundleName, eventType); + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::ReleaseDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("ReleaseDeviceManager in"); + std::string bundleName = GetJSIAppBundleName(); + LOGI("ReleaseDeviceManager for bunderName %s", bundleName.c_str()); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(bundleName); + if (ret != 0) { + LOGE("ReleaseDeviceManager for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + JSIValue result = JSI::CreateNumber((double)ret); + return result; + } + + g_deviceManagerMap.erase(bundleName); + g_initCallbackMap.erase(bundleName); + g_deviceStateCallbackMap.erase(bundleName); + g_discoverCallbackMap.erase(bundleName); + g_authCallbackMap.erase(bundleName); + g_checkAuthCallbackMap.erase(bundleName); + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::CreateDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsString(args[0])) { + LOGE("a string is required."); + return JSI::CreateNull(); + } + std::string bundleName = GetJSIAppBundleName(); + LOGI("CreateDeviceManager for bunderName is %s", bundleName.c_str()); + + if (DeviceManagerModule::GetDeviceManagerJSI(bundleName) != nullptr) { + LOGI("CreateDeviceManager repeat for bunderName %s", bundleName.c_str()); + return JSI::CreateNull(); + } + + DeviceManagerModule *obj = new DeviceManagerModule(); + obj->bundleName_ = bundleName; + g_deviceManagerMap[bundleName] = obj; + + int32_t ret = 0; + std::shared_ptr initCallback = std::make_shared(bundleName); + ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(bundleName, initCallback); + if (ret == 0) { + LOGI("InitDeviceManager for bunderName %s success", bundleName.c_str()); + JSIValue success = JSI::GetNamedProperty(args[1], CB_SUCCESS); + JSIValue data = JSI::CreateObject(); + std::string str = "InitDeviceManager success"; + JSI::SetStringProperty(data, "data", str.c_str()); + JSI::CallFunction(success, thisVal, &data, 1); + } + if (ret != 0) { + LOGI("InitDeviceManager for bunderName %s fail", bundleName.c_str()); + JSIValue fail = JSI::GetNamedProperty(args[1], CB_FAIL); + JSIValue err = JSI::CreateObject(); + std::string str = "InitDeviceManager fail"; + JSI::SetStringProperty(err, "err", str.c_str()); + JSI::CallFunction(fail, thisVal, &err, 1); + } + return JSI::CreateNull(); +} + +char *DeviceManagerModule::GetJSIAppBundleName() +{ + JSAbility *g_targetJSAbility = new JSAbility(); + const char *pname = g_targetJSAbility->GetPackageName(); + char *packageName = new char[strlen(pname)+1]; + int ret = strcpy_s(packageName, strlen(pname)+1, pname); + if (ret != DM_OK) { + LOGE("GetJSIAppBundleName error: copy BundleName failed %d", ret); + delete(g_targetJSAbility); + return nullptr; + } + delete(g_targetJSAbility); + return packageName; +} + +void InitDeviceManagerModule(JSIValue exports) +{ + JSI::SetModuleAPI(exports, "createDeviceManager", DeviceManagerModule::CreateDeviceManager); + JSI::SetModuleAPI(exports, "getTrustedDeviceListSync", DeviceManagerModule::GetTrustedDeviceListSync); + JSI::SetModuleAPI(exports, "release", DeviceManagerModule::ReleaseDeviceManager); + JSI::SetModuleAPI(exports, "startDeviceDiscovery", DeviceManagerModule::StartDeviceDiscoverSync); + JSI::SetModuleAPI(exports, "stopDeviceDiscovery", DeviceManagerModule::StopDeviceDiscoverSync); + JSI::SetModuleAPI(exports, "authenticateDevice", DeviceManagerModule::AuthenticateDevice); + JSI::SetModuleAPI(exports, "verifyAuthInfo", DeviceManagerModule::VerifyAuthInfo); + JSI::SetModuleAPI(exports, "setUserOperation", DeviceManagerModule::SetUserOperationSync); + JSI::SetModuleAPI(exports, "getAuthenticationParam", DeviceManagerModule::GetAuthenticationParamSync); + JSI::SetModuleAPI(exports, "on", DeviceManagerModule::JsOn); + JSI::SetModuleAPI(exports, "off", DeviceManagerModule::JsOff); + JSI::SetModuleAPI(exports, "getLocalDeviceInfoSync", DeviceManagerModule::GetLocalDeviceInfoSync); + JSI::SetModuleAPI(exports, "unAuthenticateDevice", DeviceManagerModule::UnAuthenticateDevice); +} +} +} \ No newline at end of file diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 8ea80487d..77630e05c 100755 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -20,8 +20,108 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - executable("devicemanagerservice") { - sources = [ "src/ipc/lite/ipc_server_main.cpp" ] + if (ohos_kernel_type == "liteos_m") { + static_library("devicemanagerservice_mini") { + include_dirs = [ + "${devicemanager_path}/interfaces/inner_kits/native_cpp/include", + "${devicemanager_path}/interfaces/inner_kits/native_cpp/include/notify", + "${services_path}/include", + "${services_path}/include/config", + "${services_path}/include/adapter", + "${services_path}/include/authentication", + "${services_path}/include/ability", + "${services_path}/include/deviceinfo", + "${services_path}/include/devicestate", + "${services_path}/include/discovery", + "${services_path}/include/dependency/commonevent", + "${services_path}/include/dependency/multipleuser", + "${services_path}/include/dependency/hichain", + "${services_path}/include/dependency/softbus", + "${services_path}/include/dependency/mini", + "${services_path}/include/dependency/timer", + "${services_path}/include/eventbus", + "${common_path}/include", + "//base/security/deviceauth/interfaces/innerkits", + "//third_party/json/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "${utils_path}/include", + "${utils_path}/include/permission/lite", + "foundation/multimedia/image_standard/mock/native/include", + "${services_path}/include/dispatch", + "${ext_path}/pin_auth/include", + ] + + include_dirs += [ + "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", + "//utils/native/lite/include", + "//utils/system/safwk/native/include", + "//third_party/json/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//foundation/communication/dsoftbus/interfaces/kits/discovery", + "//foundation/communication/dsoftbus/interfaces/kits/transport", + "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dependency/multipleuser", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + sources = [ + "${services_path}/src/ability/lite/dm_ability_manager.cpp", + "${services_path}/src/adapter/standard/dm_adapter_manager.cpp", + "${services_path}/src/authentication/auth_message_processor.cpp", + "${services_path}/src/authentication/auth_request_state.cpp", + "${services_path}/src/authentication/auth_response_state.cpp", + "${services_path}/src/authentication/auth_ui.cpp", + "${services_path}/src/authentication/dm_auth_manager.cpp", + "${services_path}/src/config/mini/dm_config_manager.cpp", + "${services_path}/src/config/mini/pin_auth.cpp", + "${services_path}/src/dependency/hichain/hichain_connector.cpp", + "${services_path}/src/dependency/mini/dm_mutex.cpp", + "${services_path}/src/dependency/mini/dm_thread.cpp", + "${services_path}/src/dependency/multipleuser/multiple_user_connector.cpp", + "${services_path}/src/dependency/softbus/softbus_connector.cpp", + "${services_path}/src/dependency/softbus/softbus_session.cpp", + "${services_path}/src/dependency/timer/mini/dm_timer.cpp", + "${services_path}/src/device_manager_service.cpp", + "${services_path}/src/deviceinfo/dm_device_info_manager.cpp", + "${services_path}/src/devicestate/dm_device_state_manager.cpp", + "${services_path}/src/discovery/dm_discovery_manager.cpp", + "${services_path}/src/dispatch/command_dispatch.cpp", + "${services_path}/src/dispatch/device_manager_service_listener_mini.cpp", + "${services_path}/src/dispatch/server_stub.cpp", + ] + + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerservice\"", + "LOG_DOMAIN=0xD004100", + ] + + ldflags = dm_ldflags + + deps = [ + "${devicemanager_path}/interfaces/inner_kits/native_cpp:devicemanagersdk_mini", + "${utils_path}:devicemanagerutils_mini", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//base/security/deviceauth/services:deviceauth", + "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", + "//foundation/communication/dsoftbus/sdk:softbus_client", + "//foundation/distributedschedule/samgr_lite/samgr", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/mbedtls", + "//utils/native/lite:utils", + ] + } + } else { + executable("devicemanagerservice") { + sources = [ "src/ipc/lite/ipc_server_main.cpp" ] + } } } else if (!support_jsapi) { group("devicemanagerservice") { diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h index 4ba96cb50..e7473332c 100644 --- a/services/devicemanagerservice/include/authentication/auth_ui.h +++ b/services/devicemanagerservice/include/authentication/auth_ui.h @@ -17,7 +17,7 @@ #define OHOS_DM_AUTH_UI_H #include - +#include #include "dm_ability_manager.h" namespace OHOS { diff --git a/services/devicemanagerservice/include/config/dm_config_manager.h b/services/devicemanagerservice/include/config/dm_config_manager.h index 4a410a1e7..266e0044a 100644 --- a/services/devicemanagerservice/include/config/dm_config_manager.h +++ b/services/devicemanagerservice/include/config/dm_config_manager.h @@ -19,7 +19,9 @@ #include #include #include +#if !defined(__LITEOS_M__) #include +#endif #include #include #include @@ -66,10 +68,12 @@ private: DmConfigManager(); private: +#if !defined(__LITEOS_M__) std::mutex authAdapterMutex_; std::mutex cryptoAdapterMutex_; std::mutex decisionAdapterMutex_; std::mutex profileAdapterMutex_; +#endif std::map soAuthLoadInfo_; std::map soAdapterLoadInfo_; std::map> decisionAdapterPtr_; diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 6c19fe3fd..b8aa3708c 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -46,9 +46,9 @@ void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo); class HiChainConnector { public: static bool onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - static void onFinish(int64_t requestId, int32_t operationCode, const char *returnData); - static void onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn); - static char *onRequest(int64_t requestId, int32_t operationCode, const char *reqParams); + static void onFinish(int64_t requestId, int operationCode, const char *returnData); + static void onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn); + static char *onRequest(int64_t requestId, int operationCode, const char *reqParams); public: HiChainConnector(); diff --git a/services/devicemanagerservice/include/dependency/mini/dm_mutex.h b/services/devicemanagerservice/include/dependency/mini/dm_mutex.h new file mode 100644 index 000000000..209d405e9 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/mini/dm_mutex.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_MUTEX_H +#define OHOS_DM_MUTEX_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class DmMutex { +public: + DmMutex(); + ~DmMutex(); +private: +pthread_mutex_t lock_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_MUTEX_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dependency/mini/dm_thread.h b/services/devicemanagerservice/include/dependency/mini/dm_thread.h new file mode 100644 index 000000000..9b5634e58 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/mini/dm_thread.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_THREAD_H +#define OHOS_DM_THREAD_H + +#include +#include +#include +#include +#include "dm_device_info.h" +#include "softbus_state_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DmThread { +using funcstr = void (*)(std::map>, DmDeviceInfo); +public: + DmThread(funcstr funcname,\ + std::map> parameter1,\ + DmDeviceInfo parameter2); + static void* PthreadDeviceStart(void* parameterInfo); + void DmCreatThread(); + +private: + struct PthreadCallbackParameter { + std::map> member1; + DmDeviceInfo member2; + }; + static funcstr funcName_; + static std::map> parameter1_; + static DmDeviceInfo parameter2_; + PthreadCallbackParameter parameterGroup_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_THREAD_H diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index a957f42a8..47193cf25 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -34,14 +34,14 @@ namespace OHOS { namespace DistributedHardware { class SoftbusConnector { public: - static void OnPublishSuccess(int32_t publishId); - static void OnPublishFail(int32_t publishId, PublishFailReason reason); + static void OnPublishSuccess(int publishId); + static void OnPublishFail(int publishId, PublishFailReason reason); static void OnSoftBusDeviceOnline(NodeBasicInfo *info); static void OnSoftbusDeviceOffline(NodeBasicInfo *info); static void OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info); static void OnSoftbusDeviceFound(const DeviceInfo *device); - static void OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason); - static void OnSoftbusDiscoverySuccess(int32_t subscribeId); + static void OnSoftbusDiscoveryFailed(int subscribeId, DiscoveryFailReason failReason); + static void OnSoftbusDiscoverySuccess(int subscribeId); static void OnParameterChgCallback(const char *key, const char *value, void *context); static int32_t GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress); static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 2eab337e6..a62cbc037 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -30,9 +30,9 @@ namespace OHOS { namespace DistributedHardware { class SoftbusSession { public: - static int32_t OnSessionOpened(int32_t sessionId, int32_t result); - static void OnSessionClosed(int32_t sessionId); - static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + static int OnSessionOpened(int sessionId, int result); + static void OnSessionClosed(int sessionId); + static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); public: SoftbusSession(); diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h index a4ffec0fd..d0baed0b2 100644 --- a/services/devicemanagerservice/include/dependency/timer/dm_timer.h +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -18,12 +18,13 @@ #include #include #include +#if !defined(__LITEOS_M__) #include +#include #include - +#endif #include #include -#include #include "dm_log.h" @@ -60,10 +61,15 @@ private: TimeoutHandle mHandle_; void *mHandleData_; int32_t mTimeFd_[2]; +#if defined(__LITEOS_M__) + void *timerId = NULL; +#else struct epoll_event mEv_; struct epoll_event mEvents_[MAX_EVENTS]; int32_t mEpFd_; std::thread mThread_; +#endif + std::string mTimerName_; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index e52d9ed73..baf81e7ee 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -20,8 +20,11 @@ #include #include "dm_device_info.h" +#if !defined(__LITEOS_M__) #include "ipc_notify_dmfa_result_req.h" #include "ipc_server_listener.h" +#endif + namespace OHOS { namespace DistributedHardware { @@ -38,7 +41,9 @@ public: void OnFaCall(std::string &pkgName, std::string ¶mJson); private: +#if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; +#endif }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 7817313fc..b2b3f5b47 100755 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -18,8 +18,11 @@ #include #include +#if defined(__LITEOS_M__) +#include "dm_mutex.h" +#else #include - +#endif #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" #include "softbus_connector.h" @@ -54,8 +57,10 @@ public: private: std::string profileSoName_; +#if !defined(__LITEOS_M__) std::mutex timerMapMutex_; std::mutex remoteDeviceInfosMutex_; +#endif std::shared_ptr softbusConnector_; std::shared_ptr listener_; std::map remoteDeviceInfos_; diff --git a/services/devicemanagerservice/include/dispatch/authenticate_device_req.h b/services/devicemanagerservice/include/dispatch/authenticate_device_req.h new file mode 100644 index 000000000..4bc90cfdd --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/authenticate_device_req.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_AUTHENTICATE_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_AUTHENTICATE_DEVICE_REQ_H + +#include "message_req.h" + +#include "dm_device_info.h" +#include "dm_app_image_info.h" + +namespace OHOS { +namespace DistributedHardware { +class AuthenticateDeviceReq : public MessageReq { +DECLARE_MESSAGE_MODEL(AuthenticateDeviceReq); +public: + const DmDeviceInfo& GetDeviceInfo() const + { + return deviceInfo_; + } + + void SetDeviceInfo(const DmDeviceInfo &deviceInfo) + { + deviceInfo_ = deviceInfo; + } + + int32_t GetAuthType() + { + return authType_; + } + + void SetAuthType(int32_t authType) + { + authType_ = authType; + } + + const std::string& GetExtra() const + { + return extra_; + } + + void SetExtra(const std::string &extra) + { + extra_ = extra; + } +private: + DmDeviceInfo deviceInfo_; + int32_t authType_; + std::string extra_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_AUTHENTICATE_DEVICE_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/command_dispatch.h b/services/devicemanagerservice/include/dispatch/command_dispatch.h new file mode 100644 index 000000000..1ccfe254c --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/command_dispatch.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_COMMAND_DISPATCH_H +#define OHOS_DEVICE_MANAGER_COMMAND_DISPATCH_H + +#include +#include +#include +#include +#include "single_instance.h" +#include "message_req.h" +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +#define DEVICEMANAGER_MESSAGE_FAILED (-1) +static int32_t GetTrustedDeviceList(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t GetLocalDeviceInfo(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t GetUdidByNetworkId(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t GetUuidByNetworkId(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t StartDeviceDiscovery(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t StopDeviceDiscovery(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t SetUserOperation(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t GetFaParam(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t AuthenticateDevice(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t UnAuthenticateDevice(const std::shared_ptr &req, const std::shared_ptr &rsp); +static int32_t VerifyAuthentication(const std::shared_ptr &req, const std::shared_ptr &rsp); + +typedef struct { + int32_t cmdCode; + int32_t (*MsgProcess) (const std::shared_ptr &req, const std::shared_ptr &rsp); +} CmdMap; + +static const CmdMap g_cmdMap[] = { + {GET_TRUST_DEVICE_LIST, GetTrustedDeviceList}, + {GET_LOCAL_DEVICE_INFO, GetLocalDeviceInfo}, + {GET_UDID_BY_NETWORK, GetUdidByNetworkId}, + {GET_UUID_BY_NETWORK, GetUuidByNetworkId}, + {START_DEVICE_DISCOVER, StartDeviceDiscovery}, + {STOP_DEVICE_DISCOVER, StopDeviceDiscovery}, + {SERVER_USER_AUTH_OPERATION, SetUserOperation}, + {SERVER_GET_DMFA_INFO, GetFaParam}, + {AUTHENTICATE_DEVICE, AuthenticateDevice}, + {UNAUTHENTICATE_DEVICE, UnAuthenticateDevice}, + {VERIFY_AUTHENTICATION, VerifyAuthentication}, +}; + +class CommandDispatch { +DECLARE_SINGLE_INSTANCE(CommandDispatch); +public: + int32_t MessageSendCmd(int32_t cmdCode, const std::shared_ptr &req, + const std::shared_ptr &rsp); + void AddPkgName(const std::string &pkgName); + void DeletePkgName(const std::string &pkgName); + const std::list& GetPkgNameList() const; +private: + std::list dmPkgName_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_COMMAND_DISPATCH_H diff --git a/services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h b/services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h new file mode 100644 index 000000000..9126d2c3d --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_DM_FA_PARAM_RSP_H +#define OHOS_DEVICE_MANAGER_GET_DM_FA_PARAM_RSP_H + +#include "dm_device_info.h" +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetDmFaParamRsp : public MessageRsp { + DECLARE_MESSAGE_MODEL(GetDmFaParamRsp); + +public: + const DmAuthParam GetDmAuthParam() const + { + return dmFaParam_; + } + + void SetDmAuthParam(const DmAuthParam &dmFaParam) + { + dmFaParam_ = dmFaParam; + } + +private: + DmAuthParam dmFaParam_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_DM_FA_PARAM_RSP_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_info_by_network_req.h b/services/devicemanagerservice/include/dispatch/get_info_by_network_req.h new file mode 100644 index 000000000..0b75fef00 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_info_by_network_req.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_REQ_H +#define OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_REQ_H + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class GetInfoByNetWorkReq : public MessageReq { + DECLARE_MESSAGE_MODEL(GetInfoByNetWorkReq); + +public: + const std::string GetNetWorkId() const + { + return netWorkId_; + } + + void SetNetWorkId(const std::string &netWorkId) + { + netWorkId_ = netWorkId; + } + +private: + std::string netWorkId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_REQ_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h b/services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h new file mode 100644 index 000000000..4ce591a44 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_RSP_H +#define OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_RSP_H + +#include + +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetInfoByNetWorkRsp : public MessageRsp { + DECLARE_MESSAGE_MODEL(GetInfoByNetWorkRsp); + +public: + 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: + std::string udid_; + std::string uuid_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_RSP_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h b/services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h new file mode 100644 index 000000000..d87cc4a5a --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_LOCAL_DEVICE_INFO_RSP_H +#define OHOS_DEVICE_MANAGER_GET_LOCAL_DEVICE_INFO_RSP_H + +#include "dm_device_info.h" +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetLocalDeviceInfoRsp : public MessageRsp { + DECLARE_MESSAGE_MODEL(GetLocalDeviceInfoRsp); + +public: + const DmDeviceInfo &GetLocalDeviceInfo() const + { + return localDeviceInfo_; + } + + void SetLocalDeviceInfo(DmDeviceInfo &localDeviceInfo) + { + localDeviceInfo_ = localDeviceInfo; + } + +private: + DmDeviceInfo localDeviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_LOCAL_DEVICE_INFO_RSP_H diff --git a/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h b/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h new file mode 100644 index 000000000..c4f4fca14 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_TRUST_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_GET_TRUST_DEVICE_REQ_H + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class GetTrustDeviceReq : public MessageReq { +DECLARE_MESSAGE_MODEL(GetTrustDeviceReq); +public: + const std::string& GetExtra() const + { + return extra_; + } + + void SetExtra(const std::string &extra) + { + extra_ = extra; + } +private: + std::string extra_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_TRUST_DEVICE_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h b/services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h new file mode 100644 index 000000000..7b9bef074 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_TRUSTDEVICE_RSP_H +#define OHOS_DEVICE_MANAGER_GET_TRUSTDEVICE_RSP_H + +#include + +#include "dm_device_info.h" + +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetTrustDeviceRsp : public MessageRsp { +DECLARE_MESSAGE_MODEL(GetTrustDeviceRsp); +public: + std::vector GetDeviceVec() const + { + return deviceVec_; + } + + void SetDeviceVec(std::vector& deviceVec) + { + deviceVec_ = deviceVec; + } +private: + std::vector deviceVec_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_TRUSTDEVICE_RSP_H diff --git a/services/devicemanagerservice/include/dispatch/get_useroperation_req.h b/services/devicemanagerservice/include/dispatch/get_useroperation_req.h new file mode 100644 index 000000000..5b2f2679c --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_useroperation_req.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_USER_OPERATION_REQ_H +#define OHOS_DEVICE_MANAGER_GET_USER_OPERATION_REQ_H +#include "message_req.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class GetUserOperationReq : public MessageReq { +DECLARE_MESSAGE_MODEL(GetUserOperationReq); +public: + int32_t GetOperation() const + { + return action_; + } + + void SetOperation(int32_t action) + { + action_ = action; + } + +private: + int32_t action_ {0}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_USER_OPERATION_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/message_def.h b/services/devicemanagerservice/include/dispatch/message_def.h new file mode 100644 index 000000000..a5efbeb5e --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/message_def.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_MANAGER_MESSAGE_DEF_H +#define DEVICE_MANAGER_MESSAGE_DEF_H + +namespace OHOS { +namespace DistributedHardware { +#define DEVICE_MANAGER_SERVICE_NAME "dev_mgr_svc" +#define MAX_DM_IPC_LEN 2048 + +#define DECLARE_MESSAGE_MODEL(className) \ +public: \ + className() = default; \ + virtual ~className() = default; \ + \ +public: \ + className(const className &) = delete; \ + className &operator=(const className &) = delete; \ + className(className &&) = delete; \ + className &operator=(className &&) = delete + +#define DECLARE_MESSAGE_INTERFACE(className) DECLARE_MESSAGE_MODEL(className) + +enum DispatchCmdID { + REGISTER_DEVICE_MANAGER_LISTENER = 0, + UNREGISTER_DEVICE_MANAGER_LISTENER, + GET_TRUST_DEVICE_LIST, + GET_LOCAL_DEVICE_INFO, + GET_UDID_BY_NETWORK, + GET_UUID_BY_NETWORK, + START_DEVICE_DISCOVER, + STOP_DEVICE_DISCOVER, + AUTHENTICATE_DEVICE, + UNAUTHENTICATE_DEVICE, + VERIFY_AUTHENTICATION, + SERVER_DEVICE_STATE_NOTIFY, + SERVER_DEVICE_FOUND, + SERVER_DISCOVER_FINISH, + SERVER_AUTH_RESULT, + SERVER_VERIFY_AUTH_RESULT, + SERVER_GET_DMFA_INFO, + SERVER_USER_AUTH_OPERATION, + SERVER_DEVICE_FA_NOTIFY, +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // DEVICE_MANAGER_MESSAGE_DEF_H diff --git a/services/devicemanagerservice/include/dispatch/message_req.h b/services/devicemanagerservice/include/dispatch/message_req.h new file mode 100644 index 000000000..d8b438a11 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/message_req.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_MESSAGE_REQ_H +#define OHOS_DEVICE_MANAGER_MESSAGE_REQ_H + +#include + +#include "message_def.h" + +namespace OHOS { +namespace DistributedHardware { +class MessageReq { +DECLARE_MESSAGE_MODEL(MessageReq); +public: + const std::string& GetPkgName() const + { + return pkgName_; + } + + void SetPkgName(const std::string &pkgName) + { + pkgName_ = pkgName; + } +private: + std::string pkgName_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_MESSAGE_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/message_rsp.h b/services/devicemanagerservice/include/dispatch/message_rsp.h new file mode 100644 index 000000000..811a28182 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/message_rsp.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_MESSAGE_RSP_H +#define OHOS_DEVICE_MANAGER_MESSAGE_RSP_H + +#include "message_def.h" + +namespace OHOS { +namespace DistributedHardware { +class MessageRsp { +DECLARE_MESSAGE_MODEL(MessageRsp); +public: + int32_t GetErrCode() const + { + return errCode_; + } + + void SetErrCode(int32_t errCode) + { + errCode_ = errCode; + } +private: + int32_t errCode_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_MESSAGE_RSP_H diff --git a/services/devicemanagerservice/include/dispatch/server_stub.h b/services/devicemanagerservice/include/dispatch/server_stub.h new file mode 100644 index 000000000..34a1b0128 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/server_stub.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_SERVER_STUB_H +#define OHOS_DEVICE_MANAGER_SERVER_STUB_H + +#include + +#endif // OHOS_DEVICE_MANAGER_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/dispatch/start_discovery_req.h b/services/devicemanagerservice/include/dispatch/start_discovery_req.h new file mode 100644 index 000000000..fd88596f5 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/start_discovery_req.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H +#define OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H + +#include "message_req.h" + +#include "dm_subscribe_info.h" + +namespace OHOS { +namespace DistributedHardware { +class StartDiscoveryReq : public MessageReq { +DECLARE_MESSAGE_MODEL(StartDiscoveryReq); +public: + const DmSubscribeInfo& GetSubscribeInfo() const + { + return subscribeInfo_; + } + + void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) + { + subscribeInfo_ = subscribeInfo; + } + const std::string &GetExtra() const + { + return extra_; + } + + void SetExtra(const std::string &extra) + { + extra_ = extra; + } + +private: + std::string extra_; + DmSubscribeInfo subscribeInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/stop_discovery_req.h b/services/devicemanagerservice/include/dispatch/stop_discovery_req.h new file mode 100644 index 000000000..4ce6703ac --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/stop_discovery_req.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H +#define OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class StopDiscoveryReq : public MessageReq { +DECLARE_MESSAGE_MODEL(StopDiscoveryReq); +public: + uint16_t GetSubscribeId() const + { + return subscribeId_; + } + + void SetSubscribeId(uint16_t subscribeId) + { + subscribeId_ = subscribeId; + } +private: + uint16_t subscribeId_ {0}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h b/services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h new file mode 100644 index 000000000..bc00e17cf --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_UNAUTHENTICATE_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_UNAUTHENTICATE_DEVICE_REQ_H + +#include "dm_device_info.h" +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class UnAuthenticateDeviceReq : public MessageReq { + DECLARE_MESSAGE_MODEL(UnAuthenticateDeviceReq); + +public: + const DmDeviceInfo &GetDeviceInfo() const + { + return deviceInfo_; + } + + void SetDeviceInfo(const DmDeviceInfo &deviceInfo) + { + deviceInfo_ = deviceInfo; + } + +private: + DmDeviceInfo deviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_UNAUTHENTICATE_DEVICE_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h b/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h new file mode 100644 index 000000000..236e77480 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_VERIFY_AUTHENTICATE_REQ_H +#define OHOS_DEVICE_MANAGER_VERIFY_AUTHENTICATE_REQ_H + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class VerifyAuthenticateReq : public MessageReq { +DECLARE_MESSAGE_MODEL(VerifyAuthenticateReq); +public: + const std::string& GetAuthPara() const + { + return authPara_; + } + + void SetAuthPara(const std::string &authPara) + { + authPara_ = authPara; + } +private: + std::string authPara_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_VERIFY_AUTHENTICATE_REQ_H diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 2fc6956ca..3ebccaaa6 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -576,11 +576,12 @@ int32_t DmAuthManager::JoinNetwork() void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); -#ifdef SUPPORT_GRAPHICS if (authResponseState_ != nullptr) { +#ifdef SUPPORT_GRAPHICS if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); } +#endif if (isFinishOfLocal_) { authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); @@ -604,11 +605,11 @@ void DmAuthManager::AuthenticateFinish() } else { authRequestContext_->reason = authResponseContext_->reply; } - +#ifdef SUPPORT_GRAPHICS if (authResponseContext_->state == AuthState::AUTH_REQUEST_INPUT) { Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); } - +#endif listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); @@ -626,7 +627,6 @@ void DmAuthManager::AuthenticateFinish() authRequestState_ = nullptr; authMessageProcessor_ = nullptr; } -#endif LOGI("DmAuthManager::AuthenticateFinish complete"); } diff --git a/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp new file mode 100644 index 000000000..c4c60b038 --- /dev/null +++ b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dm_config_manager.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "pin_auth.h" + +namespace OHOS { +namespace DistributedHardware { +DmConfigManager &DmConfigManager::GetInstance() +{ + static DmConfigManager instance; + return instance; +} + +DmConfigManager::DmConfigManager() +{ + LOGI("DmConfigManager constructor"); +} + +DmConfigManager::~DmConfigManager() +{ + LOGI("DmAdapterManager destructor"); +} + +std::shared_ptr DmConfigManager::GetDecisionAdapter(const std::string &soName) +{ + return nullptr; +} + +std::shared_ptr DmConfigManager::GetProfileAdapter(const std::string &soName) +{ + return nullptr; +} + +std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::string &soName) +{ + return nullptr; +} + +extern "C" IAuthentication *CreatePinAuthObject(void) +{ + return new PinAuth; +} + +void DmConfigManager::GetAuthAdapter(std::map> &authAdapter) +{ + authAdapter.clear(); + std::shared_ptr iAuthentication(CreatePinAuthObject()); + authAdapter[AUTH_TYPE_PIN] = iAuthentication; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/config/mini/pin_auth.cpp b/services/devicemanagerservice/src/config/mini/pin_auth.cpp new file mode 100644 index 000000000..5ac1ade7b --- /dev/null +++ b/services/devicemanagerservice/src/config/mini/pin_auth.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pin_auth.h" + +#include + +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +const int32_t MAX_VERIFY_TIMES = 3; +PinAuth::PinAuth() +{ + LOGI("PinAuth constructor"); +} + +PinAuth::~PinAuth() +{ +} + +int32_t PinAuth::ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) +{ + LOGI("ShowConfigDialog end"); + return DM_OK; +} + +int32_t PinAuth::StartAuth(std::string &authToken, std::shared_ptr authManager) +{ + LOGI("StartAuth end"); + return DM_OK; +} + +int32_t PinAuth::VerifyAuthentication(std::string &authToken, const std::string &authParam) +{ + times_ += 1; + if (authParam.length() == 1) { + if (authParam == "0") { + return DM_OK; + } + LOGE("Peer rejection"); + return DM_FAILED; + } + nlohmann::json authParamJson = nlohmann::json::parse(authParam, nullptr, false); + if (authParamJson.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + nlohmann::json authTokenJson = nlohmann::json::parse(authToken, nullptr, false); + if (authTokenJson.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + if (!authParamJson.contains(PIN_CODE_KEY) || !authTokenJson.contains(PIN_CODE_KEY)) { + LOGE("err json string, first time"); + return DM_FAILED; + } + int32_t code = authTokenJson[PIN_CODE_KEY]; + int32_t inputPinCode = authParamJson[PIN_CODE_KEY]; + if (code == inputPinCode) { + return DM_OK; + } else if (code != inputPinCode && times_ < MAX_VERIFY_TIMES) { + return DM_AUTH_INPUT_FAILED; + } else { + return DM_FAILED; + } +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index b2a5bdfc1..974b82913 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -250,7 +250,7 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectIn return ret; } -void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) +void HiChainConnector::onFinish(int64_t requestId, int operationCode, const char *returnData) { std::string data = ""; if (returnData != nullptr) { @@ -273,7 +273,7 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const } } -void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn) +void HiChainConnector::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) { (void)errorReturn; LOGI("HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", requestId, operationCode, errorCode); @@ -293,7 +293,7 @@ void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t } } -char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams) +char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const char *reqParams) { if (operationCode != GroupOperationCode::MEMBER_JOIN) { LOGE("HiChainAuthCallBack::onRequest operationCode %d", operationCode); diff --git a/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp new file mode 100644 index 000000000..eb0a0609d --- /dev/null +++ b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "dm_log.h" +#include "dm_mutex.h" + +namespace OHOS { +namespace DistributedHardware { +DmMutex::DmMutex() +{ + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGE("init mutex lock failed: %d.", ret); + } + pthread_mutex_lock(&lock_); +} + +DmMutex::~DmMutex() +{ + pthread_mutex_unlock(&lock_); + uint32_t ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.", ret); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp b/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp new file mode 100644 index 000000000..ff2bd4e91 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dm_thread.h" + +namespace OHOS { +namespace DistributedHardware { +using funcstr = void (*)(std::map>, DmDeviceInfo); + +funcstr DmThread::funcName_; +std::map> DmThread::parameter1_ = {}; +DmDeviceInfo DmThread::parameter2_; + +DmThread::DmThread(funcstr funcname,\ + std::map> parameter1,\ + DmDeviceInfo parameter2) +{ + funcName_ = funcname; + parameter1_ = parameter1; + parameter2_ = parameter2; + parameterGroup_.member1 = parameter1; + parameterGroup_.member2 = parameter2; +} + +void* DmThread::PthreadDeviceStart(void* parameterInfo) +{ + PthreadCallbackParameter *parameterStruct = static_cast(parameterInfo); + funcName_(parameterStruct->member1, parameterStruct->member2); + return nullptr; +} + +void DmThread::DmCreatThread() +{ + pthread_t tid; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_create(&tid, &attr, PthreadDeviceStart, static_cast(¶meterGroup_)); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp index 4168ce99e..e5c1f6357 100644 --- a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp +++ b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp @@ -17,9 +17,10 @@ #include "dm_constants.h" #include "dm_log.h" +#if !defined(__LITEOS_M__) #include "os_account_manager.h" - using namespace OHOS::AccountSA; +#endif namespace OHOS { namespace DistributedHardware { @@ -27,12 +28,16 @@ int32_t MultipleUserConnector::oldUserId_ = -1; int32_t MultipleUserConnector::GetCurrentAccountUserID(void) { +#if defined(__LITEOS_M__) + return 0; +#else std::vector ids; ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); if (ret != ERR_OK || ids.empty()) { return -1; } return ids[0]; +#endif } void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 40f6707cc..b1965714e 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -17,8 +17,13 @@ #include #include +#if defined(__LITEOS_M__) +#include "dm_mutex.h" +#include "dm_thread.h" +#else #include #include +#endif #include "dm_anonymous.h" #include "dm_constants.h" @@ -49,12 +54,17 @@ INodeStateCb SoftbusConnector::softbusNodeStateCb_ = { .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged}; + void DeviceOnLine(std::map> stateCallbackMap, DmDeviceInfo deviceInfo) { LOGI("Device on line start"); +#if defined(__LITEOS_M__) + DmMutex lockDeviceOnLine; +#else std::mutex lockDeviceOnLine; std::lock_guard lock(lockDeviceOnLine); +#endif for (auto &iter : stateCallbackMap) { iter.second->OnDeviceOnline(iter.first, deviceInfo); } @@ -65,8 +75,12 @@ void DeviceOffLine(std::map> DmDeviceInfo deviceInfo) { LOGI("Device off line start"); +#if defined(__LITEOS_M__) + DmMutex lockDeviceOffLine; +#else std::mutex lockDeviceOffLine; std::lock_guard lock(lockDeviceOffLine); +#endif for (auto &iter : stateCallbackMap) { iter.second->OnDeviceOffline(iter.first, deviceInfo); } @@ -106,7 +120,10 @@ int32_t SoftbusConnector::Init() dmPublishInfo.capability = DM_CAPABILITY_OSD; dmPublishInfo.capabilityData = nullptr; dmPublishInfo.dataLen = 0; - +#if defined(__LITEOS_M__) + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); + LOGI("service publish result is : %d", ret); +#else char discoverStatus[DISCOVER_STATUS_LEN + 1] = {0}; ret = GetParameter(DISCOVER_STATUS_KEY.c_str(), "not exist", discoverStatus, DISCOVER_STATUS_LEN); if (strcmp(discoverStatus, "not exist") == 0) { @@ -133,7 +150,8 @@ int32_t SoftbusConnector::Init() } ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); - LOGI("register Watch Parameter result is : %d"); + LOGI("register Watch Parameter result is : %d", ret); +#endif return ret; } @@ -448,12 +466,12 @@ void SoftbusConnector::CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, dmDeviceInfo.deviceTypeId = deviceInfo.devType; } -void SoftbusConnector::OnPublishSuccess(int32_t publishId) +void SoftbusConnector::OnPublishSuccess(int publishId) { LOGI("SoftbusConnector::OnPublishSuccess, publishId: %d", publishId); } -void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason) +void SoftbusConnector::OnPublishFail(int publishId, PublishFailReason reason) { LOGI("SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason); } @@ -468,8 +486,13 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); +#if defined(__LITEOS_M__) + DmThread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); + deviceOnLine.DmCreatThread(); +#else std::thread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); deviceOnLine.detach(); +#endif if (discoveryDeviceInfoMap_.empty()) { return; @@ -495,8 +518,13 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) } DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); +#if defined(__LITEOS_M__) + DmThread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); + deviceOffLine.DmCreatThread(); +#else std::thread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); deviceOffLine.detach(); +#endif } void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) @@ -534,7 +562,7 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) } } -void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason) +void SoftbusConnector::OnSoftbusDiscoveryFailed(int subscribeId, DiscoveryFailReason failReason) { LOGI("In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason); uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); @@ -543,7 +571,7 @@ void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFa } } -void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) +void SoftbusConnector::OnSoftbusDiscoverySuccess(int subscribeId) { LOGI("In, subscribeId %d", subscribeId); uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 8d4b55795..df6fb2fb0 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -119,7 +119,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) return DM_OK; } -int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) +int SoftbusSession::OnSessionOpened(int sessionId, int result) { int32_t sessionSide = GetSessionSide(sessionId); sessionCallback_->OnSessionOpened(sessionId, sessionSide, result); @@ -127,12 +127,12 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) return DM_OK; } -void SoftbusSession::OnSessionClosed(int32_t sessionId) +void SoftbusSession::OnSessionClosed(int sessionId) { LOGI("OnSessionClosed, sessionId:%d", sessionId); } -void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { LOGI("OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen); if (sessionId < 0 || data == nullptr || dataLen <= 0) { diff --git a/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp new file mode 100644 index 000000000..80cf42498 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_timer.h" +#include "cmsis_os2.h" +#include "securec.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const int32_t MILL_SECONDS_PER_SECOND = 1000; +} +DmTimer::DmTimer(const std::string &name) +{ + if (name.empty()) { + LOGI("DmTimer name is null"); + return; + } + mStatus_ = DmTimerStatus::DM_STATUS_INIT; + mTimeOutSec_ = 0; + mTimerName_ = name; +} + +DmTimer::~DmTimer() +{ + if (mTimerName_.empty()) { + LOGI("DmTimer is not init"); + return; + } + LOGI("DmTimer %s Destroy in", mTimerName_.c_str()); +} + +struct DmTimst { + TimeoutHandle handle; + DmTimer *dmtimer; + void *data; +}; + +static void handler(void *data) +{ + struct DmTimst *myTimer = (struct DmTimst *)data; + myTimer->handle(myTimer->data, *(myTimer->dmtimer)); +} + +DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) +{ + if (mTimerName_.empty() || handle == nullptr || data == nullptr) { + LOGI("DmTimer is not init or param empty"); + return DmTimerStatus::DM_STATUS_FINISH; + } + LOGI("DmTimer %s start timeout(%d)", mTimerName_.c_str(), timeOut); + if (mStatus_ != DmTimerStatus::DM_STATUS_INIT) { + return DmTimerStatus::DM_STATUS_BUSY; + } + + static struct DmTimst myTimer = { + .handle = handle, + .dmtimer = this, + .data = data, + }; + mTimeOutSec_ = timeOut; + + void *id = osTimerNew((osTimerFunc_t)handler, osTimerType_t::osTimerOnce, (void *)&myTimer, NULL); + if (id != NULL) { + LOGI("Get name of a timer success "); + } else { + LOGI("Get name of a timer failed"); + return DmTimerStatus::DM_STATUS_CREATE_ERROR; + } + + timerId = id; + int stOk = osTimerStart(timerId, timeOut * osKernelGetTickFreq()); + if (stOk == 0) { + LOGI("DmTimer %s start timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); + mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; + } else { + LOGI("Start a timer failed"); + (void)osTimerDelete(timerId); + } + + return mStatus_; +} + +void DmTimer::Stop(int32_t code) +{ + LOGI("DmTimer Stop code (%d)", code); + if (timerId != NULL) { + osTimerDelete(timerId); + timerId = NULL; + } + LOGI("DmTimer %s end timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); + return; +} + +std::string DmTimer::GetTimerName() +{ + return mTimerName_; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index cda681629..51cb6232b 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -17,16 +17,18 @@ #include -#include "common_event_support.h" + #include "device_manager_service_listener.h" -#include "dm_common_event_manager.h" #include "dm_constants.h" #include "dm_device_info_manager.h" #include "dm_log.h" #include "multiple_user_connector.h" #include "permission_manager.h" - +#if !defined(__LITEOS_M__) +#include "dm_common_event_manager.h" +#include "common_event_support.h" using namespace OHOS::EventFwk; +#endif namespace OHOS { namespace DistributedHardware { @@ -35,10 +37,12 @@ IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); +#if !defined(__LITEOS_M__) DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { LOGI("subscribe service event success"); } +#endif softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); hiChainConnector_->UnRegisterHiChainCallback(); } @@ -113,14 +117,14 @@ int32_t DeviceManagerService::Init() LOGI("get current account user id success"); MultipleUserConnector::SetSwitchOldUserId(userId); } - +#if !defined(__LITEOS_M__) DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), std::placeholders::_1); if (dmCommonEventManager.SubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED, callback)) { LOGI("subscribe service user switch common event success"); } - +#endif LOGI("Init success, singleton initialized"); intFlag_ = true; return DM_OK; diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 1cef6db56..ff0ba6060 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 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 @@ -26,12 +26,18 @@ const int32_t SESSION_CANCEL_TIMEOUT = 0; static void TimeOut(void *data, DmTimer& timer) { - LOGE("time out "); + LOGI("time out %s", timer.GetTimerName().c_str()); + if (data == nullptr || timer.GetTimerName().find(TIMER_PREFIX) != TIMER_DEFAULT) { + LOGE("time out is not our timer"); + return; + } + DmDeviceStateManager *deviceStateMgr = (DmDeviceStateManager*)data; if (deviceStateMgr == nullptr) { - LOGE("OnDeviceOfflineTimeOut deviceStateMgr = nullptr"); + LOGE("deviceStateMgr is nullptr"); return; } + deviceStateMgr->DeleteTimeOutGroup(timer.GetTimerName()); } @@ -64,7 +70,11 @@ int32_t DmDeviceStateManager::RegisterProfileListener(const std::string &pkgName DmDeviceInfo saveInfo = info; SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid); { +#if defined(__LITEOS_M__) + DmMutex mutexLock; +#else std::lock_guard mutexLock(remoteDeviceInfosMutex_); +#endif remoteDeviceInfos_[uuid] = saveInfo; } LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s, uuid = %s", @@ -84,7 +94,11 @@ int32_t DmDeviceStateManager::UnRegisterProfileListener(const std::string &pkgNa profileAdapter->UnRegisterProfileListener(pkgName); } { +#if defined(__LITEOS_M__) + DmMutex mutexLock; +#else std::lock_guard mutexLock(remoteDeviceInfosMutex_); +#endif if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { remoteDeviceInfos_.erase(std::string(info.deviceId)); } @@ -193,7 +207,11 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: } DmDeviceInfo saveInfo; { +#if defined(__LITEOS_M__) + DmMutex mutexLock; +#else std::lock_guard mutexLock(remoteDeviceInfosMutex_); +#endif auto iter = remoteDeviceInfos_.find(deviceId); if (iter == remoteDeviceInfos_.end()) { LOGE("OnProfileReady complete not find deviceId: %s", GetAnonyString(deviceId).c_str()); @@ -242,43 +260,53 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) return; } LOGI("Register OffLine Timer with device: %s", GetAnonyString(deviceId).c_str()); - +#if defined(__LITEOS_M__) + DmMutex mutexLock; +#else std::lock_guard mutexLock(timerMapMutex_); - deviceinfoMap_[deviceInfo.deviceId] = deviceId; - auto iter = timerMap_.find(deviceId); - if (iter != timerMap_.end()) { - iter->second->Stop(SESSION_CANCEL_TIMEOUT); - return; +#endif + for (auto &iter : stateTimerInfoMap_) { + if (iter.second.netWorkId == deviceInfo.deviceId) { + iter.second.timer->Stop(SESSION_CANCEL_TIMEOUT); + return; + } } - std::shared_ptr offLineTimer = std::make_shared(deviceId); + + std::string timerName = TIMER_PREFIX + STATE_TIMER_PREFIX + std::to_string(stateTimerInfoMap_.size()); + std::shared_ptr offLineTimer = std::make_shared(timerName); if (offLineTimer != nullptr) { - timerMap_[deviceId] = offLineTimer; + StateTimerInfo stateTimer = { + .timerName = timerName, + .netWorkId = deviceInfo.deviceId, + .deviceId = deviceId, + .timer = offLineTimer + }; + stateTimerInfoMap_[timerName] = stateTimer; } } void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) { - if (deviceinfoMap_.find(deviceInfo.deviceId) == deviceinfoMap_.end()) { - LOGE("fail to get udid by networkId"); - return; - } - - LOGI("start offline timer with device: %s", GetAnonyString(deviceinfoMap_[deviceInfo.deviceId]).c_str()); - std::lock_guard mutexLock(timerMapMutex_); - for (auto &iter : timerMap_) { - if (iter.first == deviceinfoMap_[deviceInfo.deviceId]) { - iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); + LOGI("start offline timer"); + for (auto &iter : stateTimerInfoMap_) { + if (iter.second.netWorkId == deviceInfo.deviceId) { + iter.second.timer->Start(OFFLINE_TIMEOUT, TimeOut, this); } } - deviceinfoMap_.erase(deviceInfo.deviceId); } -void DmDeviceStateManager::DeleteTimeOutGroup(std::string deviceId) +void DmDeviceStateManager::DeleteTimeOutGroup(std::string stateTimer) { - LOGI("remove hichain group with device: %s", GetAnonyString(deviceId).c_str()); + std::lock_guard mutexLock(timerMapMutex_); if (hiChainConnector_ != nullptr) { - hiChainConnector_->DeleteTimeOutGroup(deviceId.c_str()); + auto iter = stateTimerInfoMap_.find(stateTimer); + if (iter != stateTimerInfoMap_.end()) { + LOGI("remove hichain group with device: %s", + GetAnonyString(stateTimerInfoMap_[stateTimer].deviceId).c_str()); + hiChainConnector_->DeleteTimeOutGroup(stateTimerInfoMap_[stateTimer].deviceId.c_str()); + } } + stateTimerInfoMap_.erase(stateTimer); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp new file mode 100644 index 000000000..06e21ae6c --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "command_dispatch.h" +#include "dm_log.h" +#include "message_def.h" +#include "dm_constants.h" +#include "server_stub.h" +#include "securec.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "get_trustdevice_req.h" +#include "start_discovery_req.h" +#include "stop_discovery_req.h" +#include "get_useroperation_req.h" +#include "authenticate_device_req.h" +#include "verify_authenticate_req.h" +#include "get_trustdevice_rsp.h" +#include "device_manager_service.h" +#include "get_local_device_info_rsp.h" +#include "get_info_by_network_rsp.h" +#include "get_info_by_network_req.h" +#include "unauthenticate_device_req.h" +#include "get_dmfaparam_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(CommandDispatch); + +int32_t CommandDispatch::MessageSendCmd(int32_t cmdCode, const std::shared_ptr &req, + const std::shared_ptr &rsp) +{ + if (req == nullptr || rsp == nullptr) { + LOGE("Message req or rsp is null."); + return DM_INVALID_VALUE; + } + uint32_t i = 0; + for (i = 0; i < (sizeof(g_cmdMap) / sizeof(g_cmdMap[0])); i++) { + if (g_cmdMap[i].cmdCode == cmdCode) { + break; + } + } + int32_t ret = g_cmdMap[i].MsgProcess(req, rsp); + if (ret != DM_OK) { + LOGE("MessageSendCmd Failed with ret: %d", ret); + return ret; + } + return DM_OK; +} + +void CommandDispatch::AddPkgName(const std::string &pkgName) +{ + dmPkgName_.push_back(pkgName); +} + +void CommandDispatch::DeletePkgName(const std::string &pkgName) +{ + dmPkgName_.remove(pkgName); +} + +const std::list& CommandDispatch::GetPkgNameList() const +{ + return dmPkgName_; +} + +static int32_t GetTrustedDeviceList(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr prsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + + LOGI("enter GetTrustedDeviceList"); + std::vector deviceList; + int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + prsp->SetDeviceVec(deviceList); + prsp->SetErrCode(ret); + return ret; +} + +static int32_t GetLocalDeviceInfo(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + DmDeviceInfo dmDeviceInfo = {0}; + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo); + DmDeviceInfo *Info = &dmDeviceInfo; + if (Info != nullptr) { + pRsp->SetLocalDeviceInfo(dmDeviceInfo); + } + pRsp->SetErrCode(ret); + return ret; +} + +static int32_t GetUdidByNetworkId(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + std::string netWorkId = pReq->GetNetWorkId(); + std::string udid; + + int32_t ret = DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, netWorkId, udid); + pRsp->SetUdid(udid); + pRsp->SetErrCode(ret); + return ret; +} + +static int32_t GetUuidByNetworkId(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + std::string netWorkId = pReq->GetNetWorkId(); + std::string uuid; + + int32_t ret = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); + pRsp->SetUuid(uuid); + pRsp->SetErrCode(ret); + return ret; +} + +static int32_t StartDeviceDiscovery(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); + LOGI("StartDeviceDiscovery service"); + + int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, dmSubscribeInfo, extra); + rsp->SetErrCode(ret); + return ret; +} + +static int32_t StopDeviceDiscovery(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + LOGI("StopDeviceDiscovery service"); + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + + int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + rsp->SetErrCode(ret); + return ret; +} + +static int32_t SetUserOperation(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + int32_t action = pReq->GetOperation(); + + LOGI("enter server user authorization operation."); + + int32_t ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action); + rsp->SetErrCode(ret); + return ret; +} + +static int32_t GetFaParam(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + DmAuthParam authParam = { + .authToken = "", + .packageName = "", + .appName = "", + .appDescription = "", + .authType = 0, + .business = 0, + .pincode = 0, + .direction = 0, + .pinToken = 0 + }; + + LOGI("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", pkgName.c_str()); + + int32_t ret = DeviceManagerService::GetInstance().GetFaParam(pkgName, authParam); + pRsp->SetDmAuthParam(authParam); + pRsp->SetErrCode(ret); + return ret; +} + +static int32_t AuthenticateDevice(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + int32_t authType = pReq->GetAuthType(); + std::string deviceId = deviceInfo.deviceId; + + LOGI("DeviceManagerStub:: AUTHENTCATION_DEVICE:pkgName:%s", pkgName.c_str()); + + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + rsp->SetErrCode(ret); + return ret; +} + +static int32_t UnAuthenticateDevice(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + std::string deviceId = deviceInfo.deviceId; + + LOGI("enter server user authorization operation."); + int32_t ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + rsp->SetErrCode(ret); + return ret; +} + +static int32_t VerifyAuthentication(const std::shared_ptr &req, const std::shared_ptr &rsp) +{ + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + std::string authParam = pReq->GetAuthPara(); + + LOGI("DeviceManagerStub:: VERIFY_AUTHENTCATION:pkgName:%s", pkgName.c_str()); + + int32_t ret = DeviceManagerService::GetInstance().VerifyAuthentication(authParam); + rsp->SetErrCode(ret); + return ret; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp b/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp new file mode 100644 index 000000000..11568e07f --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_service_listener.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "device_manager_notify.h" +#include "command_dispatch.h" + +namespace OHOS { +namespace DistributedHardware { +void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, + const DmDeviceInfo &info) +{ + LOGI("call OnDeviceStateChange, state=%d", state); + std::list pkgNameList = CommandDispatch::GetInstance().GetPkgNameList(); + for (auto pkgName : pkgNameList) { + DmDeviceState deviceState = static_cast(state); + if (pkgName == "") { + LOGE("OnDeviceOnline, get para failed"); + return; + } + switch (deviceState) { + case DEVICE_STATE_ONLINE: + DeviceManagerNotify::GetInstance().OnDeviceOnline(pkgName, info); + break; + case DEVICE_STATE_OFFLINE: + DeviceManagerNotify::GetInstance().OnDeviceOffline(pkgName, info); + break; + case DEVICE_INFO_CHANGED: + DeviceManagerNotify::GetInstance().OnDeviceChanged(pkgName, info); + break; + default: + LOGE("unknown device state:%d", deviceState); + break; + } + } +} + +void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, + const DmDeviceInfo &info) +{ + LOGI("call OnDeviceFound for %s, originId %d, deviceId %s", pkgName.c_str(), subscribeId, + GetAnonyString(std::string(info.deviceId)).c_str()); + DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, info); +} + +void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, + int32_t failedReason) +{ + LOGI("call OnDiscoveryFailed"); + DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); +} + +void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +{ + LOGI("call OnDiscoverySuccess"); + DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); +} + +void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, + const std::string &token, int32_t status, int32_t reason) +{ + LOGI("call package: %s, deviceId: %s", pkgName.c_str(), GetAnonyString(deviceId).c_str()); + DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, token, status, reason); +} + +void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, const std::string &flag) +{ + LOGI("call OnVerifyAuthResult"); + std::list pkgNameList = CommandDispatch::GetInstance().GetPkgNameList(); + for (auto pkgName : pkgNameList) { + DeviceManagerNotify::GetInstance().OnVerifyAuthResult(pkgName, deviceId, resultCode, stoi(flag)); + } +} + +void DeviceManagerServiceListener::OnFaCall(std::string &pkgName, std::string ¶mJson) +{ + LOGI("call OnFaCall in"); + DeviceManagerNotify::GetInstance().OnFaCall(pkgName, paramJson); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dispatch/server_stub.cpp b/services/devicemanagerservice/src/dispatch/server_stub.cpp new file mode 100644 index 000000000..28a106516 --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/server_stub.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "server_stub.h" +#include "securec.h" +#include "ohos_init.h" +#include "samgr_lite.h" +#include "iproxy_server.h" +#include "dm_log.h" +#include "dm_subscribe_info.h" + +#include "message_def.h" +#include "device_manager_service.h" + +namespace { + const int32_t WAIT_FOR_SERVER = 2; + const int32_t STACK_SIZE = 0x1000; + const int32_t QUEUE_SIZE = 32; +} + +using namespace OHOS::DistributedHardware; + +struct DefaultFeatureApi { + INHERIT_SERVER_IPROXY; +}; + +struct DeviceManagerSamgrService { + INHERIT_SERVICE; + INHERIT_IUNKNOWNENTRY(DefaultFeatureApi); + Identity identity; +}; + + +static const char *GetName(Service *service) +{ + (void)service; + return DEVICE_MANAGER_SERVICE_NAME; +} + +static BOOL Initialize(Service *service, Identity identity) +{ + if (service == NULL) { + LOGW("Initialize invalid param"); + return FALSE; + } + + const int32_t DM_SERVICE_INIT_DELAY = 2; + sleep(DM_SERVICE_INIT_DELAY); + SAMGR_Bootstrap(); + + DeviceManagerService::GetInstance().Init(); + + DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; + mgrService->identity = identity; + return TRUE; +} + +static BOOL MessageHandle(Service *service, Request *request) +{ + if ((service == NULL) || (request == NULL)) { + LOGW("MessageHandle invalid param"); + return FALSE; + } + return TRUE; +} + +static TaskConfig GetTaskConfig(Service *service) +{ + (void)service; + TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL, STACK_SIZE, QUEUE_SIZE, SHARED_TASK}; + return config; +} + +static void DevMgrSvcInit(void) +{ + sleep(WAIT_FOR_SERVER); + static DeviceManagerSamgrService service = { + .GetName = GetName, + .Initialize = Initialize, + .MessageHandle = MessageHandle, + .GetTaskConfig = GetTaskConfig, + SERVER_IPROXY_IMPL_BEGIN, + .Invoke = NULL, + IPROXY_END, + }; + + if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) { + LOGE("%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + if (!SAMGR_GetInstance()->RegisterDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME, GET_IUNKNOWN(service))) { + LOGE("%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + LOGI("%s, init success", DEVICE_MANAGER_SERVICE_NAME); +} + +SYSEX_SERVICE_INIT(DevMgrSvcInit); diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 97f5c361e..65d19605d 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -20,7 +20,51 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - shared_library("devicemanagerutils") { + if (ohos_kernel_type == "liteos_m") { + static_library("devicemanagerutils_mini") { + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/permission/lite", + "${common_path}/include", + ] + + include_dirs += [ + "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", + "//utils/native/lite/include", + "//utils/system/safwk/native/include", + "//third_party/json/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + ] + + sources = [ + "${utils_path}/src/dm_anonymous.cpp", + "${utils_path}/src/dm_log.cpp", + "${utils_path}/src/dm_random.cpp", + "${utils_path}/src/permission/lite/permission_manager.cpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerutils\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", + "//foundation/distributedschedule/samgr_lite/samgr", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/mbedtls", + "//third_party/mbedtls:mbedtls_shared", + "//utils/native/lite:utils", + ] + } + } else { + shared_library("devicemanagerutils") { + } } } else { config("devicemanagerutils_config") { diff --git a/utils/src/dm_random.cpp b/utils/src/dm_random.cpp index 738d33442..952a4e51a 100644 --- a/utils/src/dm_random.cpp +++ b/utils/src/dm_random.cpp @@ -28,10 +28,15 @@ namespace OHOS { namespace DistributedHardware { int32_t GenRandInt(int32_t randMin, int32_t randMax) { +#if defined(__LITEOS_M__) + srandom(time(NULL)); + return (randMin + random() % (randMax - randMin)); +#else std::random_device randDevice; std::mt19937 genRand(randDevice()); std::uniform_int_distribution disRand(randMin, randMax); return disRand(genRand); +#endif } int64_t GenRandLongLong(int64_t randMin, int64_t randMax) -- Gitee