From d1f1183f864e4da20fd517eae1ed60c3cb32d2a6 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Wed, 12 Jan 2022 21:46:01 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E6=96=B0device=20manager=E5=B7=A5=E7=A8=8B?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=B8=8A=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: cao_liu_chao --- BUILD.gn | 18 +- common/include/constants.h | 167 --- common/include/device_manager_errno.h | 61 - common/include/device_manager_log.h | 29 - common/include/ipc/ipc_def.h | 38 +- .../ipc/model/ipc_authenticate_device_req.h | 32 +- .../ipc/model/ipc_check_authenticate_req.h | 40 - .../model/ipc_get_authenticationparam_rsp.h | 41 - .../ipc/model/ipc_get_trustdevice_req.h | 18 +- .../ipc/model/ipc_get_trustdevice_rsp.h | 17 +- .../ipc/model/ipc_notify_auth_result_req.h | 28 +- .../model/ipc_notify_check_auth_result_req.h | 64 - .../ipc/model/ipc_notify_device_found_req.h | 19 +- .../ipc/model/ipc_notify_device_state_req.h | 19 +- .../model/ipc_notify_discover_result_req.h | 18 +- .../ipc/model/ipc_notify_dmfa_result_req.h | 12 +- .../ipc/model/ipc_register_listener_req.h | 11 +- common/include/ipc/model/ipc_req.h | 16 +- common/include/ipc/model/ipc_rsp.h | 12 +- .../ipc/model/ipc_set_useroperation_req.h | 10 +- .../ipc/model/ipc_start_discovery_req.h | 30 +- .../ipc/model/ipc_stop_discovery_req.h | 14 +- common/include/single_instance.h | 36 +- devicemanager.gni | 10 +- ...hos.distributedHardware.deviceManager.d.ts | 476 -------- display/build.gradle | 57 - display/entry/build.gradle | 42 - display/entry/src/main/config.json | 61 - display/entry/src/main/js/default/app.js | 23 - .../entry/src/main/js/default/i18n/en-US.json | 4 - .../entry/src/main/js/default/i18n/zh-CN.json | 4 - .../src/main/js/default/pages/index/index.css | 169 --- .../src/main/js/default/pages/index/index.hml | 98 -- .../src/main/js/default/pages/index/index.js | 331 ------ .../main/resources/base/element/string.json | 12 - .../src/main/resources/base/media/icon.png | Bin 6790 -> 0 bytes display/settings.gradle | 1 - interfaces/inner_kits/native_cpp/BUILD.gn | 21 +- .../native_cpp/include/device_manager.h | 57 +- .../include/device_manager_callback.h | 48 +- .../native_cpp/include/device_manager_impl.h | 74 +- .../native_cpp/include/dm_app_image_info.h | 32 +- .../native_cpp/include/dm_device_info.h | 18 +- .../native_cpp/include/dm_subscribe_info.h | 10 +- .../native_cpp/include/ipc/ipc_client.h | 17 +- .../native_cpp/include/ipc/ipc_client_proxy.h | 21 +- .../include/ipc/lite/ipc_client_manager.h | 21 +- .../ipc/lite/ipc_client_server_proxy.h | 17 +- .../include/ipc/lite/ipc_client_stub.h | 17 +- .../include/ipc/standard/ipc_client_manager.h | 30 +- .../ipc/standard/ipc_client_server_proxy.h | 15 +- .../include/ipc/standard/ipc_client_stub.h | 17 +- .../include/ipc/standard/ipc_remote_broker.h | 16 +- .../include/notify/device_manager_notify.h | 77 +- .../native_cpp/src/device_manager.cpp | 2 +- .../native_cpp/src/device_manager_impl.cpp | 528 ++++++--- .../native_cpp/src/ipc/ipc_client_proxy.cpp | 18 +- .../src/ipc/lite/ipc_client_manager.cpp | 53 +- .../src/ipc/lite/ipc_client_server_proxy.cpp | 63 +- .../src/ipc/lite/ipc_client_stub.cpp | 25 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 235 ++-- .../src/ipc/standard/ipc_client_manager.cpp | 81 +- .../ipc/standard/ipc_client_server_proxy.cpp | 21 +- .../src/ipc/standard/ipc_client_stub.cpp | 25 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 433 ++++--- .../src/notify/device_manager_notify.cpp | 186 +-- interfaces/kits/js/BUILD.gn | 15 +- interfaces/kits/js/include/dm_native_event.h | 9 +- .../kits/js/include/native_devicemanager_js.h | 167 ++- interfaces/kits/js/src/dm_native_event.cpp | 24 +- .../kits/js/src/native_devicemanager_js.cpp | 1033 ++++++++++++----- ohos.build | 7 +- sa_profile/4802.xml | 8 +- services/devicemanagerservice/BUILD.gn | 190 --- .../include/ability/dm_ability_manager.h | 65 -- .../include/auth/hichain_connector.h | 96 -- .../include/ipc/ipc_server_adapter.h | 50 - .../include/ipc/ipc_server_listener_adapter.h | 43 - .../include/ipc/lite/ipc_server_listener.h | 41 - .../include/ipc/lite/ipc_server_listenermgr.h | 50 - .../include/ipc/lite/ipc_server_stub.h | 26 - .../ipc/standard/ipc_server_client_proxy.h | 35 - .../ipc/standard/ipc_server_listener.h | 36 - .../include/ipc/standard/ipc_server_stub.h | 76 -- .../include/message/msg_codec.h | 46 - .../include/message/msg_head.h | 48 - .../include/message/msg_request_auth.h | 79 -- .../include/message/msg_response_auth.h | 60 - .../include/message/msg_sync_group.h | 45 - .../include/requestauth/auth_manager.h | 65 -- .../include/requestauth/request_session.h | 86 -- .../include/requestauth/response_session.h | 81 -- .../include/softbus/softbus_adapter.h | 78 -- .../include/softbus/softbus_session.h | 53 - .../include/timer/dm_timer.h | 71 -- .../src/ability/lite/dm_ability_manager.cpp | 54 - .../ability/standard/dm_ability_manager.cpp | 97 -- .../src/auth/hichain_connector.cpp | 490 -------- .../src/ipc/ipc_server_adapter.cpp | 198 ---- .../src/ipc/ipc_server_listener_adapter.cpp | 128 -- .../src/ipc/lite/ipc_cmd_parser.cpp | 283 ----- .../src/ipc/lite/ipc_server_listener.cpp | 93 -- .../src/ipc/lite/ipc_server_listenermgr.cpp | 65 -- .../src/ipc/lite/ipc_server_main.cpp | 52 - .../src/ipc/lite/ipc_server_stub.cpp | 228 ---- .../src/ipc/standard/ipc_cmd_parser.cpp | 372 ------ .../ipc/standard/ipc_server_client_proxy.cpp | 48 - .../src/ipc/standard/ipc_server_listener.cpp | 48 - .../src/ipc/standard/ipc_server_stub.cpp | 199 ---- .../src/message/msg_codec.cpp | 113 -- .../src/message/msg_head.cpp | 52 - .../src/message/msg_request_auth.cpp | 381 ------ .../src/message/msg_response_auth.cpp | 160 --- .../src/message/msg_sync_group.cpp | 67 -- .../src/requestauth/auth_manager.cpp | 288 ----- .../src/requestauth/request_session.cpp | 258 ---- .../src/requestauth/response_session.cpp | 343 ------ .../src/softbus/softbus_adapter.cpp | 522 --------- .../src/softbus/softbus_session.cpp | 230 ---- .../src/timer/dm_timer.cpp | 153 --- test/BUILD.gn | 18 - test/unittest/BUILD.gn | 78 -- test/unittest/device_manager_impl_test.cpp | 185 --- test/unittest/device_manager_impl_test.h | 50 - test/unittest/mock/mock_ipc_client_proxy.h | 33 - utils/BUILD.gn | 32 +- utils/include/anonymous_string.h | 26 - utils/include/cipher/encrypt_utils.h | 46 - utils/include/ipc/lite/ipc_cmd_register.h | 99 +- utils/include/ipc/standard/ipc_cmd_register.h | 73 +- utils/include/log/dm_log.h | 31 - utils/src/anonymous_string.cpp | 68 -- utils/src/cipher/encrypt_utils.cpp | 152 --- utils/src/ipc/lite/ipc_cmd_register.cpp | 30 +- utils/src/ipc/standard/ipc_cmd_register.cpp | 18 +- utils/src/log/dm_log.cpp | 89 -- 136 files changed, 2433 insertions(+), 10416 deletions(-) delete mode 100644 common/include/constants.h delete mode 100644 common/include/device_manager_errno.h delete mode 100644 common/include/device_manager_log.h delete mode 100644 common/include/ipc/model/ipc_check_authenticate_req.h delete mode 100644 common/include/ipc/model/ipc_get_authenticationparam_rsp.h delete mode 100644 common/include/ipc/model/ipc_notify_check_auth_result_req.h delete mode 100644 display/@ohos.distributedHardware.deviceManager.d.ts delete mode 100644 display/build.gradle delete mode 100644 display/entry/build.gradle delete mode 100644 display/entry/src/main/config.json delete mode 100644 display/entry/src/main/js/default/app.js delete mode 100644 display/entry/src/main/js/default/i18n/en-US.json delete mode 100644 display/entry/src/main/js/default/i18n/zh-CN.json delete mode 100644 display/entry/src/main/js/default/pages/index/index.css delete mode 100644 display/entry/src/main/js/default/pages/index/index.hml delete mode 100644 display/entry/src/main/js/default/pages/index/index.js delete mode 100644 display/entry/src/main/resources/base/element/string.json delete mode 100644 display/entry/src/main/resources/base/media/icon.png delete mode 100644 display/settings.gradle delete mode 100644 services/devicemanagerservice/BUILD.gn delete mode 100644 services/devicemanagerservice/include/ability/dm_ability_manager.h delete mode 100644 services/devicemanagerservice/include/auth/hichain_connector.h delete mode 100644 services/devicemanagerservice/include/ipc/ipc_server_adapter.h delete mode 100644 services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h delete mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h delete mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h delete mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h delete mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h delete mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h delete mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h delete mode 100644 services/devicemanagerservice/include/message/msg_codec.h delete mode 100644 services/devicemanagerservice/include/message/msg_head.h delete mode 100644 services/devicemanagerservice/include/message/msg_request_auth.h delete mode 100644 services/devicemanagerservice/include/message/msg_response_auth.h delete mode 100644 services/devicemanagerservice/include/message/msg_sync_group.h delete mode 100644 services/devicemanagerservice/include/requestauth/auth_manager.h delete mode 100644 services/devicemanagerservice/include/requestauth/request_session.h delete mode 100644 services/devicemanagerservice/include/requestauth/response_session.h delete mode 100644 services/devicemanagerservice/include/softbus/softbus_adapter.h delete mode 100644 services/devicemanagerservice/include/softbus/softbus_session.h delete mode 100644 services/devicemanagerservice/include/timer/dm_timer.h delete mode 100644 services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp delete mode 100644 services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp delete mode 100644 services/devicemanagerservice/src/auth/hichain_connector.cpp delete mode 100644 services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp delete mode 100644 services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp delete mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp delete mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp delete mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp delete mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp delete mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp delete mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp delete mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp delete mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp delete mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp delete mode 100644 services/devicemanagerservice/src/message/msg_codec.cpp delete mode 100644 services/devicemanagerservice/src/message/msg_head.cpp delete mode 100644 services/devicemanagerservice/src/message/msg_request_auth.cpp delete mode 100644 services/devicemanagerservice/src/message/msg_response_auth.cpp delete mode 100644 services/devicemanagerservice/src/message/msg_sync_group.cpp delete mode 100644 services/devicemanagerservice/src/requestauth/auth_manager.cpp delete mode 100644 services/devicemanagerservice/src/requestauth/request_session.cpp delete mode 100644 services/devicemanagerservice/src/requestauth/response_session.cpp delete mode 100644 services/devicemanagerservice/src/softbus/softbus_adapter.cpp delete mode 100644 services/devicemanagerservice/src/softbus/softbus_session.cpp delete mode 100644 services/devicemanagerservice/src/timer/dm_timer.cpp delete mode 100644 test/BUILD.gn delete mode 100644 test/unittest/BUILD.gn delete mode 100644 test/unittest/device_manager_impl_test.cpp delete mode 100644 test/unittest/device_manager_impl_test.h delete mode 100644 test/unittest/mock/mock_ipc_client_proxy.h delete mode 100644 utils/include/anonymous_string.h delete mode 100644 utils/include/cipher/encrypt_utils.h delete mode 100644 utils/include/log/dm_log.h delete mode 100644 utils/src/anonymous_string.cpp delete mode 100644 utils/src/cipher/encrypt_utils.cpp delete mode 100644 utils/src/log/dm_log.cpp diff --git a/BUILD.gn b/BUILD.gn index 103ee5a70..3fc86faf2 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -11,13 +11,17 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//build/lite/config/component/lite_component.gni") + if (defined(ohos_lite)) { - import("//build/lite/config/component/lite_component.gni") lite_component("devicemanager_lite") { - features = [ - "utils:devicemanagerutils", - "services/devicemanagerservice:devicemanagerservice", - "interfaces/inner_kits/native_cpp:devicemanagersdk", - ] + if (ohos_kernel_type == "liteos_m") { + } else { + features = [ + "utils:devicemanagerutils", + "services/devicemanagerservice:devicemanagerservice", + "interfaces/inner_kits/native_cpp:devicemanagersdk", + ] + } } -} +} \ No newline at end of file diff --git a/common/include/constants.h b/common/include/constants.h deleted file mode 100644 index f8cf91ac7..000000000 --- a/common/include/constants.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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_CONSTANTS_H -#define OHOS_DEVICE_MANAGER_CONSTANTS_H - -#include -#include - -namespace OHOS { -namespace DistributedHardware { - const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; - const std::string HOST_PKG_NAME_KEY = "hostPackageName"; - - const int32_t LOG_MAX_LEN = 512; - const int32_t MIN_PIN_TOKEN = 10000000; - const int32_t MAX_PIN_TOKEN = 90000000; - const int32_t MIN_PIN_CODE = 100000; - const int32_t MAX_PIN_CODE = 999999; - const int32_t TOKEN_LEN = 9; - - const int32_t FAIL = -1; - const int32_t SUCCESS = 0; - const int32_t ERROR_INPUT_PARA_EMPTY = 2000; - const int32_t ERROR_INPUT_PARA_INVALID = 2001; - const int32_t ERROR_TARGET_PKG_NAME_NULL = 2002; - const int32_t ERROR_PKG_NAME_NOT_ON_DISCOVERY = 2003; - const int32_t ERROR_START_REMOTE_DM = 2006; - const int32_t ERROR_OPEN_CHANNEL_FAIL = 2008; - const int32_t ERROR_SEND_COMMAND_FAIL = 2009; - const int32_t ERROR_CHANNEL_BROKEN = 2010; - const int32_t ERROR_DUPLICATE_REQUEST = 2011; - const int32_t ERROR_TIME_OUT = 2012; - const int32_t ERROR_REQUEST_CANCEL = 2013; - const int32_t ERROR_USER_REJECT = 2015; - const int32_t ERROR_USER_BUSY = 2016; - const int32_t ERROR_API_NOT_SUPPORT = 2018; - const int32_t ERROR_SESSION_NOT_EXIT = 2019; - const int32_t ERROR_CREAT_GROUP_FAIL = 2020; - const int32_t ERROR_JOIN_GROUP_FAIL = 2021; - const int32_t ERROR_GET_LOCAL_DEVICE_INFO_FAIL = 2022; - const int32_t ERROR_CHECK_AUTH_FAIL = 2023; - const int32_t ERROR_NETWORK_UNAVAILABLE = 2028; - const int32_t ERROR_DEVICE_INFO_NULL = 2030; - const int32_t ERROR_APP_NAME_NULL = 2031; - const int32_t ERROR_APP_DESCRIPTION_INVALID = 2032; - const int32_t ERROR_APP_ICON_INVALID = 2033; - const int32_t ERROR_APP_THUMBNAIL_INVALID = 2034; - const int32_t ERROR_FA_START_FAIL = 2100; - - const int32_t ENCRYPT_TAG_LEN = 32; - - const std::string TAG_REQUESTER = "REQUESTER"; - const std::string TAG_TOKEN = "TOKEN"; - const std::string TAG_HOST = "HOST"; - const std::string TAG_TARGET = "TARGET"; - const std::string TAG_VISIBILITY = "VISIBILITY"; - const std::string TAG_GROUPIDS = "GROUPIDLIST"; - const std::string TAG_REPLY = "REPLY"; - const std::string TAG_NET_ID = "NETID"; - const std::string TAG_GROUP_ID = "GROUPID"; - const std::string TAG_GROUP_NAME = "GROUPNAME"; - const std::string TAG_REQUEST_ID = "REQUESTID"; - const std::string TAG_DEVICE_ID = "DEVICEID"; - const std::string TAG_DEVICE_TYPE = "DEVICETYPE"; - const std::string TAG_APP_NAME = "APPNAME"; - const std::string TAG_APP_DESCRIPTION = "APPDESC"; - const std::string TAG_APP_ICON = "APPICON"; - const std::string TAG_APP_THUMBNAIL = "APPTHUM"; - const std::string TAG_INDEX = "INDEX"; - const std::string TAG_SLICE_NUM = "SLICE"; - const std::string TAG_THUMBNAIL_SIZE = "THUMSIZE"; - const std::string TAG_AUTH_TYPE = "AUTHTYPE"; - - const std::string TAG_VER = "ITF_VER"; - const std::string TAG_TYPE = "MSG_TYPE"; - const std::string DM_ITF_VER = "1.0"; - const std::string TAG = "DM_MSG_CODEC"; - - // GroupConstants - const int32_t GROUP_VISIBILITY_IS_PUBLIC = -1; - const int32_t GROUP_VISIBILITY_IS_PRIVATE = 0; - const std::string REQUEST_AUTH_ADD_ID = "REQUEST_AUTH_ADD_ID"; - const std::string INVITATE_AUTH_ADD_ID = "INVITE_AUTH_ADD_ID"; - const int32_t PIN_CODE_INVALID = -1; - - // AuthConstants - const int32_t AUTH_SESSION_SIDE_SERVER = 0; - const int32_t AUTH_SESSION_SIDE_CLIENT = 1; - const int32_t SESSION_TYPE_IS_DEVICE_AUTH = 0; - const int32_t SESSION_TYPE_IS_APP_AUTH = 1; - const int32_t SESSION_REPLY_UNKNOWN = -1; - const int32_t SESSION_REPLY_ACCEPT = 0; - const int32_t SESSION_REPLY_CANCEL = 1; - const int32_t SESSION_REPLY_TIMEOUT = 2; - const int32_t SESSION_REPLY_AUTH_CONFIRM_TIMEOUT = 2; - const int32_t SESSION_REPLY_CANCEL_PINCODE_DISPLAY = 3; - const int32_t SESSION_REPLY_CANCEL_PINCODE_INPUT = 4; - const int32_t SESSION_REPLY_CREAT_GROUP_FAILED = 7; - const int32_t REQUEST_OPERATION = 0; - const int32_t QR_OPERATION = 1; - const int32_t PIN_OPERATION = 2; - const int32_t START_ACTIVITY_DIALOG = 1; - const int32_t START_ACTIVITY_QR = 2; - const int32_t START_ACTIVITY_FINISH = 3; - const int32_t START_ACTIVITY_PIN = 4; - const int32_t AUTH_STATUS_SKIP = 3; - const int32_t DEFAULT_PIN_CODE = 0; - const int32_t DEFAULT_PIN_TOKEN = 0; - const std::string DEVICE_NAME_KEY = "deviceName"; - const std::string DISPLAY_TIME_KEY = "displayTime"; - const std::string QR_BITMAP_KEY = "qrBitMap"; - const std::string PIN_CODE_KEY = "pinCode"; - const std::string START_ACTIVITY_KEY = "startActivityType"; - const std::string AUTH_TYPE = "authType"; - const std::string TOKEN = "token"; - const std::string PIN_TOKEN = "pinToken"; - const int32_t MSG_TYPE_TO_REMOTE = 0; - const int32_t MSG_TYPE_TO_CLOSED_CHANNEL = 1; - const std::string APP_NAME_KEY = "appName"; - const std::string APP_DESCRIPTION_KEY = "appDescription"; - const std::string APP_ICON_KEY = "appIcon"; - const std::string APP_THUMBNAIL_KEY = "appThumbnail"; - const std::string CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; - const int32_t SLICE_NUM_INVALID = -1; - const int32_t AUTH_TYPE_QR = 0; - const int32_t AUTH_TYPE_PIN = 1; - const std::string DISPLAY_OWNER = "displayOwner"; - const int32_t DISPLAY_OWNER_SYSTEM = 0; - const int32_t DISPLAY_OWNER_OTHER = 1; - - // DmService constants - const int32_t MSG_MAX_SIZE = 45 * 1024; - const int32_t DES_SLICE_MAX_NUM = 5; - const int32_t ABILITY_ON = 1; - const int32_t ABILITY_INVALID = -1; - const int32_t DES_MAX_LEN = 256; - const int32_t ICON_MAX_LEN = 32 * 1024; - const int32_t THUMB_MAX_LEN = 153 * 1024; - - const int32_t DEVICE_UUID_LENGTH = 65; - const int32_t GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP = 1; - const int32_t GROUP_TYPE_PEER_TO_PEER_GROUP = 256; - - const int32_t GROUP_VISIBILITY_PUBLIC = -1; - - const int32_t BUSINESS_FA_MIRGRATION = 0; - const int32_t BUSINESS_RESOURCE_ACCESS = 1; - - // Base64 Constants - const int32_t BASE64_BYTE_LEN_3 = 3; - const int32_t BASE64_BYTE_LEN_4 = 4; -} -} -#endif diff --git a/common/include/device_manager_errno.h b/common/include/device_manager_errno.h deleted file mode 100644 index ab01276d9..000000000 --- a/common/include/device_manager_errno.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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_ERRNO_H -#define OHOS_DEVICE_MANAGER_ERRNO_H - -namespace OHOS { -namespace DistributedHardware { -enum { - DEVICEMANAGER_FAILED = (-10000), - DEVICEMANAGER_SERVICE_NOT_READY, - DEVICEMANAGER_DEVICE_ALREADY_TRUSTED, - DEVICEMANAGER_GET_TRUSTED_DEVICE_FAILED, - DEVICEMANAGER_ALREADY_INIT, - DEVICEMANAGER_INIT_FAILED, - DEVICEMANAGER_MALLOC_ERROR, - DEVICEMANAGER_LOCK_ERROR, - DEVICEMANAGER_INVALID_PARAM, - DEVICEMANAGER_INVALID_VALUE, - DEVICEMANAGER_COPY_FAILED, - DEVICEMANAGER_NULLPTR, - DEVICEMANAGER_DISCOVERY_FAILED, - DEVICEMANAGER_FLATTEN_OBJECT, - DEVICEMANAGER_WRITE_FAILED, - DEVICEMANAGER_IPC_FAILED, - DEVICEMANAGER_IPC_TRANSACTION_FAILED, - DEVICEMANAGER_IPC_NOT_REGISTER_FUNC, - HICHAIN_GROUP_CREATE_FAILED, - HICHAIN_MEMBER_ADD_FAILED, - HICHAIN_CREATE_CHANNEL_FAILED, - MSG_DECODE_PARA_FAILED, - ENCRYPT_UTILS_INVALID_PARAM, - ENCRYPT_UTILS_GCM_SETKEY_FAILED, - ENCRYPT_UTILS_GCM_CRYPT_FAILED, - ENCRYPT_UTILS_GCM_AUTH_DECRYPT_FAILED, - ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED, - ENCRYPT_UTILS_AES_GCM_DECRYPT_FAILED, - ERR_GEN_RANDOM_PINTOKEN_FAILED, - PIN_CODE_CHECK_FAILED, - PIN_TOKEN_CHECK_FAILED, - DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED, - DEVICEMANAGER_OPEN_SESSION_FAILED, - AUTH_PARA_INVALID, - ENCODE_DATA_ERROR, - DEVICEMANAGER_OK = 0 -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_ERRNO_H diff --git a/common/include/device_manager_log.h b/common/include/device_manager_log.h deleted file mode 100644 index fa0f776a3..000000000 --- a/common/include/device_manager_log.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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_LOG_H -#define OHOS_DEVICE_MANAGER_LOG_H - -#include - -#include "dm_log.h" - -namespace OHOS { -namespace DistributedHardware { -#define DMLOG(level, fmt, ...) DMLog(level, \ - (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LOG_H diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index b4dff8d42..ec3a93d3e 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,35 +21,39 @@ namespace DistributedHardware { #define DEVICE_MANAGER_SERVICE_NAME "dev_mgr_svc" #define MAX_DM_IPC_LEN 2048 -#define DECLARE_IPC_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_IPC_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_IPC_INTERFACE(className) \ - DECLARE_IPC_MODEL(className) +#define DECLARE_IPC_INTERFACE(className) DECLARE_IPC_MODEL(className) enum IpcCmdID { 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, - CHECK_AUTHENTICATION, + UNAUTHENTICATE_DEVICE, + VERIFY_AUTHENTICATION, SERVER_DEVICE_STATE_NOTIFY, SERVER_DEVICE_FOUND, SERVER_DISCOVER_FINISH, SERVER_AUTH_RESULT, - SERVER_CHECK_AUTH_RESULT, - SERVER_GET_AUTHENTCATION_INFO, - SERVER_USER_AUTHORIZATION_OPERATION, - SERVER_DEVICEMANAGER_FA_NOTIFY, + SERVER_VERIFY_AUTH_RESULT, + SERVER_GET_DMFA_INFO, + SERVER_USER_AUTH_OPERATION, + SERVER_DEVICE_FA_NOTIFY, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_authenticate_device_req.h b/common/include/ipc/model/ipc_authenticate_device_req.h index f4f066b3f..cb91c7743 100644 --- a/common/include/ipc/model/ipc_authenticate_device_req.h +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,20 +13,19 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_AUTHENTICATE_DEVICE_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_AUTHENTICATE_DEVICE_REQ_H - -#include "ipc_req.h" +#ifndef OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H +#define OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H #include "dm_device_info.h" -#include "dm_app_image_info.h" +#include "ipc_req.h" namespace OHOS { namespace DistributedHardware { class IpcAuthenticateDeviceReq : public IpcReq { -DECLARE_IPC_MODEL(IpcAuthenticateDeviceReq); + DECLARE_IPC_MODEL(IpcAuthenticateDeviceReq); + public: - const DmDeviceInfo& GetDeviceInfo() const + const DmDeviceInfo &GetDeviceInfo() const { return deviceInfo_; } @@ -36,30 +35,31 @@ public: deviceInfo_ = deviceInfo; } - const DmAppImageInfo& GetAppImageInfo() const + int32_t GetAuthType() { - return appImageInfo_; + return authType_; } - void SetAppImageInfo(const DmAppImageInfo &appImageInfo) + void SetAuthType(int32_t authType) { - appImageInfo_ = appImageInfo; + authType_ = authType; } - const std::string& GetExtra() const + const std::string &GetExtra() const { return extra_; } - void SetExtra(std::string &extra) + void SetExtra(const std::string &extra) { extra_ = extra; } + private: DmDeviceInfo deviceInfo_; - DmAppImageInfo appImageInfo_; + int32_t authType_; std::string extra_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_AUTHENTICATE_DEVICE_REQ_H +#endif // OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H diff --git a/common/include/ipc/model/ipc_check_authenticate_req.h b/common/include/ipc/model/ipc_check_authenticate_req.h deleted file mode 100644 index ea136b421..000000000 --- a/common/include/ipc/model/ipc_check_authenticate_req.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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_IPC_CHECK_AUTHENTICATE_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H - -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcCheckAuthenticateReq : public IpcReq { -DECLARE_IPC_MODEL(IpcCheckAuthenticateReq); -public: - const std::string& GetAuthPara() const - { - return authPara_; - } - - void SetAuthPara(std::string &authPara) - { - authPara_ = authPara; - } -private: - std::string authPara_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H diff --git a/common/include/ipc/model/ipc_get_authenticationparam_rsp.h b/common/include/ipc/model/ipc_get_authenticationparam_rsp.h deleted file mode 100644 index b12c39f68..000000000 --- a/common/include/ipc/model/ipc_get_authenticationparam_rsp.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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_IPC_GET_AUTH_PARAM_RSP_H -#define OHOS_DEVICE_MANAGER_IPC_GET_AUTH_PARAM_RSP_H - -#include "ipc_rsp.h" -#include "dm_device_info.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcGetAuthParamRsp : public IpcRsp { -DECLARE_IPC_MODEL(IpcGetAuthParamRsp); -public: - const DmAuthParam& GetAuthParam() const - { - return authParam_; - } - - void SetAuthParam(DmAuthParam &authParam) - { - authParam_ = authParam; - } -private: - DmAuthParam authParam_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_GET_AUTH_PARAM_RSP_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_get_trustdevice_req.h b/common/include/ipc/model/ipc_get_trustdevice_req.h index 695d87186..d4a0a85a5 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_req.h +++ b/common/include/ipc/model/ipc_get_trustdevice_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,28 +13,30 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_GET_TRUST_DEVICE_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_GET_TRUST_DEVICE_REQ_H +#ifndef OHOS_DM_IPC_GET_TRUST_DEVICE_REQ_H +#define OHOS_DM_IPC_GET_TRUST_DEVICE_REQ_H #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { -class IpcGetTrustdeviceReq : public IpcReq { -DECLARE_IPC_MODEL(IpcGetTrustdeviceReq); +class IpcGetTrustDeviceReq : public IpcReq { + DECLARE_IPC_MODEL(IpcGetTrustDeviceReq); + public: - const std::string& GetExtra() const + const std::string &GetExtra() const { return extra_; } - void SetExtra(std::string &extra) + void SetExtra(const std::string &extra) { extra_ = extra; } + private: std::string extra_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_GET_TRUST_DEVICE_REQ_H +#endif // OHOS_DM_IPC_GET_TRUST_DEVICE_REQ_H diff --git a/common/include/ipc/model/ipc_get_trustdevice_rsp.h b/common/include/ipc/model/ipc_get_trustdevice_rsp.h index 6df09e883..67260f38b 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_rsp.h +++ b/common/include/ipc/model/ipc_get_trustdevice_rsp.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,32 +13,33 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_GET_TRUSTDEVICE_RSP_H -#define OHOS_DEVICE_MANAGER_IPC_GET_TRUSTDEVICE_RSP_H +#ifndef OHOS_DM_IPC_GET_TRUST_DEVICE_RSP_H +#define OHOS_DM_IPC_GET_TRUST_DEVICE_RSP_H #include #include "dm_device_info.h" - #include "ipc_rsp.h" namespace OHOS { namespace DistributedHardware { -class IpcGetTrustdeviceRsp : public IpcRsp { -DECLARE_IPC_MODEL(IpcGetTrustdeviceRsp); +class IpcGetTrustDeviceRsp : public IpcRsp { + DECLARE_IPC_MODEL(IpcGetTrustDeviceRsp); + public: std::vector GetDeviceVec() const { return deviceVec_; } - void SetDeviceVec(std::vector& deviceVec) + void SetDeviceVec(std::vector &deviceVec) { deviceVec_ = deviceVec; } + private: std::vector deviceVec_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_GET_TRUSTDEVICE_RSP_H +#endif // OHOS_DM_IPC_GET_TRUST_DEVICE_RSP_H diff --git a/common/include/ipc/model/ipc_notify_auth_result_req.h b/common/include/ipc/model/ipc_notify_auth_result_req.h index afee8f664..7c9034b16 100644 --- a/common/include/ipc/model/ipc_notify_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_auth_result_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_AUTH_RESULT_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_AUTH_RESULT_REQ_H +#ifndef OHOS_DM_IPC_NOTIFY_AUTH_RESULT_REQ_H +#define OHOS_DM_IPC_NOTIFY_AUTH_RESULT_REQ_H #include @@ -23,26 +23,27 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyAuthResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyAuthResultReq); + DECLARE_IPC_MODEL(IpcNotifyAuthResultReq); + public: std::string GetDeviceId() const { return deviceId_; } - void SetDeviceId(std::string& deviceId) + void SetDeviceId(const std::string &deviceId) { deviceId_ = deviceId; } - int32_t GetPinToken() const + std::string GetPinToken() const { - return pinToken_; + return token_; } - void SetPinToken(int32_t pinToken) + void SetToken(const std::string &token) { - pinToken_ = pinToken; + token_ = token; } int32_t GetStatus() const @@ -64,12 +65,13 @@ public: { reason_ = reason; } + private: std::string deviceId_; - int32_t pinToken_ {0}; - int32_t status_ {0}; - int32_t reason_ {0}; + std::string token_; + int32_t status_{0}; + int32_t reason_{0}; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_AUTH_RESULT_REQ_H +#endif // OHOS_DM_IPC_NOTIFY_AUTH_RESULT_REQ_H diff --git a/common/include/ipc/model/ipc_notify_check_auth_result_req.h b/common/include/ipc/model/ipc_notify_check_auth_result_req.h deleted file mode 100644 index 0e153d560..000000000 --- a/common/include/ipc/model/ipc_notify_check_auth_result_req.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H - -#include - -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcNotifyCheckAuthResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyCheckAuthResultReq); -public: - std::string GetDeviceId() const - { - return deviceId_; - } - - void SetDeviceId(std::string& deviceId) - { - deviceId_ = deviceId; - } - - int32_t GetResult() const - { - return result_; - } - - void SetResult(int32_t result) - { - result_ = result; - } - - int32_t GetFlag() const - { - return flag_; - } - - void SetFlag(int32_t flag) - { - flag_ = flag; - } -private: - std::string deviceId_; - int32_t result_ {0}; - int32_t flag_ {0}; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H diff --git a/common/include/ipc/model/ipc_notify_device_found_req.h b/common/include/ipc/model/ipc_notify_device_found_req.h index 6c0947660..d52c13f93 100644 --- a/common/include/ipc/model/ipc_notify_device_found_req.h +++ b/common/include/ipc/model/ipc_notify_device_found_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,24 +13,24 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_FOUND_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_FOUND_REQ_H +#ifndef OHOS_DM_IPC_NOTIFY_DEVICE_FOUND_REQ_H +#define OHOS_DM_IPC_NOTIFY_DEVICE_FOUND_REQ_H #include "dm_device_info.h" - #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { class IpcNotifyDeviceFoundReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyDeviceFoundReq); + DECLARE_IPC_MODEL(IpcNotifyDeviceFoundReq); + public: - const DmDeviceInfo& GetDeviceInfo() const + const DmDeviceInfo &GetDeviceInfo() const { return dmDeviceInfo_; } - void SetDeviceInfo(DmDeviceInfo& dmDeviceInfo) + void SetDeviceInfo(const DmDeviceInfo &dmDeviceInfo) { dmDeviceInfo_ = dmDeviceInfo; } @@ -44,10 +44,11 @@ public: { subscribeId_ = subscribeId; } + private: - uint16_t subscribeId_ {0}; + uint16_t subscribeId_{0}; DmDeviceInfo dmDeviceInfo_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_FOUND_REQ_H +#endif // OHOS_DM_IPC_NOTIFY_DEVICE_FOUND_REQ_H diff --git a/common/include/ipc/model/ipc_notify_device_state_req.h b/common/include/ipc/model/ipc_notify_device_state_req.h index 0f20867c5..19cfb68da 100644 --- a/common/include/ipc/model/ipc_notify_device_state_req.h +++ b/common/include/ipc/model/ipc_notify_device_state_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,17 +13,17 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_STATE_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_STATE_REQ_H +#ifndef OHOS_DM_IPC_NOTIFY_DEVICE_STATE_REQ_H +#define OHOS_DM_IPC_NOTIFY_DEVICE_STATE_REQ_H #include "dm_device_info.h" - #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { class IpcNotifyDeviceStateReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyDeviceStateReq); + DECLARE_IPC_MODEL(IpcNotifyDeviceStateReq); + public: int32_t GetDeviceState() const { @@ -35,19 +35,20 @@ public: deviceState_ = deviceState; } - const DmDeviceInfo& GetDeviceInfo() const + const DmDeviceInfo &GetDeviceInfo() const { return dmDeviceInfo_; } - void SetDeviceInfo(DmDeviceInfo& dmDeviceInfo) + void SetDeviceInfo(const DmDeviceInfo &dmDeviceInfo) { dmDeviceInfo_ = dmDeviceInfo; } + private: - int32_t deviceState_ {0}; + int32_t deviceState_{0}; DmDeviceInfo dmDeviceInfo_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_STATE_REQ_H +#endif // OHOS_DM_IPC_NOTIFY_DEVICE_STATE_REQ_H diff --git a/common/include/ipc/model/ipc_notify_discover_result_req.h b/common/include/ipc/model/ipc_notify_discover_result_req.h index ea6776ed0..8c9588399 100644 --- a/common/include/ipc/model/ipc_notify_discover_result_req.h +++ b/common/include/ipc/model/ipc_notify_discover_result_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,17 +13,16 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DISCOVER_RESULT_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_DISCOVER_RESULT_REQ_H - -#include +#ifndef OHOS_DM_IPC_NOTIFY_DISCOVER_RESULT_REQ_H +#define OHOS_DM_IPC_NOTIFY_DISCOVER_RESULT_REQ_H #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { class IpcNotifyDiscoverResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyDiscoverResultReq); + DECLARE_IPC_MODEL(IpcNotifyDiscoverResultReq); + public: uint16_t GetSubscribeId() const { @@ -44,10 +43,11 @@ public: { result_ = result; } + private: - uint16_t subscribeId_ {0}; - int32_t result_ {0}; + uint16_t subscribeId_{0}; + int32_t result_{0}; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_DISCOVER_RESULT_REQ_H +#endif // OHOS_DM_IPC_NOTIFY_DISCOVER_RESULT_REQ_H diff --git a/common/include/ipc/model/ipc_notify_dmfa_result_req.h b/common/include/ipc/model/ipc_notify_dmfa_result_req.h index e6012aa7a..006c0966e 100644 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,27 +16,27 @@ #ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DMFA_RESULT_REQ_H #define OHOS_DEVICE_MANAGER_IPC_NOTIFY_DMFA_RESULT_REQ_H -#include - #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { class IpcNotifyDMFAResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyDMFAResultReq); + DECLARE_IPC_MODEL(IpcNotifyDMFAResultReq); + public: std::string GetJsonParam() const { return JsonParam_; } - void SetJsonParam(std::string& JsonParam) + void SetJsonParam(const std::string &JsonParam) { JsonParam_ = JsonParam; } + private: std::string JsonParam_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_AUTH_RESULT_REQ_H +#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_DMFA_RESULT_REQ_H diff --git a/common/include/ipc/model/ipc_register_listener_req.h b/common/include/ipc/model/ipc_register_listener_req.h index 67690a5b8..539b0e58b 100644 --- a/common/include/ipc/model/ipc_register_listener_req.h +++ b/common/include/ipc/model/ipc_register_listener_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_REGISTER_LISTENER_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_REGISTER_LISTENER_REQ_H +#ifndef OHOS_DM_IPC_REGISTER_LISTENER_REQ_H +#define OHOS_DM_IPC_REGISTER_LISTENER_REQ_H #include "ipc_req.h" @@ -27,7 +27,8 @@ namespace OHOS { namespace DistributedHardware { class IpcRegisterListenerReq : public IpcReq { -DECLARE_IPC_MODEL(IpcRegisterListenerReq); + DECLARE_IPC_MODEL(IpcRegisterListenerReq); + public: #ifdef LITE_DEVICE SvcIdentity GetSvcIdentity() const @@ -59,4 +60,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_REGISTER_LISTENER_REQ_H +#endif // OHOS_DM_IPC_REGISTER_LISTENER_REQ_H diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index ac6e99d80..7ecadbf3c 100644 --- a/common/include/ipc/model/ipc_req.h +++ b/common/include/ipc/model/ipc_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_REQ_H +#ifndef OHOS_DM_IPC_REQ_H +#define OHOS_DM_IPC_REQ_H #include @@ -23,20 +23,22 @@ namespace OHOS { namespace DistributedHardware { class IpcReq { -DECLARE_IPC_MODEL(IpcReq); + DECLARE_IPC_MODEL(IpcReq); + public: - const std::string& GetPkgName() const + const std::string &GetPkgName() const { return pkgName_; } - void SetPkgName(std::string &pkgName) + void SetPkgName(const std::string &pkgName) { pkgName_ = pkgName; } + private: std::string pkgName_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_REQ_H +#endif // OHOS_DM_IPC_REQ_H diff --git a/common/include/ipc/model/ipc_rsp.h b/common/include/ipc/model/ipc_rsp.h index 14394280b..251d6097b 100644 --- a/common/include/ipc/model/ipc_rsp.h +++ b/common/include/ipc/model/ipc_rsp.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_RSP_H -#define OHOS_DEVICE_MANAGER_IPC_RSP_H +#ifndef OHOS_DM_IPC_RSP_H +#define OHOS_DM_IPC_RSP_H #include @@ -23,7 +23,8 @@ namespace OHOS { namespace DistributedHardware { class IpcRsp { -DECLARE_IPC_MODEL(IpcRsp); + DECLARE_IPC_MODEL(IpcRsp); + public: int32_t GetErrCode() const { @@ -34,9 +35,10 @@ public: { errCode_ = errCode; } + private: int32_t errCode_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_RSP_H +#endif // OHOS_DM_IPC_RSP_H diff --git a/common/include/ipc/model/ipc_set_useroperation_req.h b/common/include/ipc/model/ipc_set_useroperation_req.h index e2f51db3f..9b6e85fe7 100644 --- a/common/include/ipc/model/ipc_set_useroperation_req.h +++ b/common/include/ipc/model/ipc_set_useroperation_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,13 +15,15 @@ #ifndef OHOS_DEVICE_MANAGER_IPC_GET_USER_OPERATION_REQ_H #define OHOS_DEVICE_MANAGER_IPC_GET_USER_OPERATION_REQ_H -#include "ipc_req.h" + #include "dm_device_info.h" +#include "ipc_req.h" namespace OHOS { namespace DistributedHardware { class IpcGetOperationReq : public IpcReq { -DECLARE_IPC_MODEL(IpcGetOperationReq); + DECLARE_IPC_MODEL(IpcGetOperationReq); + public: int32_t GetOperation() const { @@ -34,7 +36,7 @@ public: } private: - int32_t action_ {0}; + int32_t action_{0}; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h index 341641e61..e145ac89d 100644 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ b/common/include/ipc/model/ipc_start_discovery_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,30 +13,42 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_START_DISCOVERY_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_START_DISCOVERY_REQ_H - -#include "ipc_req.h" +#ifndef OHOS_DM_IPC_START_DISCOVERY_REQ_H +#define OHOS_DM_IPC_START_DISCOVERY_REQ_H #include "dm_subscribe_info.h" +#include "ipc_req.h" namespace OHOS { namespace DistributedHardware { class IpcStartDiscoveryReq : public IpcReq { -DECLARE_IPC_MODEL(IpcStartDiscoveryReq); + DECLARE_IPC_MODEL(IpcStartDiscoveryReq); + public: - const DmSubscribeInfo& GetSubscribeInfo() const + const DmSubscribeInfo &GetSubscribeInfo() const { return subscribeInfo_; } - void SetSubscribeInfo(DmSubscribeInfo &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_IPC_START_DISCOVERY_REQ_H +#endif // OHOS_DM_IPC_START_DISCOVERY_REQ_H diff --git a/common/include/ipc/model/ipc_stop_discovery_req.h b/common/include/ipc/model/ipc_stop_discovery_req.h index bf1de6b17..10c547e88 100644 --- a/common/include/ipc/model/ipc_stop_discovery_req.h +++ b/common/include/ipc/model/ipc_stop_discovery_req.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_STOP_DISCOVERY_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_STOP_DISCOVERY_REQ_H +#ifndef OHOS_DM_IPC_STOP_DISCOVERY_REQ_H +#define OHOS_DM_IPC_STOP_DISCOVERY_REQ_H #include @@ -23,7 +23,8 @@ namespace OHOS { namespace DistributedHardware { class IpcStopDiscoveryReq : public IpcReq { -DECLARE_IPC_MODEL(IpcStopDiscoveryReq); + DECLARE_IPC_MODEL(IpcStopDiscoveryReq); + public: uint16_t GetSubscribeId() const { @@ -34,9 +35,10 @@ public: { subscribeId_ = subscribeId; } + private: - uint16_t subscribeId_ {0}; + uint16_t subscribeId_{0}; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_STOP_DISCOVERY_REQ_H +#endif // OHOS_DM_IPC_STOP_DISCOVERY_REQ_H diff --git a/common/include/single_instance.h b/common/include/single_instance.h index a76aa07e2..0bfa9e404 100644 --- a/common/include/single_instance.h +++ b/common/include/single_instance.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,34 +13,34 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_SINGLE_INSTANCE_H -#define OHOS_DEVICE_MANAGER_SINGLE_INSTANCE_H +#ifndef OHOS_DM_SINGLE_INSTANCE_H +#define OHOS_DM_SINGLE_INSTANCE_H namespace OHOS { namespace DistributedHardware { #define DECLARE_SINGLE_INSTANCE_BASE(className) \ -public: \ - static className & GetInstance(); \ +public: \ + static className &GetInstance(); \ + \ private: \ - className(const className&) = delete; \ - className& operator= (const className&) = delete; \ - className(className&&) = delete; \ - className& operator= (className&&) = delete; \ - + className(const className &) = delete; \ + className &operator=(const className &) = delete; \ + className(className &&) = delete; \ + className &operator=(className &&) = delete; #define DECLARE_SINGLE_INSTANCE(className) \ DECLARE_SINGLE_INSTANCE_BASE(className) \ private: \ className() = default; \ - ~className() = default; \ + ~className() = default; -#define IMPLEMENT_SINGLE_INSTANCE(className) \ -className & className::GetInstance() \ -{ \ - static auto instance = new className(); \ - return *instance; \ -} +#define IMPLEMENT_SINGLE_INSTANCE(className) \ + className &className::GetInstance() \ + { \ + static auto instance = new className(); \ + return *instance; \ + } }; // namespace DistributedHardware }; // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_SINGLE_INSTANCE_H \ No newline at end of file +#endif // OHOS_DM_SINGLE_INSTANCE_H \ No newline at end of file diff --git a/devicemanager.gni b/devicemanager.gni index e8576d35d..7487a8b32 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -11,14 +11,18 @@ # See the License for the specific language governing permissions and # limitations under the License. +#------------------------device manager------------------------------# devicemanager_path = "//foundation/distributedhardware/devicemanager" common_path = "${devicemanager_path}/common" - utils_path = "${devicemanager_path}/utils" +services_path = "${devicemanager_path}/services/devicemanagerservice" +innerkits_path = "${devicemanager_path}/interfaces/inner_kits" +ext_path = "${devicemanager_path}/ext" -services_path = "${devicemanager_path}/services" +#--------------------------softbus----------------------------------# -innerkits_path = "${devicemanager_path}/interfaces/inner_kits" +#---------------------------hichan----------------------------------# +#----------------------compilation options--------------------------# dm_ldflags = [ "-lpthread" ] diff --git a/display/@ohos.distributedHardware.deviceManager.d.ts b/display/@ohos.distributedHardware.deviceManager.d.ts deleted file mode 100644 index 604936a6e..000000000 --- a/display/@ohos.distributedHardware.deviceManager.d.ts +++ /dev/null @@ -1,476 +0,0 @@ -/* - * 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. - */ - -import { AsyncCallback, Callback } from './basic'; - -declare namespace deviceManager { - /** - * DeviceInfo - */ - interface DeviceInfo { - /** - * DeviceId ID. - */ - deviceId: string; - - /** - * Device name of the device. - */ - deviceName: string; - - /** - * Device type of the device. - */ - deviceType: DeviceType; - } - - /** - * Device Type definitions - */ - enum DeviceType { - /** - * Indicates an unknown device type. - */ - UNKNOWN_TYPE = 0, - - /** - * Indicates a speaker. - */ - SPEAKER = 0x0A, - - /** - * Indicates a smartphone. - */ - PHONE = 0x0E, - - /** - * Indicates a tablet. - */ - TABLET = 0x11, - - /** - * Indicates a smart watch. - */ - WEARABLE = 0x6D, - - /** - * Indicates a car. - */ - CAR = 0x83, - - /** - * Indicates a smart TV. - */ - TV = 0x9C - } - - /** - * Device state change event definition - */ - enum DeviceStateChangeAction { - /** - * device online action - */ - ONLINE = 0, - - /** - * device ready action, the device information synchronization was completed. - */ - READY = 1, - - /** - * device offline action - */ - OFFLINE = 2, - - /** - * device change action - */ - CHANGE = 3 - } - - /** - * Service subscribe info for device discover - * - * @systemapi this method can be used only by system applications. - */ - interface SubscribeInfo { - /** - * Service subscribe ID, the value is in scope [0, 65535], should be unique for each discover process - */ - subscribeId: number; - - /** - * Discovery mode for service subscription. - */ - mode: DiscoverMode; - - /** - * Service subscription medium. - */ - medium: ExchangeMedium; - - /** - * Service subscription frequency. - */ - freq: ExchangeFreq; - - /** - * only find the device with the same account. - */ - isSameAccount: boolean; - - /** - * find the sleeping devices. - */ - isWakeRemote: boolean; - - /** - * Subscribe capability. - */ - capability: SubscribeCap; - } - - /** - * device discover mode - * - * @systemapi this method can be used only by system applications. - */ - enum DiscoverMode { - /** - * Passive - */ - DISCOVER_MODE_PASSIVE = 0x55, - - /** - * Proactive - */ - DISCOVER_MODE_ACTIVE = 0xAA - } - - /** - * device discover medium - * - * @systemapi this method can be used only by system applications. - */ - enum ExchangeMedium { - /** - * Automatic medium selection - */ - AUTO = 0, - - /** - * Bluetooth - */ - BLE = 1, - - /** - * Wi-Fi - */ - COAP = 2, - - /** - * USB - */ - USB = 3 - } - - /** - * device discover freq - * - * @systemapi this method can be used only by system applications. - */ - enum ExchangeFreq { - /** - * Low - */ - LOW = 0, - - /** - * Medium - */ - MID = 1, - - /** - * High - */ - HIGH = 2, - - /** - * Super-high - */ - SUPER_HIGH = 3 - } - - /** - * device discover capability - * - * @systemapi this method can be used only by system applications. - */ - enum SubscribeCap { - /** - * ddmpCapability - */ - SUBSCRIBE_CAPABILITY_DDMP = 0 - } - - /** - * Device Authentication param - * - * @systemapi this method can be used only by system applications - */ - interface AuthParam { - /** - * Authentication type, 1 for pin code. - */ - authType: number; - - /** - * App application Icon. - */ - appIcon?: Uint8Array; - - /** - * App application thumbnail. - */ - appThumbnail?: Uint8Array; - - /** - * Authentication extra infos. - */ - extraInfo: {[key:string] : any}; - - } - - /** - * Device auth info. - * - * @systemapi this method can be used only by system applications - */ - interface AuthInfo { - /** - * Authentication type, 1 for pin code. - */ - authType: number; - - /** - * the token used for this authentication. - */ - token: number; - - /** - * Authentication extra infos. - */ - extraInfo: {[key:string] : any}; - } - - /** - * User Operation Action from devicemanager Fa. - * - * @systemapi this method can be used only by system applications. - */ - enum UserOperationAction { - /** - * allow authentication - */ - ACTION_ALLOW_AUTH = 0, - - /** - * cancel authentication - */ - ACTION_CANCEL_AUTH = 1, - - /** - * user operation timeout for authentication confirm - */ - ACTION_AUTH_CONFIRM_TIMEOUT = 2, - - /** - * cancel pincode display - */ - ACTION_CANCEL_PINCODE_DISPLAY = 3, - - /** - * cancel pincode input - */ - ACTION_CANCEL_PINCODE_INPUT = 4, - } - - /** - * Creates a {@code DeviceManager} instance. - * - *

To manage devices, you must first call this method to obtain a {@code DeviceManager} instance and then - * use this instance to call other device management methods. - * - * @param bundleName Indicates the bundle name of the application. - * @param callback Indicates the callback to be invoked upon {@code DeviceManager} instance creation. - */ - function createDeviceManager(bundleName: string, callback: AsyncCallback): void; - - /** - * Provides methods for managing devices. - */ - interface DeviceManager { - /** - * Releases the {@code DeviceManager} instance after the methods for device management are no longer used. - */ - release(): void; - - /** - * Obtains a list of trusted devices. - * - * @param options Indicates the extra parameters to be passed to this method for device filtering or sorting. - * This parameter can be null. For details about available values, see {@link #TARGET_PACKAGE_NAME} and - * {@link #SORT_TYPE}. - * @return Returns a list of trusted devices. - */ - getTrustedDeviceListSync(): Array; - - /** - * Start to discover device. - * - * @param bundleName Indicates the bundle name of the application. - * @param subscribeInfo subscribe info to discovery device - * @systemapi this method can be used only by system applications. - */ - startDeviceDiscovery(subscribeInfo: SubscribeInfo): void; - - /** - * Stop to discover device. - * - * @param bundleName Indicates the bundle name of the application. - * @param subscribeId Service subscribe ID - * @systemapi this method can be used only by system applications. - */ - stopDeviceDiscovery(subscribeId: number): void; - - /** - * Authenticate the specified device. - * - * @param deviceInfo deviceInfo of device to authenticate - * @param authparam authparam of device to authenticate - * @param callback Indicates the callback to be invoked upon authenticateDevice - * @systemapi this method can be used only by system applications. - */ - authenticateDevice(deviceInfo: DeviceInfo, authparam: AuthParam, callback: AsyncCallback<{deviceId: string, pinTone ?: number}>): void; - - /** - * verify auth info, such as pin code. - * - * @param authInfo device auth info o verify - * @param callback Indicates the callback to be invoked upon verifyAuthInfo - * @systemapi this method can be used only by system applications. - */ - verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void; - - /** - * Get authenticate parameters for peer device, this interface can only used by devicemanager Fa. - * - * @param authParam authparam for peer device - * @systemapi this method can be used only by system applications. - */ - getAuthenticationParam(): AuthParam; - - /** - * Set user Operation from devicemanager Fa, this interface can only used by devicemanager Fa. - * - * @param operateAction User Operation Actions. - * @systemapi this method can be used only by system applications. - */ - setUserOperation(operateAction: UserOperationAction): void; - - /** - * Register a callback from deviceManager service so that the devicemanager Fa can be notified when some events happen. - * this interface can only used by devicemanager Fa. - * - * @param callback for devicemanager Fa to register. - * @systemapi this method can be used only by system applications. - */ - on(type: 'dmFaCallback', callback: Callback<{ param: string}>): void; - - /** - * UnRegister dmFaCallback, this interface can only used by devicemanager Fa. - * - * @param callback for devicemanager Fa to register. - * @systemapi this method can be used only by system applications. - */ - off(type: 'dmFaCallback', callback?: Callback<{ param: string}>): void; - - /** - * Register a device state callback so that the application can be notified upon device state changes based on - * the application bundle name. - * - * @param bundleName Indicates the bundle name of the application. - * @param callback Indicates the device state callback to register. - */ - on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void; - - /** - * UnRegister device state callback based on the application bundle name. - * - * @param bundleName Indicates the bundle name of the application. - * @param callback Indicates the device state callback to register. - */ - off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void; - - /** - * Register a device found callback so that the application can be notified when the device was found - * - * @param callback Indicates the device found callback to register. - * @systemapi this method can be used only by system applications. - */ - on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: DeviceInfo }>): void; - - /** - * UnRegister a device found callback so that the application can be notified when the device was found - * - * @param callback Indicates the device found callback to register. - * @systemapi this method can be used only by system applications. - */ - off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: DeviceInfo }>): void; - - /** - * Register a device found result callback so that the application can be notified when the device discover was failed - * - * @param callback Indicates the device found result callback to register. - * @systemapi this method can be used only by system applications. - */ - on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: number }>): void; - - /** - * UnRegister a device found result callback so that the application can be notified when the device discover was failed - * - * @param callback Indicates the device found result callback to register. - * @systemapi this method can be used only by system applications. - */ - off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: number }>): void; - - /** - * Register a serviceError callback so that the application can be notified when devicemanager service died - * - * @param callback Indicates the service error callback to register. - */ - on(type: 'serviceDie', callback: () => void): void; - - /** - * UnRegister a serviceError callback so that the application can be notified when devicemanager service died - * - * @param callback Indicates the service error callback to register. - */ - off(type: 'serviceDie', callback?: () => void): void; - } -} - -export default deviceManager; diff --git a/display/build.gradle b/display/build.gradle deleted file mode 100644 index 12771702e..000000000 --- a/display/build.gradle +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - */ - - // Top-level build file where you can add configuration options common to all sub-projects/modules. -apply plugin: 'com.huawei.ohos.app' - -ohos { - compileSdkVersion 6 - defaultConfig { - compatibleSdkVersion 6 - } -} - -buildscript { - repositories { - maven { - url 'http://repo.ark.tools.huawei.com/artifactory/maven-public/' - } - maven { - url 'https://mirrors.huaweicloud.com/repository/maven/' - } - maven { - url 'https://developer.huawei.com/repo/' - } - jcenter() - } - dependencies { - classpath 'com.huawei.ohos:hap:2.4.4.3-RC' - } -} - -allprojects { - repositories { - maven { - url 'http://repo.ark.tools.huawei.com/artifactory/maven-public/' - } - maven { - url 'https://mirrors.huaweicloud.com/repository/maven/' - } - maven { - url 'https://developer.huawei.com/repo/' - } - jcenter() - } -} \ No newline at end of file diff --git a/display/entry/build.gradle b/display/entry/build.gradle deleted file mode 100644 index 498918b6f..000000000 --- a/display/entry/build.gradle +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - */ - - apply plugin: 'com.huawei.ohos.hap' -apply plugin: 'com.huawei.ohos.decctest' -//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 -ohos { - compileSdkVersion 6 - defaultConfig { - compatibleSdkVersion 6 - } - buildTypes { - release { - proguardOpt { - proguardEnabled false - rulesFiles 'proguard-rules.pro' - } - } - } - -} - -dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) - testImplementation 'junit:junit:4.13' - ohosTestImplementation 'com.huawei.ohos.testkit:runner:1.0.0.200' -} -decc { - supportType = ['html', 'xml'] -} diff --git a/display/entry/src/main/config.json b/display/entry/src/main/config.json deleted file mode 100644 index faf4f0465..000000000 --- a/display/entry/src/main/config.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "app": { - "bundleName": "com.ohos.devicemanagerui", - "vendor": "ohos", - "version": { - "code": 1000000, - "name": "1.0.0" - } - }, - "deviceConfig": {}, - "module": { - "package": "com.ohos.devicemanagerui", - "name": ".MyApplication", - "mainAbility": "com.ohos.devicemanagerui.MainAbility", - "deviceType": [ - "phone", - "tablet", - "tv", - "wearable" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry", - "installationFree": false - }, - "abilities": [ - { - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "visible": true, - "name": "com.ohos.devicemanagerui.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "$string:entry_MainAbility", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": true - } - } - ] - } -} \ No newline at end of file diff --git a/display/entry/src/main/js/default/app.js b/display/entry/src/main/js/default/app.js deleted file mode 100644 index 8e47afff1..000000000 --- a/display/entry/src/main/js/default/app.js +++ /dev/null @@ -1,23 +0,0 @@ -/* - * 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. - */ - -export default { - onCreate() { - console.info('AceApplication onCreate'); - }, - onDestroy() { - console.info('AceApplication onDestroy'); - } -}; diff --git a/display/entry/src/main/js/default/i18n/en-US.json b/display/entry/src/main/js/default/i18n/en-US.json deleted file mode 100644 index 9e5209101..000000000 --- a/display/entry/src/main/js/default/i18n/en-US.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "strings": { - } -} \ No newline at end of file diff --git a/display/entry/src/main/js/default/i18n/zh-CN.json b/display/entry/src/main/js/default/i18n/zh-CN.json deleted file mode 100644 index 9e5209101..000000000 --- a/display/entry/src/main/js/default/i18n/zh-CN.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "strings": { - } -} \ No newline at end of file diff --git a/display/entry/src/main/js/default/pages/index/index.css b/display/entry/src/main/js/default/pages/index/index.css deleted file mode 100644 index 132302197..000000000 --- a/display/entry/src/main/js/default/pages/index/index.css +++ /dev/null @@ -1,169 +0,0 @@ -/* - * 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. - */ - -.container { - flex-direction: column; - justify-content: center; - align-items: center; - opacity: 0.8; - background-color: azure; -} - -.container > div { - flex-direction: column; - justify-content: center; - align-items: center; -} - -.main-pin > .pin-numb { - flex-direction: row; - justify-content: space-around; - align-items: center; - padding: 15px 30px 10px 30px; -} -.main-pin > .pin-numb > .pin-numb-item { - font-size: 30px; - line-height: 30px; - height: 40px; - padding-bottom: 5px; - font-weight: 800; - width: 30px; - border-bottom-width: 2px; - border-bottom-color: darkgray; - text-align: center; -} - -.main-pin > .input { - flex-direction: row; - justify-content: space-around; - align-items: center; - padding: 5px 30px 5px 30px; -} - -.main-pin > .input > .numb { - text-color: black; - padding: 5px; - flex-shrink: 0; - flex-basis: 60px; - background-color: white; - border: 1px; -} - -.join-auth { - padding-top: 30px; -} -.join-auth-image > image { - height: 170px; -} -.join-authorize { - padding-top: 10px; -} -.join-pin { - padding: 10px 0; -} -.join-pin > .pin { - font-size: 50px; - line-height: 90px; - font-weight: bolder; - color: #000000; -} - -.join-auth > .title, -.join-auth-image > .title, -.join-authorize > .title { - font-size: 18px; - line-height: 80px; - font-weight: 800; - color: #000000; -} -.join-auth > .title { - line-height: 40px; -} -.join-auth-image > .title { - line-height: 26px; -} -.join-pin > .title { - font-size: 28px; - line-height: 60px; - font-weight: 800; -} -.main-pin > .title { - font-size: 30px; - line-height: 40px; - font-weight: bolder; -} - -.join-auth > .title-tip, -.join-auth-image > .title-tip, -.main-pin > .title-tip, -.join-authorize > .title-tip { - font-size: 15px; - line-height: 40px; - color: #5A5A5A; -} -.join-auth > .title-tip { - line-height: 40px; -} -.join-auth-image > .title-tip { - line-height: 24px; -} -.join-pin > .title-tip { - font-size: 20px; - line-height: 50px; - font-weight: 600; -} -.main-pin > .title-tip { - font-size: 18px; - line-height: 30px; - font-weight: 800; -} - -.join-auth > .dialog-foot, -.join-auth-image > .dialog-foot, -.join-authorize > .dialog-foot { - flex-direction: row; - justify-content: center; - align-items: center; - justify-content: space-around; - margin: 80px 20px 30px 20px; -} -.join-authorize > .dialog-foot { - margin: 100px 20px 30px 20px; -} -.join-auth-image > .dialog-foot { - margin: 10px 20px 10px 20px; -} -.join-pin > .dialog-foot { - margin: 10px 20px 10px 20px; -} - -.join-auth .button-cancel, -.join-auth-image .button-cancel, -.join-authorize .button-cancel { - width: 160px; - height: 36px; -} -.join-pin .button-cancel { - width: 100%; - font-size: 26px; - height: 50px; -} - -.join-auth .button-ok, -.join-auth-image .button-ok, -.join-authorize .button-ok { - width: 150px; - height: 36px; -} \ No newline at end of file diff --git a/display/entry/src/main/js/default/pages/index/index.hml b/display/entry/src/main/js/default/pages/index/index.hml deleted file mode 100644 index 7f388b212..000000000 --- a/display/entry/src/main/js/default/pages/index/index.hml +++ /dev/null @@ -1,98 +0,0 @@ - - -

-
- PIN码连接 - 请输入平板上显示的PIN码 -
- {{pin[0]}} - {{pin[1]}} - {{pin[2]}} - {{pin[3]}} - {{pin[4]}} - {{pin[5]}} -
-
- - - - -
-
- - - - -
-
- - - - -
-
-
- 是否允许{{statusInfo.deviceName}}连接本机 - 用于资源访问 -
- - -
-
-
- {{ statusInfo.appName }} - 是否允许打开apply auth? - 来自{{statusInfo.deviceName}} -
- - -
-
-
- - {{ statusInfo.appName }} - 是否允许打开apply auth? - 来自{{statusInfo.deviceName}} -
- - -
-
-
- PIN码连接 - 请在主控端输入连接码进行验证 - {{statusInfo.pinCode.split('').join(' ')}} -
- -
-
-
diff --git a/display/entry/src/main/js/default/pages/index/index.js b/display/entry/src/main/js/default/pages/index/index.js deleted file mode 100644 index 0304a8d52..000000000 --- a/display/entry/src/main/js/default/pages/index/index.js +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import router from '@system.router'; -import deviceManager from '@ohos.distributedHardware.deviceManager'; -function uint8ArrayToBase64(array) { - array = new Uint8Array(array); - let table = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'], - base64Str = '', length = array.byteLength, i = 0; - for(i = 0; length - i >= 3; i += 3) { - let num1 = array[i], num2 = array[i + 1], num3 = array[i + 2]; - base64Str += table[num1 >>> 2] + table[((num1 & 0b11) << 4) | (num2 >>> 4)] + table[((num2 & 0b1111) << 2) | (num3 >>> 6)] + table[num3 & 0b111111]; - } - const lastByte = length - i; - if (lastByte === 1) { - const lastNum1 = array[i]; - base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4)] + '=='; - } else if (lastByte === 2) { - const lastNum1 = array[i]; - const lastNum2 = array[i + 1]; - base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4) | (lastNum2 >>> 4)] + table[(lastNum2 & 0b1111) << 2] + '='; - } - return 'data:image/png;base64,' + base64Str; -} -const TAG = "DeviceManagerUI:"; -let dmClass; - -export default { - data: { - // showType: ['main-pin','join-authorize','join-auth','join-auth-image','join-pin'] - status: "", - // showInfo - statusInfo: { - deviceName: "AppName", - appName: 'PackageName', - appIcon: null, - pinCode: '', - pinToken: '' - }, - // join: join-authorize timing - timeRemaining: 0, - // input pinCode - pin: ['','','','','',''], - // input pinCode next number - pinNumb: 0 - }, - - log(m) { - console.info(TAG + m); - }, - - onDestroy() { - if (dmClass != null) { - dmClass.off('dmFaCallback'); - dmClass.off('deviceStateChange'); - dmClass.off('serviceDie'); - dmClass.release(); - dmClass = null - } - }, - - onShow() { - if (dmClass) { - this.initStatue() - } else { - this.log('createDeviceManager') - deviceManager.createDeviceManager('com.ohos.devicemanagerui', (err, dm) => { - this.log("createDeviceManager err:" + JSON.stringify(err) + ' --success:' + JSON.stringify(dm)) - if (err) return; - dmClass = dm; - dmClass.on('dmFaCallback', () => router.back()) - this.initStatue() - }); - } - }, - - onHide() { - this.timeRemaining = 0 - }, - - /** - * Get authentication param - */ - initStatue() { - this.log('initStatue') - const data = dmClass.getAuthenticationParam() - this.log('getAuthenticationParam:' + JSON.stringify(data)) - // Authentication type, 1 for pin code. - if (data && data.authType == 1) { - this.statusInfo = { - deviceName: data.extraInfo.PackageName, - appName: data.extraInfo.appName, - appIcon: uint8ArrayToBase64(data.appIcon), - pinCode: data.extraInfo.pinCode + '', - pinToken: data.extraInfo.pinToken - } - // direction: 1(main)/0(join) - if (data.extraInfo.direction == 1) { - this.mainPin() - } else if (data.appIcon) { - this.joinAuthImage() - } else if (data.extraInfo.business == 0) { - // business: 0(FA流转)/1(资源访问) - this.joinAuth() - } else { - this.joinAuthorize() - } - } - }, - - /** - * Set user Operation from devicemanager Fa, this interface can only used by devicemanager Fa. - * - * @param operateAction User Operation Actions. - * ACTION_ALLOW_AUTH = 0, allow authentication - * ACTION_CANCEL_AUTH = 1, cancel authentication - * ACTION_AUTH_CONFIRM_TIMEOUT = 2, user operation timeout for authentication confirm - * ACTION_CANCEL_PINCODE_DISPLAY = 3, cancel pinCode display - * ACTION_CANCEL_PINCODE_INPUT = 4, cancel pinCode input - */ - setUserOperation(operation) { - this.log('setUserOperation: ' + operation) - if (dmClass != null) { - var data = dmClass.setUserOperation(operation); - this.log('setUserOperation result: ' + JSON.stringify(data)) - } else { - this.log('deviceManagerObject not exit') - } - }, - - /** - * verify auth info, such as pin code. - * @param pinCode - * @return - */ - verifyAuthInfo(pinCode) { - this.log('verifyAuthInfo: ' + pinCode) - if (dmClass != null) { - dmClass.verifyAuthInfo({ - "authType": 1, - "token": this.statusInfo.pinToken, - "extraInfo": { - "pinCode": +pinCode - } - }, (err, data) => { - if (err) { - this.log("verifyAuthInfo err:" + JSON.stringify(err)) - } - this.log("verifyAuthInfo result:" + JSON.stringify(data)) - router.back() - }); - } else { - this.log('deviceManagerObject not exit') - } - }, - - /** - * Input pinCode at the main control terminal - */ - mainPin() { - this.status = 'main-pin' - }, - - /** - * Enter a number with the keyboard - * @param s - * @return - */ - mainInputPin(s) { - this.log('mainInputPin input: ' + s + '-' + this.pin) - if (this.pinNumb == 6) return - if (this.pinNumb < 6) { - this.pin[this.pinNumb] = s - ++this.pinNumb - this.pin = [...this.pin] - } - this.log('mainInputPin pin: ' + this.pin + '-' + this.pin.join('')) - if (this.pinNumb == 6) { - // input end - this.log('mainInputPin end: ' + this.pin + '-' + this.pin.join('')) - this.verifyAuthInfo(this.pin.join('')) - } - }, - - /** - * Keyboard delete number - */ - mainInputPinBack() { - if (this.pinNumb > 0) { - --this.pinNumb - this.pin[this.pinNumb] = '' - this.pin = [...this.pin] - } - }, - - /** - * Cancel pinCode input - */ - mainInputPinCancel() { - this.setUserOperation(4) - }, - - /** - * Join end authorization, business(FA流转)/1(资源访问): 0 - */ - joinAuthorize() { - this.status = 'join-authorize' - this.timing(60, 'join-authorize', () => { - this.setUserOperation(2) - router.back() - }) - }, - - /** - * Join end authorization, business(FA流转)/1(资源访问): 1 - */ - joinAuth() { - this.status = 'join-auth' - this.timing(60, 'join-auth', () => { - this.setUserOperation(2) - router.back() - }) - }, - - /** - * Join end authorization, business(FA流转)/1(资源访问): 1, show application icon - */ - joinAuthImage() { - this.status = 'join-auth-image' - this.timing(60, 'join-auth-image', () => { - this.setUserOperation(2) - router.back() - }) - }, - - /** - * Display pinCode at join end - */ - joinPin() { - this.status = 'join-pin' - }, - - /** - * Cancel authorization - */ - joinAuthorizeCancel() { - this.setUserOperation(1) - router.back() - }, - - /** - * Confirm authorization - */ - joinAuthorizeOk() { - this.setUserOperation(0) - this.joinPin() - }, - - /** - * Cancel authorization - */ - joinAuthCancel() { - this.setUserOperation(1) - router.back() - }, - - /** - * Confirm authorization - */ - joinAuthOk() { - this.setUserOperation(0) - this.joinPin() - }, - - /** - * Cancel authorization - */ - joinAuthImageCancel() { - this.setUserOperation(1) - router.back() - }, - - /** - * Confirm authorization - */ - joinAuthImageOk() { - this.setUserOperation(0) - this.joinPin() - }, - - /** - * Cancel authorization - */ - joinPinCancel() { - this.setUserOperation(3) - router.back() - }, - - /** - * Pure function countdown - * @param numb second - * @param status - * @param callback - * @return - */ - timing(numb, status, callback) { - this.timeRemaining = numb - const next = () => { - if (status != this.status) return - --this.timeRemaining - if (this.timeRemaining > 0) { - setTimeout(next, 1000) - } else { - callback() - } - } - next() - } -} diff --git a/display/entry/src/main/resources/base/element/string.json b/display/entry/src/main/resources/base/element/string.json deleted file mode 100644 index c0dd3a09e..000000000 --- a/display/entry/src/main/resources/base/element/string.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "string": [ - { - "name": "entry_MainAbility", - "value": "entry_MainAbility" - }, - { - "name": "mainability_description", - "value": "JS_Empty Ability" - } - ] -} \ No newline at end of file diff --git a/display/entry/src/main/resources/base/media/icon.png b/display/entry/src/main/resources/base/media/icon.png deleted file mode 100644 index ce307a8827bd75456441ceb57d530e4c8d45d36c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6790 zcmX|G1ymHk)?T_}Vd;>R?p|tHQo6fg38|$UVM!6BLrPFWk?s;$LOP{GmJpBl$qoSA!PUg~PA65-S00{{S`XKG6NkG0RgjEntPrmV+?0|00mu7;+5 zrdpa{2QLqPJ4Y{j7=Mrl{BaxrkdY69+c~(w{Fv-v&aR%aEI&JYSeRTLWm!zbv;?)_ ziZB;fwGbbeL5Q}YLx`J$lp~A09KK8t_z}PZ=4ZzgdeKtgoc+o5EvN9A1K1_<>M?MBqb#!ASf&# zEX?<)!RH(7>1P+j=jqG(58}TVN-$psA6K}atCuI!KTJD&FMmH-78ZejBm)0qc{ESp z|LuG1{QnBUJRg_E=h1#XMWt2%fcoN@l7eAS!Es?Q+;XsRNPhiiE=@AqlLkJzF`O18 zbsbSmKN=aaq8k3NFYZfDWpKmM!coBU0(XnL8R{4=i|wi{!uWYM2je{U{B*K2PVdu&=E zTq*-XsEsJ$u5H4g6DIm2Y!DN`>^v|AqlwuCD;w45K0@eqauiqWf7l&o)+YLHm~|L~ z7$0v5mkobriU!H<@mVJHLlmQqzQ3d6Rh_-|%Yy2li*tHO>_vcnuZ7OR_xkAIuIU&x z-|8Y0wj|6|a6_I(v91y%k_kNw6pnkNdxjqG8!%Vz_d%c_!X+6-;1`GC9_FpjoHev5fEV7RhJ>r=mh-jp$fqbqRJ=obwdgLDVP5+s zy1=_DWG0Y-Jb3t^WXmkr(d9~08k-|#Ly zaNOmT(^9tIb&eb4%CzIT zAm3CUtWSr1t4?h1kk#NBi{U|pJslvME{q|_eS^3En>SOqSxyuN1x;Is@8~m?*>}** znrRFArP!K_52RpX*&JHMR<^lVdm8ypJ}0R(SD(51j;6@ni$6bQ+2XL+R^|NnSp5}(kzvMZ^(@4fD_{QVu$(&K6H|C37TG1Am9Re{<<3gd zh@`>;BqkXMW&p0T6rt|iB$)~CvFe(XC)F9WgAZn*0@t$oZo;!*}r@_`h?KKH&6A@3= zISXoQB+~`op>NP-buiA*^0n{@i{_?MRG)&k)c)k_F+-2Lud!S9pc+i`s74NpBCaGF zXN+pHkubw*msGBTY27BKHv)RRh3;nMg4&$fD_6X9Vt~;_4D+5XPH~#Kn-yjcy!$}1 zigv#FNY>TqMhtIBb@UoF!cE~Q8~;!Pek>SQQwHnHuWKoVBosAiOr}q>!>aE*Krc)V zBUMEcJ5NU0g8}-h6i1zpMY9>m4ne?=U2~`w7K7Q0gB_=p@$5K7p6}thw z-~3dMj?YNX2X$lZ+7ngQ$=s}3mizNN@kE%OtB)?c&i~2L55z8^=yz;xMHLmlY>&Q# zJj?!)M#q_SyfkQh)k?j8IfLtB)ZCp|*vf4_B zos?73yd^h-Ac+;?E4*bpf=o*^3x3-`TVjbY4n6!EN10K6o@fxdyps05Vo3PU)otB} z`3kR+2w7_C#8Z!q`J)p{Vh!+m9-UP!$STp+Hb}}#@#_u^SsUQg<}59< zTvH3%XS4G+6FF^(m6bVF&nSUIXcl;nw{=H$%fgeJ>CgDYiLdpDXr{;-AnG z8dvcrHYVMI&`R6;GWekI@Ir3!uo)oz4^{6q0m^}@f2tM9&=YHNi6-?rh0-{+k@cQm zdp`g#YdQn%MDVg2GR>wZ`n2<0l4)9nx1Wfr&!Dvz=bPwU!h2S?ez6MVc5APE4-xLB zi&W9Q8k2@0w!C53g?iAIQ}~p*3O(@zja6KQ=M3zfW*_6o5SwR-)6VBh~m7{^-=MC-owYH5-u40a}a0liho3QZZ5L{bS_xM1)4}19)zTU$$MY zq3eZML1WC{K%YFd`Be0M-rkO^l?h{kM{$2oK1*A@HVJ57*yhDkUF!2WZ&oA4Y-sK( zCY69%#`mBCi6>6uw(x4gbFaP0+FD*JKJ-q!F1E?vLJ+d35!I5d7@^eU?(CS|C^tmI5?lv@s{{*|1F zFg|OzNpZ0hxljdjaW%45O0MOttRrd(Z?h{HYbB-KFUx&9GfFL3b8NwZ$zNu)WbBD` zYkj$^UB5%3Pj1MDr>S2Ejr9pUcgA!;ZG!@{uAy12)vG=*^9-|dNQBc8&`oxBlU~#y zs!anJX&T?57Jdr^sb>e+V`MVfY>Y0ESg7MG<7W0g&bR-ZYzzZ%2H&Etcp zcd6QeXO1D!5A#zM0lx*GH}`M)2~ZFLE;sP^RSB5wVMNfiZXPd(cmO>j=OSA3`o5r& zna(|^jGXbdN7PK)U8b7^zYtYkkeb%<%F~=OqB~kXMQkq}ii|skh@WSRt>5za;cjP0 zZ~nD%6)wzedqE}BMLt~qKwlvTr33))#uP~xyw#*Eaa|DbMQ_%mG0U8numf8)0DX`r zRoG2bM;#g|p-8gWnwRV5SCW0tLjLO&9Z?K>FImeIxlGUgo0Zk`9Qzhj1eco~7XZy+hXc@YF&ZQ=? zn*^1O56yK^x{y}q`j7}blGCx%dydV!c7)g~tJzmHhV=W~jbWRRR{1<^oDK+1clprm zz$eCy7y9+?{E|YgkW~}}iB#I4XoJ*xr8R?i_Hv$=Cof5bo-Nj~f`-DLebH}&0% zfQj9@WGd4;N~Y?mzQsHJTJq6!Qzl^-vwol(+fMt#Pl=Wh#lI5Vmu@QM0=_r+1wHt` z+8WZ~c2}KQQ+q)~2Ki77QvV&`xb|xVcTms99&cD$Zz4+-^R4kvUBxG8gDk7Y`K*)JZ^2rL(+ZWV~%W(@6 z)0bPArG#BROa_PHs~&WplQ_UIrpd)1N1QGPfv!J(Z9jNT#i%H?CE6|pPZb9hJ1JW4 z^q;ft#!HRNV0YgPojzIYT`8LuET2rUe-J|c!9l4`^*;4WtY@Ew@pL>wkjmMgGfN7 ze}}GtmU0@<_#08~I-Suk=^*9GLW=H4xhsml;vAV{%hy5Eegl@!6qKqbG024%n2HHw zCc@ivW_$@5ZoHP70(7D+(`PvgjW1Pd`wsiuv-aCukMrafwDm)B!xXVy*j2opohhoU zcJz%ADmj>i3`-3-$7nQKBQQuGY;2Qt&+(L~C>vSGFj5{Mlv?T_^dql;{zkpe4R1}R z%XfZyQ}wr*sr>jrKgm*PWLjuVc%6&&`Kbf1SuFpHPN&>W)$GmqC;pIoBC`=4-hPY8 zT*>%I2fP}vGW;R=^!1be?ta2UQd2>alOFFbVl;(SQJ4Jk#)4Z0^wpWEVvY4=vyDk@ zqlModi@iVPMC+{?rm=4(n+<;|lmUO@UKYA>EPTS~AndtK^Wy^%#3<;(dQdk3WaUkRtzSMC9}7x2||CNpF#(3T4C)@ z$~RWs`BNABKX|{cmBt>Q=&gkXl&x!!NK_%5hW0LS)Z4PB>%sV?F-{Wyj#s7W%$F{D zXdK^Fp3wvy+48+GP6F_|^PCRx=ddcTO3sG;B23A49~Qaw31SZ0Rc~`r4qqt%#OGW{ zCA_(LG5^N>yzUn&kAgVmxb=EA8s&tBXC}S1CZ(KoW)(%^JjLTPo^fs`Va;`=YlVPgmB$!yB}<(4ym6OeZ3xAJJ#;)2+B%p3P1Wt+d$eo`vz`T zXfUP2))kBDPoscH;Jc7I3NU<({|@wM$&GaDt`n7WLgIY3IA7A6-_R?z8N3mz|}*i z(zl5ot--Oq@f2-nv{X(ujT2T(k1vY_qh93pK@>H-qc%2Xta)IP0Q%zt%bqYgI`o!wv!0QerB`nCN^1n|@$sVOQ!V0teVG!I z_fD%JvfDeT1cK#-{o6Gv7}& zY0#NWin~kVaf$aufV&;63Hbs|`QVZWpDX6IMk1Hj2G}fiH9e-^6u2zf^FIr^BwD<6zjw63+{yUe8PUFvk8v{sJ=R{d#`O!sz`Q13~< zPT$JS(w=yQfU2`zPCNfSw=&zup@DXc(98afjhv@1w_f!m2Z>rMJ19AB&dB%P#Ls3b z=lK7OILM+SQ&VEd=1GN6o&>YVVtIzoZ%=Z_SdqJN2}E43{bE`>w+A;=y->@^k{oCC z$F*WTY&?34;kfyFV?b*Xb1Pq`Z=%OgwEg)Rz)tx=`f%5#w_INP=x&z5!jI;#;N$ma zhO)+MDm;SxOEVL15; zGq(v2pL3&P1Sl)8P*;G-fd{l1QJsv@e@d8)1PK4w2m*M%V3j-V~L^$i|&C@b?D?9tfwE{B^}Z$k8e5FmQ>v7Xz)sG32g9t}YBt zyR$+*_00RmPx+0mW+vVG4mxd(n$(eQf3-w>JPl2UJpafrPaL5@2j}%{VE-) zBI%6Qpj*dsdH<;g!S!avA~bv^0E+ zfyJbSjPb+j;J52U)<|cIcntQBI2T#>2;tOxu{%D?kML476AErF(qN9hPva5Nkc@BF zC-tLF@3ZFb%Kpj)M<{)x*l|*Ia@ECeXo2E4h2f!aV=cHAhi_E_mfUth(sM4^hJq7B zQsGWqdZUm9S%F`$nQ*_#NcuD`&)Ek%_s{&^78{9Hm ztri&rYLOxgFdG>O@+XHy z9#;|&vBCPXH5Mon^I`jSuR$&~ZWtyB67ujzFSj!51>#C}C17~TffQ{c-!QFQkTQ%! zIR^b1`zHx|*1GU?tbBx23weFLz5H?y_Q%N&t$}k?w+``2A=aotj0;2v$~AL z{scF-cL{wsdrmPvf#a9OHyYLcwQD4Kcm)`LLwMh4WT~p29f7M!iafJSU`IV}QY5Wa z(n44-9oA}?J{a+ah*@31WTs#&J#o1`H98#6IQf;Wv0N_!);f&9g7o-k(lW5rWnDUR zQBFIRG+X=6NnsI@mxnwm;tf5;_Uxg?jZ8m-m0}&6+DA!qam(p$mN5R})yA_7m$q@| zFEd|dpS595rxQr-n#GjI5i-AhnUE>Cr;jpCqSrD~EwK_DqI^7%3#p5)%T_od!t3SOmH9MyXeeGO2(UQL;ax|x?Ncixmeo1=$ z{-);Au{*tfzOG?KQ~K|ak8-HQ?`Pekhe2WM(8s{xv-p>Zmu_6{G!-oE$7$mY`MOJorI=+mMx?H;`pr!;fVYz?5~yXBACruWB`Ph zZM}90_<^OBxIhyZ9BW$`>6JvO;%VFpqVr8|7t3~AmxYak6?`Pp#c;**_SYmi`&z23 z`p6_~ePvH)C6x-G9$hgL=eVALq`-AiamN>!3~Lxw&{H(b{B(7xSRm6<3<{%{yXiH# zos5Rv1L+8fUKJLo%P>4I&$}y -#include #include +#include +#include #include "device_manager_callback.h" +#include "dm_device_info.h" #include "dm_subscribe_info.h" -#include "dm_app_image_info.h" namespace OHOS { namespace DistributedHardware { class DeviceManager { public: static DeviceManager &GetInstance(); + public: - virtual int32_t InitDeviceManager(std::string &pkgName, std::shared_ptr dmInitCallback) = 0; - virtual int32_t UnInitDeviceManager(std::string &pkgName) = 0; - virtual int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, - std::vector &deviceList) = 0; - virtual int32_t RegisterDevStateCallback(std::string &pkgName, std::string &extra, - std::shared_ptr callback) = 0; - virtual int32_t UnRegisterDevStateCallback(std::string &pkgName) = 0; - virtual int32_t StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &subscribeInfo, - std::shared_ptr callback) = 0; - virtual int32_t StopDeviceDiscovery(std::string &pkgName, uint16_t subscribeId) = 0; - virtual int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra, std::shared_ptr callback) = 0; - virtual int32_t CheckAuthentication(std::string &pkgName, std::string &authPara, - std::shared_ptr callback) = 0; - virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) = 0; - virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) = 0; - virtual int32_t RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback) = 0; - virtual int32_t UnRegisterDeviceManagerFaCallback(std::string &pkgName) = 0; + virtual int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) = 0; + virtual int32_t UnInitDeviceManager(const std::string &pkgName) = 0; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) = 0; + virtual int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &deviceInfo) = 0; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) = 0; + virtual int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra, std::shared_ptr callback) = 0; + virtual int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) = 0; + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const DmDeviceInfo &deviceInfo, + const std::string &extra, std::shared_ptr callback) = 0; + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) = 0; + virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) = 0; + virtual int32_t RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDeviceManagerFaCallback(const std::string &pkgName) = 0; + virtual int32_t GetFaParam(const std::string &pkgName, DmAuthParam &faParam) = 0; + virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) = 0; + virtual int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid) = 0; + virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) = 0; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_H +#endif // DEVICE_MANAGER_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 786e8ca85..f175f2344 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_CALLBACK_H -#define OHOS_DEVICE_MANAGER_CALLBACK_H +#ifndef OHOS_DM_CALLBACK_H +#define OHOS_DM_CALLBACK_H #include #include @@ -25,44 +25,56 @@ namespace OHOS { namespace DistributedHardware { class DmInitCallback { public: - virtual ~DmInitCallback() {} + virtual ~DmInitCallback() + { + } virtual void OnRemoteDied() = 0; }; class DeviceStateCallback { public: - virtual ~DeviceStateCallback() {} + virtual ~DeviceStateCallback() + { + } virtual void OnDeviceOnline(const DmDeviceInfo &deviceInfo) = 0; - virtual void OnDeviceReady(const DmDeviceInfo &deviceInfo) = 0; virtual void OnDeviceOffline(const DmDeviceInfo &deviceInfo) = 0; virtual void OnDeviceChanged(const DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceReady(const DmDeviceInfo &deviceInfo) = 0; }; -class DiscoverCallback { +class DiscoveryCallback { public: - virtual ~DiscoverCallback() {} + virtual ~DiscoveryCallback() + { + } virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; - virtual void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) = 0; + virtual void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) = 0; virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) = 0; }; class AuthenticateCallback { public: - virtual ~AuthenticateCallback() {} - virtual void OnAuthResult(std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) = 0; + virtual ~AuthenticateCallback() + { + } + virtual void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) = 0; }; -class CheckAuthCallback { +class VerifyAuthCallback { public: - virtual ~CheckAuthCallback() {} - virtual void OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) = 0; + virtual ~VerifyAuthCallback() + { + } + virtual void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) = 0; }; - class DeviceManagerFaCallback { public: - virtual ~DeviceManagerFaCallback() {} - virtual void OnCall(std::string ¶mJson) = 0; + virtual ~DeviceManagerFaCallback() + { + } + virtual void OnCall(const std::string ¶mJson) = 0; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_CALLBACK_H +#endif // OHOS_DM_CALLBACK_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 8e46f12fb..46d8c3222 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,41 +16,57 @@ #ifndef OHOS_DEVICE_MANAGER_IMPL_H #define OHOS_DEVICE_MANAGER_IMPL_H -#include - #include "device_manager.h" - -#include "ipc_client_proxy.h" #include "ipc_client_manager.h" - -#include "single_instance.h" +#include "ipc_client_proxy.h" namespace OHOS { namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { -DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); public: - virtual int32_t InitDeviceManager(std::string &pkgName, - std::shared_ptr dmInitCallback) override; - virtual int32_t UnInitDeviceManager(std::string &pkgName) override; - virtual int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, - std::vector &deviceList) override; - virtual int32_t RegisterDevStateCallback(std::string &pkgName, std::string &extra, - std::shared_ptr callback) override; - virtual int32_t UnRegisterDevStateCallback(std::string &pkgName) override; - virtual int32_t StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &subscribeInfo, - std::shared_ptr callback) override; - virtual int32_t StopDeviceDiscovery(std::string &pkgName, uint16_t subscribeId) override; - virtual int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra, - std::shared_ptr callback) override; - virtual int32_t CheckAuthentication(std::string &pkgName, std::string &authPara, - std::shared_ptr callback) override; - virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) override; - virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) override; - virtual int32_t RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback) override; - virtual int32_t UnRegisterDeviceManagerFaCallback(std::string &pkgName) override; + static DeviceManagerImpl &GetInstance(); + +public: + virtual int32_t InitDeviceManager(const std::string &pkgName, + std::shared_ptr dmInitCallback) override; + virtual int32_t UnInitDeviceManager(const std::string &pkgName) override; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) override; + virtual int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &deviceInfo) override; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) override; + virtual int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra, + std::shared_ptr callback) override; + virtual int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) override; + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const DmDeviceInfo &deviceInfo, + const std::string &extra, + std::shared_ptr callback) override; + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) override; + virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) override; + virtual int32_t RegisterDeviceManagerFaCallback(const std::string &packageName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDeviceManagerFaCallback(const std::string &pkgName) override; + virtual int32_t GetFaParam(const std::string &pkgName, DmAuthParam &faParam) override; + virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) override; + virtual int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) override; + virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) override; + +private: + DeviceManagerImpl() = default; + ~DeviceManagerImpl() = default; + DeviceManagerImpl(const DeviceManagerImpl &) = delete; + DeviceManagerImpl &operator=(const DeviceManagerImpl &) = delete; + DeviceManagerImpl(DeviceManagerImpl &&) = delete; + DeviceManagerImpl &operator=(DeviceManagerImpl &&) = delete; + +private: + bool isSystemAppCalling(void); + private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); diff --git a/interfaces/inner_kits/native_cpp/include/dm_app_image_info.h b/interfaces/inner_kits/native_cpp/include/dm_app_image_info.h index 9fbccd7d6..91636af6e 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_app_image_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_app_image_info.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H -#define OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H +#ifndef OHOS_DM_APP_IMAGE_INFO_H +#define OHOS_DM_APP_IMAGE_INFO_H #include @@ -48,7 +48,7 @@ public: return; } - appThumbnail = new (std::nothrow) uint8_t[appThumbnailLen_] {0}; + appThumbnail = new (std::nothrow) uint8_t[appThumbnailLen_]{0}; if (appThumbnail != nullptr) { appThumbnailLen = appThumbnailLen_; } @@ -56,7 +56,7 @@ public: int32_t SetThumbnailData(uint8_t *srcBuffer, int32_t srcBufferLen, int32_t copyIndex, int32_t copyLen) { - if (srcBuffer == nullptr || srcBufferLen <= 0 || copyLen > srcBufferLen || copyIndex < 0) { + if (srcBuffer == nullptr || srcBufferLen <= 0 || copyLen > srcBufferLen || copyIndex < 0) { return -1; } @@ -94,7 +94,7 @@ public: } } - DmAppImageInfo& operator=(const DmAppImageInfo &other) + DmAppImageInfo &operator=(const DmAppImageInfo &other) { if (this != &other) { SaveData(other.GetAppIcon(), other.GetAppIconLen(), other.GetAppThumbnail(), other.GetAppThumbnailLen()); @@ -102,8 +102,8 @@ public: return *this; } - DmAppImageInfo(DmAppImageInfo&&) = delete; - DmAppImageInfo& operator=(DmAppImageInfo&&) = delete; + DmAppImageInfo(DmAppImageInfo &&) = delete; + DmAppImageInfo &operator=(DmAppImageInfo &&) = delete; int32_t GetAppIconLen() const { @@ -124,6 +124,7 @@ public: { return appThumbnail; } + private: void SaveData(const uint8_t *appIcon_, int32_t appIconLen_, const uint8_t *appThumbnail_, int32_t appThumbnailLen_) { @@ -140,7 +141,7 @@ private: appIcon = nullptr; appIconLen = 0; } - appIcon = new (std::nothrow) uint8_t[appIconLen_] {0}; + appIcon = new (std::nothrow) uint8_t[appIconLen_]{0}; } if (appIcon != nullptr) { appIconLen = appIconLen_; @@ -160,7 +161,7 @@ private: appThumbnail = nullptr; appThumbnailLen = 0; } - appThumbnail = new (std::nothrow) uint8_t[appThumbnailLen_] {0}; + appThumbnail = new (std::nothrow) uint8_t[appThumbnailLen_]{0}; } if (appThumbnail != nullptr) { appThumbnailLen = appThumbnailLen_; @@ -170,14 +171,15 @@ private: } } } + private: - int32_t appIconLen {0}; - uint8_t *appIcon {nullptr}; - int32_t appThumbnailLen {0}; - uint8_t *appThumbnail {nullptr}; + int32_t appIconLen{0}; + uint8_t *appIcon{nullptr}; + int32_t appThumbnailLen{0}; + uint8_t *appThumbnail{nullptr}; const int32_t ICON_MAX_LEN = 32 * 1024; const int32_t THUMB_MAX_LEN = 153 * 1024; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H +#endif // OHOS_DM_APP_IMAGE_INFO_H diff --git a/interfaces/inner_kits/native_cpp/include/dm_device_info.h b/interfaces/inner_kits/native_cpp/include/dm_device_info.h index 2e084e749..88be8a134 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_DEVICE_INFO_H -#define OHOS_DEVICE_MANAGER_DEVICE_INFO_H +#ifndef OHOS_DM_DEVICE_INFO_H +#define OHOS_DM_DEVICE_INFO_H #include @@ -25,31 +25,34 @@ namespace OHOS { namespace DistributedHardware { -typedef enum DMDeviceType { +typedef enum DmDeviceType { DEVICE_TYPE_UNKNOWN = 0x00, DEVICE_TYPE_WIFI_CAMERA = 0x08, DEVICE_TYPE_AUDIO = 0x0A, + DEVICE_TYPE_PC = 0x0C, DEVICE_TYPE_PHONE = 0x0E, DEVICE_TYPE_PAD = 0x11, DEVICE_TYPE_WATCH = 0x6D, DEVICE_TYPE_CAR = 0x83, DEVICE_TYPE_TV = 0x9C, -} DMDeviceType; +} DmDeviceType; typedef enum DmDeviceState { DEVICE_STATE_UNKNOWN = 0, DEVICE_STATE_ONLINE = 1, DEVICE_STATE_OFFLINE = 2, DEVICE_INFO_CHANGED = 3, + DEVICE_INFO_READY = 4, } DmDeviceState; typedef struct DmDeviceInfo { char deviceId[DM_MAX_DEVICE_ID_LEN]; char deviceName[DM_MAX_DEVICE_NAME_LEN]; - DMDeviceType deviceTypeId; + uint16_t deviceTypeId; } DmDeviceInfo; typedef struct DmAuthParam { + std::string authToken; std::string packageName; std::string appName; std::string appDescription; @@ -60,6 +63,7 @@ typedef struct DmAuthParam { int32_t pinToken; DmAppImageInfo imageinfo; } DmAuthParam; + } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_DEVICE_INFO_H +#endif // OHOS_DM_DEVICE_INFO_H diff --git a/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h b/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h index 2101c59e5..87561c4e8 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H -#define OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H +#ifndef OHOS_DM_SUBSCRIBE_INFO_H +#define OHOS_DM_SUBSCRIBE_INFO_H #include @@ -26,7 +26,7 @@ typedef enum DmDiscoverMode { /* Passive */ DM_DISCOVER_MODE_PASSIVE = 0x55, /* Proactive */ - DM_DISCOVER_MODE_ACTIVE = 0xAA + DM_DISCOVER_MODE_ACTIVE = 0xAA } DmDiscoverMode; typedef enum DmExchangeMedium { @@ -76,4 +76,4 @@ typedef struct DmSubscribeInfo { } DmSubscribeInfo; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H +#endif // OHOS_DM_SUBSCRIBE_INFO_H diff --git a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h index 818746ff7..85ee63e9c 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,12 +13,12 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_H +#ifndef OHOS_DM_IPC_CLIENT_H +#define OHOS_DM_IPC_CLIENT_H #include -#include #include +#include #include "ipc_req.h" #include "ipc_rsp.h" @@ -26,12 +26,13 @@ namespace OHOS { namespace DistributedHardware { class IpcClient { -DECLARE_IPC_INTERFACE(IpcClient); + DECLARE_IPC_INTERFACE(IpcClient); + public: - virtual int32_t Init(std::string &pkgName) = 0; - virtual int32_t UnInit(std::string &pkgName) = 0; + virtual int32_t Init(const std::string &pkgName) = 0; + virtual int32_t UnInit(const std::string &pkgName) = 0; virtual int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) = 0; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_H \ No newline at end of file +#endif // OHOS_DM_IPC_CLIENT_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h index faa9e1a4b..7571f0188 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_PROXY_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_PROXY_H +#ifndef OHOS_DM_IPC_CLIENT_PROXY_H +#define OHOS_DM_IPC_CLIENT_PROXY_H #include #include @@ -26,16 +26,19 @@ namespace OHOS { namespace DistributedHardware { class IpcClientProxy : public IpcClient { -DECLARE_IPC_INTERFACE(IpcClientProxy); + DECLARE_IPC_INTERFACE(IpcClientProxy); + public: - IpcClientProxy(std::shared_ptr ipcClientManager) : ipcClientManager_(ipcClientManager) {}; + IpcClientProxy(std::shared_ptr ipcClientManager) : ipcClientManager_(ipcClientManager){}; + public: - virtual int32_t Init(std::string &pkgName); - virtual int32_t UnInit(std::string &pkgName); + virtual int32_t Init(const std::string &pkgName); + virtual int32_t UnInit(const std::string &pkgName); virtual int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + private: - std::shared_ptr ipcClientManager_ {nullptr}; + std::shared_ptr ipcClientManager_{nullptr}; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_PROXY_H \ No newline at end of file +#endif // OHOS_DM_IPC_CLIENT_PROXY_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_manager.h b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_manager.h index 997b5d39b..2142ffad9 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_manager.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_manager.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,12 +13,12 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H +#ifndef OHOS_DM_IPC_CLIENT_MANAGER_H +#define OHOS_DM_IPC_CLIENT_MANAGER_H #include -#include #include +#include #include "ipc_client.h" #include "ipc_client_server_proxy.h" @@ -26,17 +26,20 @@ namespace OHOS { namespace DistributedHardware { class IpcClientManager : public IpcClient { -DECLARE_IPC_INTERFACE(IpcClientManager); + DECLARE_IPC_INTERFACE(IpcClientManager); + public: - virtual int32_t Init(std::string &pkgName) override; - virtual int32_t UnInit(std::string &pkgName) override; + virtual int32_t Init(const std::string &pkgName) override; + virtual int32_t UnInit(const std::string &pkgName) override; virtual int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; + private: - bool IsInit(std::string &pkgName); + bool IsInit(const std::string &pkgName); + private: IpcClientServerProxy serverProxy_; std::set packageInitSet_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H \ No newline at end of file +#endif // OHOS_DM_IPC_CLIENT_MANAGER_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_server_proxy.h b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_server_proxy.h index d7497c55c..29cf5c71d 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_server_proxy.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_server_proxy.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,33 +13,34 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H +#ifndef OHOS_DM_IPC_CLIENT_SERVER_PROXY_H +#define OHOS_DM_IPC_CLIENT_SERVER_PROXY_H #include #include #include +#include "ipc_req.h" +#include "ipc_rsp.h" #include "iproxy_client.h" #include "liteipc_adapter.h" #include "samgr_lite.h" -#include "ipc_req.h" -#include "ipc_rsp.h" - namespace OHOS { namespace DistributedHardware { class IpcClientServerProxy { public: int32_t Init(); int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + private: IClientProxy *GetServerProxy(void); int32_t RegisterServerDeathCb(void); + private: std::mutex lock_; - IClientProxy *serviceProxy_ {nullptr}; + IClientProxy *serviceProxy_{nullptr}; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H +#endif // OHOS_DM_IPC_CLIENT_SERVER_PROXY_H diff --git a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_stub.h b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_stub.h index 672e4cb89..caec91608 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_stub.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_stub.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,31 +13,32 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H +#ifndef OHOS_DM_IPC_CLIENT_STUB_H +#define OHOS_DM_IPC_CLIENT_STUB_H -#include #include +#include #include "liteipc_adapter.h" - #include "single_instance.h" namespace OHOS { namespace DistributedHardware { class IpcClientStub { -DECLARE_SINGLE_INSTANCE(IpcClientStub); + DECLARE_SINGLE_INSTANCE(IpcClientStub); + public: int32_t Init(); SvcIdentity GetSvcIdentity() const { return clientIdentity_; } + private: std::mutex lock_; - bool bInit {false}; + bool bInit{false}; SvcIdentity clientIdentity_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H +#endif // OHOS_DM_IPC_CLIENT_STUB_H diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_manager.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_manager.h index 422f29728..058f74423 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_manager.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_manager.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,20 +13,19 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H +#ifndef OHOS_DM_IPC_CLIENT_MANAGER_H +#define OHOS_DM_IPC_CLIENT_MANAGER_H #include -#include #include +#include #include -#include "iremote_object.h" - #include "ipc_client.h" #include "ipc_client_stub.h" #include "ipc_def.h" #include "ipc_remote_broker.h" +#include "iremote_object.h" namespace OHOS { namespace DistributedHardware { @@ -38,21 +37,24 @@ public: }; class IpcClientManager : public IpcClient { -friend class DmDeathRecipient; -DECLARE_IPC_INTERFACE(IpcClientManager); + friend class DmDeathRecipient; + DECLARE_IPC_INTERFACE(IpcClientManager); + public: - virtual int32_t Init(std::string &pkgName) override; - virtual int32_t UnInit(std::string &pkgName) override; + virtual int32_t Init(const std::string &pkgName) override; + virtual int32_t UnInit(const std::string &pkgName) override; virtual int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; + private: - bool IsInit(std::string &pkgName); + bool IsInit(const std::string &pkgName); int32_t ClientInit(); + private: std::mutex lock_; std::map> dmListener_; - sptr dmInterface_ {nullptr}; - sptr dmRecipient_ {nullptr}; + sptr dmInterface_{nullptr}; + sptr dmRecipient_{nullptr}; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H \ No newline at end of file +#endif // OHOS_DM_IPC_CLIENT_MANAGER_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_server_proxy.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_server_proxy.h index 3fd0586cd..dce3c3ddc 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_server_proxy.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_server_proxy.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,27 +13,28 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H +#ifndef OHOS_DM_IPC_CLIENT_SERVER_PROXY_H +#define OHOS_DM_IPC_CLIENT_SERVER_PROXY_H #include #include -#include "iremote_proxy.h" #include "ipc_remote_broker.h" #include "ipc_req.h" #include "ipc_rsp.h" +#include "iremote_proxy.h" namespace OHOS { namespace DistributedHardware { class IpcClientServerProxy : public IRemoteProxy { public: - explicit IpcClientServerProxy(const sptr &impl) : IRemoteProxy(impl) {}; - ~IpcClientServerProxy() {}; + explicit IpcClientServerProxy(const sptr &impl) : IRemoteProxy(impl){}; + ~IpcClientServerProxy(){}; int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; + private: static inline BrokerDelegator delegator_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H +#endif // OHOS_DM_IPC_CLIENT_SERVER_PROXY_H diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_stub.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_stub.h index 61633f6e8..ccb4e0b7a 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_stub.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_stub.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,28 +13,27 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H -#define OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H +#ifndef OHOS_DM_IPC_CLIENT_STUB_H +#define OHOS_DM_IPC_CLIENT_STUB_H #include #include -#include "iremote_stub.h" -#include "iremote_broker.h" - #include "ipc_remote_broker.h" #include "ipc_req.h" #include "ipc_rsp.h" +#include "iremote_broker.h" +#include "iremote_stub.h" namespace OHOS { namespace DistributedHardware { class IpcClientStub : public IRemoteStub { public: - IpcClientStub() {}; - ~IpcClientStub() {}; + IpcClientStub(){}; + ~IpcClientStub(){}; int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H +#endif // OHOS_DM_IPC_CLIENT_STUB_H diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_remote_broker.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_remote_broker.h index b2b8618c7..ce5ded9cf 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_remote_broker.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_remote_broker.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,26 +13,28 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_REMOTE_BROKER_H -#define OHOS_DEVICE_MANAGER_IPC_REMOTE_BROKER_H +#ifndef OHOS_DM_IPC_REMOTE_BROKER_H +#define OHOS_DM_IPC_REMOTE_BROKER_H #include #include -#include "iremote_broker.h" - #include "ipc_req.h" #include "ipc_rsp.h" +#include "iremote_broker.h" namespace OHOS { namespace DistributedHardware { class IpcRemoteBroker : public OHOS::IRemoteBroker { public: - virtual ~IpcRemoteBroker() {} + virtual ~IpcRemoteBroker() + { + } virtual int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) = 0; + public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.devicemanager"); }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_REMOTE_BROKER_H +#endif // OHOS_DM_IPC_REMOTE_BROKER_H diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index a654b5536..2f882bb12 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 @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,63 +13,66 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_NOTIFY_H -#define OHOS_DEVICE_MANAGER_NOTIFY_H +#ifndef OHOS_DM_NOTIFY_H +#define OHOS_DM_NOTIFY_H -#include #include -#include -#include #include +#include +#include +#include +#include "device_manager_callback.h" #include "dm_device_info.h" #include "dm_subscribe_info.h" -#include "device_manager_callback.h" #include "single_instance.h" namespace OHOS { namespace DistributedHardware { class DeviceManagerNotify { -DECLARE_SINGLE_INSTANCE(DeviceManagerNotify); + DECLARE_SINGLE_INSTANCE(DeviceManagerNotify); + public: - void RegisterDeathRecipientCallback(std::string &pkgName, std::shared_ptr dmInitCallback); - void UnRegisterDeathRecipientCallback(std::string &pkgName); - void RegisterDeviceStateCallback(std::string &pkgName, std::shared_ptr callback); - void UnRegisterDeviceStateCallback(std::string &pkgName); - void RegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId, - std::shared_ptr callback); - void UnRegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId); - void RegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId, - std::shared_ptr callback); - void UnRegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId); - void UnRegisterPackageCallback(std::string &pkgName); - void RegisterCheckAuthenticationCallback(std::string &pkgName, std::string &authPara, - std::shared_ptr callback); - void UnRegisterCheckAuthenticationCallback(std::string &pkgName); - void RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback); - void UnRegisterDeviceManagerFaCallback(std::string &pkgName); + void RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback); + void UnRegisterDeathRecipientCallback(const std::string &pkgName); + void RegisterDeviceStateCallback(const std::string &pkgName, std::shared_ptr callback); + void UnRegisterDeviceStateCallback(const std::string &pkgName); + void RegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId, + std::shared_ptr callback); + void UnRegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId); + void RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback); + void UnRegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId); + void UnRegisterPackageCallback(const std::string &pkgName); + void RegisterVerifyAuthenticationCallback(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback); + void UnRegisterVerifyAuthenticationCallback(const std::string &pkgName); + void RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback); + void UnRegisterDeviceManagerFaCallback(const std::string &pkgName); + public: void OnRemoteDied(); - void OnDeviceOnline(std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnDeviceOffline(std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnDeviceChanged(std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnDeviceFound(std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo); - void OnDiscoverFailed(std::string &pkgName, uint16_t subscribeId, int32_t failedReason); - void OnDiscoverySuccess(std::string &pkgName, uint16_t subscribeId); - void OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, uint32_t status, - uint32_t reason); - void OnCheckAuthResult(std::string &pkgName, std::string &deviceId, int32_t resultCode, int32_t flag); + void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo); + void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason); + void OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId); + void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, + uint32_t status, uint32_t reason); + void OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode, int32_t flag); void OnFaCall(std::string &pkgName, std::string ¶mJson); + private: std::mutex lock_; std::map> deviceStateCallback_; - std::map>> deviceDiscoverCallbacks_; + std::map>> deviceDiscoveryCallbacks_; std::map>> authenticateCallback_; - std::map> checkauthcallback_; + std::map> verifyAuthCallback_; std::map> dmInitCallback_; std::map> dmFaCallback_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_NOTIFY_H +#endif // OHOS_DM_NOTIFY_H diff --git a/interfaces/inner_kits/native_cpp/src/device_manager.cpp b/interfaces/inner_kits/native_cpp/src/device_manager.cpp index 4bedc0a57..0e934d8d2 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 23f7ef2c6..efb536dbb 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,279 +15,521 @@ #include "device_manager_impl.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "device_manager_notify.h" -#include "constants.h" +#include "bundle_constants.h" +#include "bundle_info.h" +#include "bundle_mgr_client.h" +#include "bundle_mgr_interface.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "device_manager_notify.h" +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_authenticate_device_req.h" -#include "ipc_check_authenticate_req.h" +#include "ipc_get_dmfaparam_rsp.h" +#include "ipc_get_info_by_network_req.h" +#include "ipc_get_info_by_network_rsp.h" +#include "ipc_get_local_device_info_rsp.h" #include "ipc_get_trustdevice_req.h" #include "ipc_get_trustdevice_rsp.h" -#include "ipc_rsp.h" #include "ipc_req.h" +#include "ipc_rsp.h" +#include "ipc_set_useroperation_req.h" +#include "ipc_skeleton.h" #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.h" -#include "ipc_get_authenticationparam_rsp.h" -#include "ipc_set_useroperation_req.h" +#include "ipc_unauthenticate_device_req.h" +#include "ipc_verify_authenticate_req.h" + +using namespace OHOS::AppExecFwk; +using namespace OHOS::AppExecFwk::Constants; namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); +bool DeviceManagerImpl::isSystemAppCalling(void) +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + if (uid < 0) { + LOGI("app caller uid is: %d,", uid); + return false; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + LOGE("failed to get system ability mgr."); + return false; + } + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + LOGE("failed to get bundle manager proxy."); + return false; + } -int32_t DeviceManagerImpl::InitDeviceManager(std::string &pkgName, std::shared_ptr dmInitCallback) + LOGI("get bundle manager proxy success."); + sptr iBundleMgr = iface_cast(remoteObject); + return iBundleMgr->CheckIsSystemAppByUid(uid); +} + +DeviceManagerImpl &DeviceManagerImpl::GetInstance() { - DMLOG(DM_LOG_INFO, "DeviceManager::InitDeviceManager start, pkgName: %s", pkgName.c_str()); + 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 (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty() || dmInitCallback == nullptr) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager error: Invalid parameter"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("InitDeviceManager error: Invalid parameter"); + return DM_INVALID_VALUE; } int32_t ret = ipcClientProxy_->Init(pkgName); - if (ret != DEVICEMANAGER_OK) { - return ret; + if (ret != DM_OK) { + LOGE("InitDeviceManager error: proxy init failed ret: %d", ret); + return DM_INIT_FAILED; } + DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); - DMLOG(DM_LOG_INFO, "success"); - return DEVICEMANAGER_OK; + LOGI("InitDeviceManager success"); + return DM_OK; } -int32_t DeviceManagerImpl::UnInitDeviceManager(std::string &pkgName) +int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) { - DMLOG(DM_LOG_INFO, "DeviceManager::UnInitDeviceManager start, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::UnInitDeviceManager start, pkgName: %s", pkgName.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager error: Invalid parameter"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("UnInitDeviceManager error: Invalid parameter"); + return DM_INVALID_VALUE; } int32_t ret = ipcClientProxy_->UnInit(pkgName); - if (ret != DEVICEMANAGER_OK) { - return ret; + if (ret != DM_OK) { + LOGE("UnInitDeviceManager error: proxy unInit failed ret: %d", ret); + return DM_UNINIT_FAILED; } + DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); - DMLOG(DM_LOG_INFO, "DeviceManager::UnInitDeviceManager completed with errcode %d", ret); - return DEVICEMANAGER_OK; + LOGI("UnInitDeviceManager success"); + return DM_OK; } -int32_t DeviceManagerImpl::GetTrustedDeviceList(std::string &pkgName, std::string &extra, - std::vector &deviceList) +int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) { - DMLOG(DM_LOG_INFO, "DeviceManager::GetTrustedDeviceList start, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::GetTrustedDeviceList start, pkgName: %s", pkgName.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("GetTrustedDeviceList error: Invalid para"); + return DM_INVALID_VALUE; } - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetExtra(extra); - if (ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; + int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); + if (ret != DM_OK) { + LOGE("GetTrustedDeviceList error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; + } + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGI("GetTrustedDeviceList error: failed ret: %d", ret); + return DM_IPC_RESPOND_ERROR; } - if (rsp->GetErrCode() == DEVICEMANAGER_OK) { - deviceList = rsp->GetDeviceVec(); + + 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 (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + int32_t ret = ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp); + if (ret != DM_OK) { + LOGE("GetLocalDeviceInfo error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; } - DMLOG(DM_LOG_INFO, "DeviceManager::GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGI("GetLocalDeviceInfo error: failed ret: %d", ret); + return DM_IPC_RESPOND_ERROR; + } + + info = rsp->GetLocalDeviceInfo(); + LOGI("GetLocalDeviceInfo completed,pkgname%s", req->GetPkgName().c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::RegisterDevStateCallback(std::string &pkgName, std::string &extra, - std::shared_ptr callback) +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) { - DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("RegisterDevStateCallback error: Invalid para"); + return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); - DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + LOGI("RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::UnRegisterDevStateCallback(std::string &pkgName) +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) { - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::UnRegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("UnRegisterDevStateCallback error: Invalid para"); + return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + LOGI("UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &subscribeInfo, - std::shared_ptr callback) +int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra, std::shared_ptr callback) { - DMLOG(DM_LOG_INFO, "DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("StartDeviceDiscovery error: Invalid para"); + return DM_INVALID_VALUE; } - DMLOG(DM_LOG_INFO, "DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); - DeviceManagerNotify::GetInstance().RegisterDiscoverCallback(pkgName, subscribeInfo.subscribeId, callback); + 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 (ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; + int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp); + if (ret != DM_OK) { + LOGE("StartDeviceDiscovery error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; } - int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "DeviceManager StartDeviceDiscovery Failed with ret %d", ret); - return ret; + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StartDeviceDiscovery error: Failed with ret %d", ret); + return DM_IPC_RESPOND_ERROR; } - return DEVICEMANAGER_OK; + + LOGI("StartDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::StopDeviceDiscovery(std::string &pkgName, uint16_t subscribeId) +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - DMLOG(DM_LOG_INFO, "DeviceManager::StopDeviceDiscovery start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::StopDeviceDiscovery start , pkgName: %s", pkgName.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("StopDeviceDiscovery error: Invalid para"); + return DM_INVALID_VALUE; } - DMLOG(DM_LOG_INFO, "StopDeviceDiscovery in, pkgName %s", pkgName.c_str()); + 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 (ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; + int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + if (ret != DM_OK) { + LOGE("StopDeviceDiscovery error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; } - int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery Failed with ret %d", ret); - return ret; + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StopDeviceDiscovery error: Failed with ret %d", ret); + return DM_IPC_RESPOND_ERROR; } - DeviceManagerNotify::GetInstance().UnRegisterDiscoverCallback(pkgName, subscribeId); - DMLOG(DM_LOG_INFO, "DeviceManager::StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + + DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + LOGI("StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra, std::shared_ptr callback) +int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const DmDeviceInfo &deviceInfo, const std::string &extra, + std::shared_ptr callback) { - DMLOG(DM_LOG_INFO, "DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("AuthenticateDevice error: Invalid para"); + return DM_INVALID_VALUE; } - DMLOG(DM_LOG_INFO, "AuthenticateDevice in, pkgName %s", pkgName.c_str()); 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); - req->SetAppImageInfo(imageInfo); - if (ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; + int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); + if (ret != DM_OK) { + LOGE("AuthenticateDevice error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; } - int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice Failed with ret %d", ret); - return ret; + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("AuthenticateDevice error: Failed with ret %d", ret); + return DM_IPC_RESPOND_ERROR; } + std::string strDeviceId = deviceInfo.deviceId; DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, strDeviceId, callback); - DMLOG(DM_LOG_INFO, "DeviceManager::AuthenticateDevice completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + LOGI("DeviceManager::AuthenticateDevice completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::CheckAuthentication(std::string &pkgName, std::string &authPara, - std::shared_ptr callback) +int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { - DMLOG(DM_LOG_INFO, "DeviceManager::CheckAuthentication start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s, deviceId: %s", pkgName.c_str(), deviceId.c_str()); + if (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } + + if (deviceId.empty()) { + LOGE("UnAuthenticateDevice error: Invalid para"); + return DM_INVALID_VALUE; + } + + DmDeviceInfo deviceInfo; + strcpy(deviceInfo.deviceId, deviceId.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetDeviceInfo(deviceInfo); + int32_t ret = ipcClientProxy_->SendRequest(UNAUTHENTICATE_DEVICE, req, rsp); + if (ret != DM_OK) { + LOGE("UnAuthenticateDevice error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; + } + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("UnAuthenticateDevice error: Failed with ret %d", ret); + return DM_IPC_RESPOND_ERROR; + } + + DeviceManagerNotify::GetInstance().UnRegisterAuthenticateCallback(pkgName, deviceId); + LOGI("UnAuthenticateDevice completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + LOGI("DeviceManager::RegisterDeviceManagerFaCallback start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty() || callback == nullptr) { + LOGE("RegisterDeviceManagerFaCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); + LOGI("DeviceManager::RegisterDevStateCallback completed, pkgName: %s", pkgName.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 (!isSystemAppCalling()) { + LOGI("the caller is not a system app"); + return DM_NOT_SYSTEM_APP; + } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("VerifyAuthentication error: Invalid para"); + return DM_INVALID_VALUE; } - DMLOG(DM_LOG_INFO, "CheckAuthentication in, pkgName %s", pkgName.c_str()); - std::shared_ptr req = std::make_shared(); + + 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 (ipcClientProxy_->SendRequest(CHECK_AUTHENTICATION, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; - } - int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "CheckAuthentication Failed with ret %d", ret); + int32_t ret = ipcClientProxy_->SendRequest(VERIFY_AUTHENTICATION, req, rsp); + if (ret != DM_OK) { + LOGE("VerifyAuthentication error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("VerifyAuthentication error: Failed with ret %d", ret); return ret; } - DeviceManagerNotify::GetInstance().RegisterCheckAuthenticationCallback(pkgName, authPara, callback); - DMLOG(DM_LOG_INFO, "DeviceManager::CheckAuthentication completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + + LOGI("VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) +int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &dmFaParam) { - DMLOG(DM_LOG_INFO, "DeviceManager::GetAuthenticationParam start"); + LOGI("DeviceManager::GetFaParam 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(); + std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - if (ipcClientProxy_->SendRequest(SERVER_GET_AUTHENTCATION_INFO, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; + + if (ipcClientProxy_->SendRequest(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { + LOGI("DeviceManagerImpl::GetFaParam start 2"); + return DM_IPC_SEND_REQUEST_FAILED; } - authParam = rsp->GetAuthParam(); - return DEVICEMANAGER_OK; + dmFaParam = rsp->GetDmAuthParam(); + LOGI("GetFaParam completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action) +int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action) { - DMLOG(DM_LOG_INFO, "DeviceManager::SetUserOperation start"); + 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 (ipcClientProxy_->SendRequest(SERVER_USER_AUTHORIZATION_OPERATION, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; + if (ipcClientProxy_->SendRequest(SERVER_USER_AUTH_OPERATION, req, rsp) != DM_OK) { + return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "CheckAuthentication Failed with ret %d", ret); + if (ret != DM_OK) { + LOGE("CheckAuthentication Failed with ret %d", ret); return ret; } - return DEVICEMANAGER_OK; + LOGI("SetUserOperation completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback) +int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) { - DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDeviceManagerFaCallback start, pkgName: %s", packageName.c_str()); - if (packageName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; - } - DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(packageName, callback); - DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback completed, pkgName: %s", packageName.c_str()); - return DEVICEMANAGER_OK; + 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->SetNetWorkId(netWorkId); + + if (ipcClientProxy_->SendRequest(GET_UDID_BY_NETWORK, req, rsp) != DM_OK) { + return DM_IPC_SEND_REQUEST_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("CheckAuthentication Failed with ret %d", ret); + return ret; + } + udid = rsp->GetUdid(); + return DM_OK; } -int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(std::string &pkgName) +int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) { - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDeviceManagerFaCallback start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("VerifyAuthentication failed, pkgName is empty"); + return DM_INVALID_VALUE; } - DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetNetWorkId(netWorkId); + + if (ipcClientProxy_->SendRequest(GET_UUID_BY_NETWORK, req, rsp) != DM_OK) { + return DM_IPC_SEND_REQUEST_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("CheckAuthentication Failed with ret %d", ret); + return ret; + } + uuid = rsp->GetUuid(); + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/ipc_client_proxy.cpp b/interfaces/inner_kits/native_cpp/src/ipc/ipc_client_proxy.cpp index 77cf6559d..57fd0e97b 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/ipc_client_proxy.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/ipc_client_proxy.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,23 +15,23 @@ #include "ipc_client_proxy.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { -int32_t IpcClientProxy::Init(std::string &pkgName) +int32_t IpcClientProxy::Init(const std::string &pkgName) { if (ipcClientManager_ == nullptr) { - return DEVICEMANAGER_NULLPTR; + return DM_POINT_NULL; } return ipcClientManager_->Init(pkgName); } -int32_t IpcClientProxy::UnInit(std::string &pkgName) +int32_t IpcClientProxy::UnInit(const std::string &pkgName) { if (ipcClientManager_ == nullptr) { - return DEVICEMANAGER_NULLPTR; + return DM_POINT_NULL; } return ipcClientManager_->UnInit(pkgName); } @@ -39,8 +39,8 @@ int32_t IpcClientProxy::UnInit(std::string &pkgName) int32_t IpcClientProxy::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { if (req == nullptr || rsp == nullptr || ipcClientManager_ == nullptr) { - DMLOG(DM_LOG_INFO, "req,rsp or ipc client is null"); - return DEVICEMANAGER_NULLPTR; + LOGI("req,rsp or ipc client is null"); + return DM_POINT_NULL; } return ipcClientManager_->SendRequest(cmdCode, req, rsp); } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp index 26551b435..0b1a27788 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,27 +15,26 @@ #include "ipc_client_manager.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" - +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_client_stub.h" #include "ipc_register_listener_req.h" namespace OHOS { namespace DistributedHardware { -int32_t IpcClientManager::Init(std::string &pkgName) +int32_t IpcClientManager::Init(const std::string &pkgName) { if (IsInit(pkgName)) { - DMLOG(DM_LOG_INFO, "already init"); - return DEVICEMANAGER_OK; + LOGI("already init"); + return DM_OK; } - if (serverProxy_.Init() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "server proxy init failed."); - return DEVICEMANAGER_INIT_FAILED; + if (serverProxy_.Init() != DM_OK) { + LOGE("server proxy init failed."); + return DM_INIT_FAILED; } - if (IpcClientStub::GetInstance().Init() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "ipcclientstub init failed."); - return DEVICEMANAGER_INIT_FAILED; + if (IpcClientStub::GetInstance().Init() != DM_OK) { + LOGE("ipcclientstub init failed."); + return DM_INIT_FAILED; } std::shared_ptr req = std::make_shared(); @@ -43,48 +42,48 @@ int32_t IpcClientManager::Init(std::string &pkgName) req->SetPkgName(pkgName); req->SetSvcIdentity(IpcClientStub::GetInstance().GetSvcIdentity()); int32_t ret = serverProxy_.SendCmd(REGISTER_DEVICE_MANAGER_LISTENER, req, rsp); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); + if (ret != DM_OK) { + LOGE("InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); return ret; } ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "DeviceManager::InitDeviceManager completed, pkgName: %s, ret=%d", pkgName.c_str(), ret); + if (ret != DM_OK) { + LOGE("DeviceManager::InitDeviceManager completed, pkgName: %s, ret=%d", pkgName.c_str(), ret); return ret; } packageInitSet_.emplace(pkgName); - return DEVICEMANAGER_OK; + return DM_OK; } -int32_t IpcClientManager::UnInit(std::string &pkgName) +int32_t IpcClientManager::UnInit(const std::string &pkgName) { - DMLOG(DM_LOG_INFO, "UnInitDeviceManager in, pkgName %s", pkgName.c_str()); + LOGI("UnInitDeviceManager in, pkgName %s", pkgName.c_str()); if (!IsInit(pkgName)) { - return DEVICEMANAGER_FAILED; + return DM_FAILED; } std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); int32_t ret = serverProxy_.SendCmd(UNREGISTER_DEVICE_MANAGER_LISTENER, req, rsp); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); + if (ret != DM_OK) { + LOGE("UnRegisterDeviceManagerListener Failed with ret %d", ret); return ret; } packageInitSet_.erase(pkgName); - DMLOG(DM_LOG_INFO, "UnInitDeviceManager SUCCESS"); - return DEVICEMANAGER_OK; + LOGI("UnInitDeviceManager SUCCESS"); + return DM_OK; } int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { std::string pkgName = req->GetPkgName(); if (!IsInit(pkgName)) { - return DEVICEMANAGER_SERVICE_NOT_READY; + return DM_SERVICE_NOT_READY; } return serverProxy_.SendCmd(cmdCode, req, rsp); } -bool IpcClientManager::IsInit(std::string &pkgName) +bool IpcClientManager::IsInit(const std::string &pkgName) { return (packageInitSet_.count(pkgName) > 0); } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_server_proxy.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_server_proxy.cpp index bfac66bf3..bf2f2b670 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_server_proxy.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_server_proxy.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,17 +15,16 @@ #include "ipc_client_server_proxy.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" #include "device_manager_notify.h" - -#include "ipc_def.h" +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_cmd_register.h" +#include "ipc_def.h" namespace OHOS { namespace DistributedHardware { namespace { - const int32_t INVALID_CB_ID = 0xFF; +const int32_t INVALID_CB_ID = 0xFF; } static uint32_t g_deathCbId = INVALID_CB_ID; static SvcIdentity g_svcIdentity; @@ -43,23 +42,23 @@ int32_t DMDeathCallback(const IpcContext *ctx, void *ipcMsg, IpcIo *data, void * (void)ipcMsg; (void)data; (void)arg; - DMLOG(DM_LOG_INFO, "ATTENTION SERVICE (%s) DEAD !!!\n", DEVICE_MANAGER_SERVICE_NAME); + LOGI("ATTENTION SERVICE (%s) DEAD !!!\n", DEVICE_MANAGER_SERVICE_NAME); UnregisterDeathCallback(g_svcIdentity, g_deathCbId); g_deathCbId = INVALID_CB_ID; g_svcIdentity.handle = 0; g_svcIdentity.token = 0; g_svcIdentity.cookie = 0; DeviceManagerNotify::GetInstance().OnRemoteDied(); - return DEVICEMANAGER_OK; + return DM_OK; } static int32_t SendCmdResultCb(IOwner owner, int32_t code, IpcIo *reply) { (void)code; int32_t cmdCode = *(int32_t *)owner; - DMLOG(DM_LOG_INFO, "SendCmdResultCb code:%d", cmdCode); + LOGI("SendCmdResultCb code:%d", cmdCode); (void)IpcCmdRegister::GetInstance().ReadResponse(cmdCode, *reply, pCurRsp); - return DEVICEMANAGER_OK; + return DM_OK; } IClientProxy *IpcClientServerProxy::GetServerProxy(void) @@ -67,14 +66,14 @@ IClientProxy *IpcClientServerProxy::GetServerProxy(void) IClientProxy *clientProxy = nullptr; IUnknown *iUnknown = nullptr; - DMLOG(DM_LOG_INFO, "start get client proxy"); + LOGI("start get client proxy"); iUnknown = SAMGR_GetInstance()->GetDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME); if (iUnknown == nullptr) { return nullptr; } - if (iUnknown->QueryInterface(iUnknown, CLIENT_PROXY_VER, (void **)&clientProxy) != DEVICEMANAGER_OK || + if (iUnknown->QueryInterface(iUnknown, CLIENT_PROXY_VER, (void **)&clientProxy) != DM_OK || clientProxy == nullptr) { - DMLOG(DM_LOG_ERROR, "QueryInterface failed"); + LOGE("QueryInterface failed"); } return clientProxy; } @@ -84,52 +83,52 @@ int IpcClientServerProxy::RegisterServerDeathCb(void) g_svcIdentity = SAMGR_GetRemoteIdentity(DEVICE_MANAGER_SERVICE_NAME, nullptr); g_deathCbId = INVALID_CB_ID; if (RegisterDeathCallback(nullptr, g_svcIdentity, DMDeathCallback, nullptr, &g_deathCbId) != EC_SUCCESS) { - DMLOG(DM_LOG_ERROR, "reg death callback failed"); - return DEVICEMANAGER_FAILED; + LOGE("reg death callback failed"); + return DM_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - DMLOG(DM_LOG_INFO, "SendCmd:%d", cmdCode); + LOGI("SendCmd:%d", cmdCode); uint8_t data[MAX_DM_IPC_LEN] = {0}; IpcIo request; - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, request, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_FAILED; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, request, data, MAX_DM_IPC_LEN) != DM_OK) { + return DM_FAILED; } { std::lock_guard autoLock(lock_); pCurRsp = rsp; if (serviceProxy_ != nullptr && serviceProxy_->Invoke(serviceProxy_, cmdCode, &request, &cmdCode, SendCmdResultCb) != 0) { - DMLOG(DM_LOG_ERROR, "serviceProxy_ invoke failed."); - return DEVICEMANAGER_FAILED; + LOGE("serviceProxy_ invoke failed."); + return DM_FAILED; } } - DMLOG(DM_LOG_INFO, "SendCmd:%d end", cmdCode); - return DEVICEMANAGER_OK; + LOGI("SendCmd:%d end", cmdCode); + return DM_OK; } int32_t IpcClientServerProxy::Init(void) { if (serviceProxy_ != nullptr) { - DMLOG(DM_LOG_INFO, "ServerProxy already Init"); - return DEVICEMANAGER_OK; + LOGI("ServerProxy already Init"); + return DM_OK; } HOS_SystemInit(); serviceProxy_ = GetServerProxy(); if (serviceProxy_ == nullptr) { - DMLOG(DM_LOG_ERROR, "get ipc client proxy failed"); - return DEVICEMANAGER_FAILED; + LOGE("get ipc client proxy failed"); + return DM_FAILED; } - if (RegisterServerDeathCb() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "register server death cb failed"); - return DEVICEMANAGER_FAILED; + if (RegisterServerDeathCb() != DM_OK) { + LOGE("register server death cb failed"); + return DM_FAILED; } - DMLOG(DM_LOG_INFO, "ServerProxyInit ok"); - return DEVICEMANAGER_OK; + LOGI("ServerProxyInit ok"); + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_stub.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_stub.cpp index 2726d7ee3..36132ab8b 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_stub.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_stub.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,12 +15,11 @@ #include "ipc_client_stub.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" #include "device_manager_notify.h" - -#include "ipc_def.h" +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_cmd_register.h" +#include "ipc_def.h" namespace OHOS { namespace DistributedHardware { @@ -30,16 +29,16 @@ static int32_t ClientIpcInterfaceMsgHandle(const IpcContext *ctx, void *ipcMsg, { (void)arg; if (ipcMsg == nullptr || io == nullptr) { - DMLOG(DM_LOG_ERROR, "invalid param"); - return DEVICEMANAGER_INVALID_PARAM; + LOGE("invalid param"); + return DM_INPUT_PARA_EMPTY; } uint32_t code = 0; GetCode(ipcMsg, &code); - int32_t errCode = DEVICEMANAGER_OK; + int32_t errCode = DM_OK; errCode = IpcCmdRegister::GetInstance().OnIpcCmd(code, *io); - DMLOG(DM_LOG_INFO, "receive ipc transact code:%u, retCode=%d", code, errCode); + LOGI("receive ipc transact code:%u, retCode=%d", code, errCode); FreeBuffer(ctx, ipcMsg); return errCode; } @@ -48,14 +47,14 @@ int32_t IpcClientStub::Init() { std::lock_guard autoLock(lock_); if (bInit) { - return DEVICEMANAGER_OK; + return DM_OK; } if (RegisterIpcCallback(ClientIpcInterfaceMsgHandle, 0, IPC_WAIT_FOREVER, &clientIdentity_, nullptr) != 0) { - DMLOG(DM_LOG_ERROR, "register ipc cb failed"); - return DEVICEMANAGER_FAILED; + LOGE("register ipc cb failed"); + return DM_FAILED; } bInit = true; - return DEVICEMANAGER_OK; + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp index bd67cd215..82226e953 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,32 +13,27 @@ * limitations under the License. */ -#include "ipc_cmd_register.h" -#include "ipc_def.h" - -#include "securec.h" -#include "constants.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" #include "device_manager_notify.h" - +#include "dm_constants.h" #include "dm_device_info.h" +#include "dm_log.h" #include "dm_subscribe_info.h" - +#include "ipc_authenticate_device_req.h" +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_get_local_device_info_rsp.h" +#include "ipc_get_trustdevice_req.h" +#include "ipc_get_trustdevice_rsp.h" #include "ipc_register_listener_req.h" #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.h" -#include "ipc_get_trustdevice_req.h" -#include "ipc_get_trustdevice_rsp.h" -#include "ipc_authenticate_device_req.h" -#include "ipc_check_authenticate_req.h" -#include "ipc_get_authenticationparam_rsp.h" -#include "ipc_set_useroperation_req.h" +#include "ipc_verify_authenticate_req.h" +#include "securec.h" namespace OHOS { namespace DistributedHardware { -ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); @@ -47,47 +42,47 @@ ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBa IpcIoInit(&request, buffer, buffLen, 1); IpcIoPushString(&request, pkgName.c_str()); IpcIoPushSvc(&request, &svcIdentity); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(REGISTER_DEVICE_MANAGER_LISTENER, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) + uint8_t *buffer, size_t buffLen) { std::string pkgName = pBaseReq->GetPkgName(); IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, pkgName.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } -ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) { - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string extra = pReq->GetExtra(); IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, pkgName.c_str()); IpcIoPushString(&request, extra.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptr pBaseRsp) { - std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); int32_t deviceNum = IpcIoPopInt32(&reply); uint32_t deviceTotalSize = deviceNum * (int32_t)sizeof(DmDeviceInfo); @@ -95,9 +90,9 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptr deviceInfoVec; DmDeviceInfo *pDmDeviceinfo = (DmDeviceInfo *)IpcIoPopFlatObj(&reply, &deviceTotalSize); if (pDmDeviceinfo == nullptr) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList read node info failed!"); - pRsp->SetErrCode(DEVICEMANAGER_IPC_TRANSACTION_FAILED); - return DEVICEMANAGER_IPC_TRANSACTION_FAILED; + LOGE("GetTrustedDeviceList read node info failed!"); + pRsp->SetErrCode(DM_IPC_TRANSACTION_FAILED); + return DM_IPC_TRANSACTION_FAILED; } for (int32_t i = 0; i < deviceNum; ++i) { pDmDeviceinfo = pDmDeviceinfo + i; @@ -106,30 +101,52 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptrSetDeviceVec(deviceInfoVec); } pRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; +} + +ON_IPC_SET_REQUEST(GET_LOCAL_DEVICE_INFO, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + IpcIoInit(&request, buffer, buffLen, 0); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + + uint32_t size = 0; + DmDeviceInfo *dmDeviceInfo = (DmDeviceInfo *)IpcIoPopFlatObj(&reply, &size); + if (dmDeviceInfo != nullptr) { + pRsp->SetLocalDeviceInfo(*dmDeviceInfo); + } + pRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; } -ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushString(&request, extra.c_str()); IpcIoPushFlatObj(&request, &dmSubscribeInfo, sizeof(DmSubscribeInfo)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } -ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); @@ -138,21 +155,21 @@ ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, pkgName.c_str()); IpcIoPushUint16(&request, subscribeId); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } -ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); - std::string extra = pReq->GetExtra(); + std::string extra = pReq->GetExtra(); DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); IpcIoInit(&request, buffer, buffLen, 0); @@ -160,30 +177,49 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, IpcIo IpcIoPushString(&request, extra.c_str()); IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); // L1 暂时没有考虑appimage校验(8k限制) - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } -ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +ON_IPC_SET_REQUEST(VERIFY_AUTHENTICATION, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) { - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string authPara = pReq->GetAuthPara(); IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, authPara.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } -ON_IPC_READ_RESPONSE(CHECK_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_USER_AUTH_OPERATION, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t action = pReq->GetOperation(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushInt32(&request, action); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_USER_AUTH_OPERATION, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; } ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply) @@ -192,9 +228,9 @@ ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply) std::string pkgName = (const char *)IpcIoPopString(&reply, &len); DmDeviceState deviceState = static_cast(IpcIoPopInt32(&reply)); uint32_t size; - const DmDeviceInfo *deviceInfo = (const DmDeviceInfo*)IpcIoPopFlatObj(&reply, &size); + const DmDeviceInfo *deviceInfo = (const DmDeviceInfo *)IpcIoPopFlatObj(&reply, &size); if (pkgName == "" || len == 0 || deviceInfo == NULL) { - DMLOG(DM_LOG_ERROR, "OnDeviceOnline, get para failed"); + LOGE("OnDeviceOnline, get para failed"); return; } switch (deviceState) { @@ -208,7 +244,7 @@ ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply) DeviceManagerNotify::GetInstance().OnDeviceChanged(pkgName, *deviceInfo); break; default: - DMLOG(DM_LOG_ERROR, "unknown device state:%d", deviceState); + LOGE("unknown device state:%d", deviceState); break; } } @@ -219,9 +255,9 @@ ON_IPC_CMD(SERVER_DEVICE_FOUND, IpcIo &reply) std::string pkgName = (const char *)IpcIoPopString(&reply, &len); uint16_t subscribeId = IpcIoPopUint16(&reply); uint32_t size; - const DmDeviceInfo *deviceInfo = (const DmDeviceInfo*)IpcIoPopFlatObj(&reply, &size); + const DmDeviceInfo *deviceInfo = (const DmDeviceInfo *)IpcIoPopFlatObj(&reply, &size); if (pkgName == "" || len == 0 || deviceInfo == NULL) { - DMLOG(DM_LOG_ERROR, "OnDeviceChanged, get para failed"); + LOGE("OnDeviceChanged, get para failed"); return; } DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, *deviceInfo); @@ -235,13 +271,13 @@ ON_IPC_CMD(SERVER_DISCOVER_FINISH, IpcIo &reply) int32_t failedReason = IpcIoPopInt32(&reply); if (pkgName == "" || len == 0) { - DMLOG(DM_LOG_ERROR, "OnDiscoverySuccess, get para failed"); + LOGE("OnDiscoverySuccess, get para failed"); return; } - if (failedReason == DEVICEMANAGER_OK) { + if (failedReason == DM_OK) { DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); } else { - DeviceManagerNotify::GetInstance().OnDiscoverFailed(pkgName, subscribeId, failedReason); + DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); } } @@ -251,18 +287,18 @@ ON_IPC_CMD(SERVER_AUTH_RESULT, IpcIo &reply) std::string pkgName = (const char *)IpcIoPopString(&reply, &len); size_t devIdLen = 0; std::string deviceId = (const char *)IpcIoPopString(&reply, &devIdLen); - int32_t pinToken = IpcIoPopInt32(&reply); + // int32_t pinToken = IpcIoPopInt32(&reply); int32_t status = IpcIoPopInt32(&reply); int32_t reason = IpcIoPopInt32(&reply); if (pkgName == "" || len == 0 || deviceId == "" || devIdLen == 0) { - DMLOG(DM_LOG_ERROR, "OnAuthResult, get para failed"); + LOGE("OnAuthResult, get para failed"); return; } - DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, pinToken, status, reason); + DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, nullptr, status, reason); } -ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, IpcIo &reply) +ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply) { size_t len = 0; std::string pkgName = (const char *)IpcIoPopString(&reply, &len); @@ -272,80 +308,13 @@ ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, IpcIo &reply) int32_t flag = IpcIoPopInt32(&reply); if (pkgName == "" || len == 0 || deviceId == "" || devIdLen == 0) { - DMLOG(DM_LOG_ERROR, "OnAuthResult, get para failed"); + LOGE("OnAuthResult, get para failed"); return; } - DeviceManagerNotify::GetInstance().OnCheckAuthResult(pkgName, deviceId, resultCode, flag); -} - -ON_IPC_SET_REQUEST(SERVER_GET_AUTHENTCATION_INFO, std::shared_ptr pBaseReq, IpcIo& request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string packagename = pReq->GetPkgName(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, packagename.c_str()); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, IpcIo& reply, std::shared_ptr pBaseRsp) -{ - std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); - DmAuthParam authParam = {0}; - authParam.direction = IpcIoPopInt32(&reply); - authParam.authType = IpcIoPopInt32(&reply); - if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - authParam.pinToken = IpcIoPopInt32(&reply); - pRsp->SetAuthParam(authParam); - return DEVICEMANAGER_OK; - } - size_t PackagerNamelen = 0; - authParam.packageName = strdup((const char *)IpcIoPopString(&reply, &PackagerNamelen)); - size_t appNameLen = 0; - authParam.appName = strdup((const char *)IpcIoPopString(&reply, &appNameLen)); - size_t appDesLen = 0; - authParam.appDescription = strdup((const char *)IpcIoPopString(&reply, &appDesLen)); - authParam.business = IpcIoPopInt32(&reply); - authParam.pincode = IpcIoPopInt32(&reply); - - uint32_t appIconLen = IpcIoPopInt32(&reply); - uint8_t *appIconBuffer = nullptr; - uint32_t appThumbnailLen = IpcIoPopInt32(&reply); - uint8_t *appThumbBuffer = nullptr; - - if (appIconLen > 0) { - appIconBuffer = (uint8_t *)IpcIoPopFlatObj(&reply, &appIconLen); - } - if (appThumbnailLen > 0) { - appThumbBuffer = (uint8_t *)IpcIoPopFlatObj(&reply, &appThumbnailLen); - } - - authParam.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); - pRsp->SetAuthParam(authParam); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr pBaseReq, IpcIo& request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName= pReq->GetPkgName(); - int32_t action = pReq->GetOperation(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, pkgName.c_str()); - IpcIoPushInt32(&request, action); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + DeviceManagerNotify::GetInstance().OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); } -ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) +ON_IPC_CMD(SERVER_DEVICE_FA_NOTIFY, IpcIo &reply) { size_t len = 0; std::string packagename = (const char *)IpcIoPopString(&reply, &len); diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 26d9fb927..b2b58f1f0 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,68 +15,67 @@ #include "ipc_client_manager.h" +#include "device_manager_notify.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_client_stub.h" +#include "ipc_register_listener_req.h" #include "ipc_remote_broker.h" #include "iremote_object.h" #include "iservice_registry.h" #include "system_ability_definition.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "device_manager_notify.h" - -#include "ipc_register_listener_req.h" - namespace OHOS { namespace DistributedHardware { void DmDeathRecipient::OnRemoteDied(const wptr &remote) { (void)remote; - DMLOG(DM_LOG_WARN, "DmDeathRecipient : OnRemoteDied"); + LOGW("DmDeathRecipient : OnRemoteDied"); DeviceManagerNotify::GetInstance().OnRemoteDied(); } int32_t IpcClientManager::ClientInit() { - DMLOG(DM_LOG_INFO, "InitDeviceManagerService start"); + LOGI("InitDeviceManagerService start"); if (dmInterface_ != nullptr) { - DMLOG(DM_LOG_INFO, "DeviceManagerService Already Init"); - return DEVICEMANAGER_OK; + LOGI("DeviceManagerService Already Init"); + return DM_OK; } auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { - DMLOG(DM_LOG_ERROR, "Get SystemAbilityManager Failed"); - return DEVICEMANAGER_SERVICE_NOT_READY; + LOGE("Get SystemAbilityManager Failed"); + return DM_SERVICE_NOT_READY; } auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); if (object == nullptr) { - DMLOG(DM_LOG_ERROR, "Get DeviceManager SystemAbility Failed"); - return DEVICEMANAGER_SERVICE_NOT_READY; + LOGE("Get DeviceManager SystemAbility Failed"); + return DM_SERVICE_NOT_READY; } if (dmRecipient_ == nullptr) { dmRecipient_ = sptr(new DmDeathRecipient()); } if (!object->AddDeathRecipient(dmRecipient_)) { - DMLOG(DM_LOG_ERROR, "InitDeviceManagerService: AddDeathRecipient Failed"); + LOGE("InitDeviceManagerService: AddDeathRecipient Failed"); } dmInterface_ = iface_cast(object); - DMLOG(DM_LOG_INFO, "DeviceManager::InitDeviceManagerService completed"); - return DEVICEMANAGER_OK; + LOGI("DeviceManager::InitDeviceManagerService completed"); + return DM_OK; } -int32_t IpcClientManager::Init(std::string &pkgName) +int32_t IpcClientManager::Init(const std::string &pkgName) { std::lock_guard autoLock(lock_); int32_t ret = ClientInit(); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager Failed with ret %d", ret); + if (ret != DM_OK) { + LOGE("InitDeviceManager Failed with ret %d", ret); return ret; } if (dmListener_.count(pkgName) > 0) { - DMLOG(DM_LOG_INFO, "dmListener_ Already Init"); - return DEVICEMANAGER_OK; + LOGI("dmListener_ Already Init"); + return DM_OK; } sptr listener = sptr(new IpcClientStub()); @@ -85,25 +84,25 @@ int32_t IpcClientManager::Init(std::string &pkgName) req->SetPkgName(pkgName); req->SetListener(listener); ret = dmInterface_->SendCmd(REGISTER_DEVICE_MANAGER_LISTENER, req, rsp); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); + if (ret != DM_OK) { + LOGE("InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); return ret; } ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { return ret; } dmListener_[pkgName] = listener; - DMLOG(DM_LOG_INFO, "completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + LOGI("completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } -int32_t IpcClientManager::UnInit(std::string &pkgName) +int32_t IpcClientManager::UnInit(const std::string &pkgName) { - DMLOG(DM_LOG_INFO, "in, pkgName %s", pkgName.c_str()); + LOGI("in, pkgName %s", pkgName.c_str()); if (dmInterface_ == nullptr) { - DMLOG(DM_LOG_ERROR, "DeviceManager not Init"); - return DEVICEMANAGER_SERVICE_NOT_READY; + LOGE("DeviceManager not Init"); + return DM_SERVICE_NOT_READY; } std::lock_guard autoLock(lock_); @@ -112,8 +111,8 @@ int32_t IpcClientManager::UnInit(std::string &pkgName) std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); int32_t ret = dmInterface_->SendCmd(UNREGISTER_DEVICE_MANAGER_LISTENER, req, rsp); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); + if (ret != DM_OK) { + LOGE("UnRegisterDeviceManagerListener Failed with ret %d", ret); return ret; } dmListener_.erase(pkgName); @@ -122,28 +121,30 @@ int32_t IpcClientManager::UnInit(std::string &pkgName) dmInterface_ = nullptr; dmRecipient_ = nullptr; } - DMLOG(DM_LOG_INFO, "completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + LOGI("completed, pkgName: %s", pkgName.c_str()); + return DM_OK; } int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { + LOGI("IpcClientManager::SendRequest in"); std::string pkgName = req->GetPkgName(); if (!IsInit(pkgName)) { - return DEVICEMANAGER_SERVICE_NOT_READY; + LOGE("IpcClientManager::SendRequest DM_SERVICE_NOT_READY"); + return DM_SERVICE_NOT_READY; } return dmInterface_->SendCmd(cmdCode, req, rsp); } -bool IpcClientManager::IsInit(std::string &pkgName) +bool IpcClientManager::IsInit(const std::string &pkgName) { if (dmInterface_ == nullptr) { - DMLOG(DM_LOG_ERROR, "DeviceManager not Init"); + LOGE("DeviceManager not Init"); return false; } std::lock_guard autoLock(lock_); if (dmListener_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "dmListener_ not Init for %s", pkgName.c_str()); + LOGE("dmListener_ not Init for %s", pkgName.c_str()); return false; } return true; diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp index 75d0d1923..0a8e93040 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,31 +15,30 @@ #include "ipc_client_server_proxy.h" +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_cmd_register.h" #include "ipc_types.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" - namespace OHOS { namespace DistributedHardware { int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { sptr remote = Remote(); if (remote == nullptr) { - DMLOG(DM_LOG_ERROR, "remote service null"); - return DEVICEMANAGER_NULLPTR; + LOGE("remote service null"); + return DM_POINT_NULL; } MessageParcel data; MessageParcel reply; MessageOption option; - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_FAILED; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) { + return DM_IPC_SEND_REQUEST_FAILED; } - if (remote->SendRequest(cmdCode, data, reply, option) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); - return DEVICEMANAGER_IPC_FAILED; + if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { + LOGE("SendRequest fail, cmd:%d", cmdCode); + return DM_IPC_SEND_REQUEST_FAILED; } return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp index cbe30dd5b..748da1c82 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,31 +15,28 @@ #include "ipc_client_stub.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_cmd_register.h" #include "ipc_skeleton.h" #include "ipc_types.h" -#include "ipc_cmd_register.h" - -#include "device_manager_log.h" -#include "device_manager_errno.h" - namespace OHOS { namespace DistributedHardware { -int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, - MessageOption &option) +int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - DMLOG(DM_LOG_INFO, "code = %d, flags= %d.", code, option.GetFlags()); - if (IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply) == DEVICEMANAGER_OK) { - return DEVICEMANAGER_OK; + LOGI("code = %d, flags= %d.", code, option.GetFlags()); + if (IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply) == DM_OK) { + return DM_OK; } - DMLOG(DM_LOG_WARN, "unsupport code: %d", code); + LOGW("unsupport code: %d", code); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } int32_t IpcClientStub::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - DMLOG(DM_LOG_ERROR, "error"); - return DEVICEMANAGER_OK; + LOGE("error"); + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index 45b3f02a9..644701c10 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,24 +13,28 @@ * limitations under the License. */ -#include "ipc_cmd_register.h" - -#include "securec.h" -#include "constants.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" #include "device_manager_notify.h" - +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "ipc_authenticate_device_req.h" +#include "ipc_cmd_register.h" #include "ipc_def.h" -#include "ipc_register_listener_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" +#include "ipc_get_dmfaparam_rsp.h" +#include "ipc_get_info_by_network_req.h" +#include "ipc_get_info_by_network_rsp.h" +#include "ipc_get_local_device_info_rsp.h" #include "ipc_get_trustdevice_req.h" #include "ipc_get_trustdevice_rsp.h" -#include "ipc_authenticate_device_req.h" -#include "ipc_check_authenticate_req.h" -#include "ipc_get_authenticationparam_rsp.h" +#include "ipc_register_listener_req.h" +#include "ipc_req.h" +#include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" +#include "ipc_start_discovery_req.h" +#include "ipc_stop_discovery_req.h" +#include "ipc_unauthenticate_device_req.h" +#include "ipc_verify_authenticate_req.h" +#include "securec.h" namespace OHOS { namespace DistributedHardware { @@ -40,75 +44,141 @@ ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBa std::string pkgName = pReq->GetPkgName(); sptr listener = pReq->GetListener(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write pkgName failed"); + return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteRemoteObject(listener)) { - DMLOG(DM_LOG_ERROR, "write listener failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write listener failed"); + return DM_IPC_TRANSACTION_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, MessageParcel &data) { std::string pkgName = pBaseReq->GetPkgName(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write papam failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write papam failed"); + return DM_IPC_TRANSACTION_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, MessageParcel &data) { - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string extra = pReq->GetExtra(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkg failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write pkg failed"); + return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteString(extra)) { - DMLOG(DM_LOG_ERROR, "write extra failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write extra failed"); + return DM_IPC_TRANSACTION_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, MessageParcel &reply, std::shared_ptr pBaseRsp) { - std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); int32_t deviceNum = reply.ReadInt32(); - int32_t deviceTotalSize = deviceNum * (int32_t)sizeof(DmDeviceInfo); - if (deviceTotalSize > 0) { + if (deviceNum > 0) { std::vector deviceInfoVec; - DmDeviceInfo *pDmDeviceinfo = (DmDeviceInfo *)reply.ReadRawData(deviceTotalSize); - if (pDmDeviceinfo == nullptr) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList read node info failed!"); - pRsp->SetErrCode(DEVICEMANAGER_IPC_TRANSACTION_FAILED); - return DEVICEMANAGER_IPC_TRANSACTION_FAILED; - } + DmDeviceInfo *pDmDeviceinfo = nullptr; for (int32_t i = 0; i < deviceNum; ++i) { - pDmDeviceinfo = pDmDeviceinfo + i; + pDmDeviceinfo = nullptr; + pDmDeviceinfo = (DmDeviceInfo *)reply.ReadRawData((int32_t)sizeof(DmDeviceInfo)); + if (pDmDeviceinfo == nullptr) { + LOGE("GetTrustedDeviceList read node info failed!"); + pRsp->SetErrCode(DM_IPC_TRANSACTION_FAILED); + return DM_IPC_TRANSACTION_FAILED; + } deviceInfoVec.emplace_back(*pDmDeviceinfo); } pRsp->SetDeviceVec(deviceInfoVec); } pRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; +} + +ON_IPC_SET_REQUEST(GET_LOCAL_DEVICE_INFO, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + DmDeviceInfo *localDeviceInfo = (DmDeviceInfo *)reply.ReadRawData(sizeof(DmDeviceInfo)); + if (localDeviceInfo == nullptr) { + LOGE("write subscribe info failed"); + } + pRsp->SetLocalDeviceInfo(*localDeviceInfo); + pRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(GET_UDID_BY_NETWORK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string netWorkId = pReq->GetNetWorkId(); + if (!data.WriteString(pkgName)) { + return DM_FLATTEN_OBJECT; + } + if (!data.WriteString(netWorkId)) { + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_UDID_BY_NETWORK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + pRsp->SetUdid(reply.ReadString()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(GET_UUID_BY_NETWORK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string netWorkId = pReq->GetNetWorkId(); + if (!data.WriteString(pkgName)) { + return DM_FLATTEN_OBJECT; + } + if (!data.WriteString(netWorkId)) { + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_UUID_BY_NETWORK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + pRsp->SetUuid(reply.ReadString()); + return DM_OK; } ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) @@ -117,20 +187,20 @@ ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, Mess std::string pkgName = pReq->GetPkgName(); const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write pkgName failed"); + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo))) { - DMLOG(DM_LOG_ERROR, "write subscribe info failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write subscribe info failed"); + return DM_IPC_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) @@ -139,83 +209,145 @@ ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, Messa std::string pkgName = pReq->GetPkgName(); uint16_t subscribeId = pReq->GetSubscribeId(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write pkgName failed"); + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteInt16(subscribeId)) { - DMLOG(DM_LOG_ERROR, "write subscribeId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write subscribeId failed"); + return DM_IPC_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, MessageParcel &data) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); - std::string extra = pReq->GetExtra(); + std::string extra = pReq->GetExtra(); + int32_t authType = pReq->GetAuthType(); DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); - DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); + std::string deviceId = deviceInfo.deviceId; + // DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write pkgName failed"); + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteString(extra)) { - DMLOG(DM_LOG_ERROR, "write extra failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { - DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + LOGE("write extra failed"); + return DM_IPC_FLATTEN_OBJECT; } - int32_t appIconLen = imageInfo.GetAppIconLen(); - int32_t appThumbnailLen = imageInfo.GetAppThumbnailLen(); - if (!data.WriteInt32(appIconLen)) { - DMLOG(DM_LOG_ERROR, "write imageinfo appicon len failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + if (!data.WriteString(deviceId)) { + LOGE("write extra failed"); + return DM_IPC_FLATTEN_OBJECT; } - if (!data.WriteInt32(appThumbnailLen)) { - DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnailLen failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + if (!data.WriteInt32(authType)) { + LOGE("write pkgName failed"); + return DM_IPC_FLATTEN_OBJECT; } - if (appIconLen > 0 && !data.WriteRawData(imageInfo.GetAppIcon(), appIconLen)) { - DMLOG(DM_LOG_ERROR, "write imageinfo appIcon failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_OK; +} + +ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(UNAUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + std::string deviceId = deviceInfo.deviceId; + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_IPC_FLATTEN_OBJECT; } - if (appThumbnailLen > 0 && !data.WriteRawData(imageInfo.GetAppThumbnail(), appThumbnailLen)) { - DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnail failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + if (!data.WriteString(deviceId)) { + LOGE("write extra failed"); + return DM_IPC_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } -ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(UNAUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } -ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, MessageParcel &data) +ON_IPC_SET_REQUEST(VERIFY_AUTHENTICATION, std::shared_ptr pBaseReq, MessageParcel &data) { - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string authPara = pReq->GetAuthPara(); if (!data.WriteString(authPara)) { - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_GET_DMFA_INFO, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagename = pReq->GetPkgName(); + if (!data.WriteString(packagename)) { + LOGE("write pkgName failed"); + return DM_IPC_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_GET_DMFA_INFO, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + DmAuthParam authParam; + authParam.direction = reply.ReadInt32(); + authParam.authType = reply.ReadInt32(); + authParam.authToken = reply.ReadString(); + authParam.packageName = reply.ReadString(); + authParam.appName = reply.ReadString(); + authParam.appDescription = reply.ReadString(); + authParam.business = reply.ReadInt32(); + authParam.pincode = reply.ReadInt32(); + pRsp->SetDmAuthParam(authParam); + return DM_OK; } -ON_IPC_READ_RESPONSE(CHECK_AUTHENTICATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +ON_IPC_SET_REQUEST(SERVER_USER_AUTH_OPERATION, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t action = pReq->GetOperation(); + + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_IPC_TRANSACTION_FAILED; + } + if (!data.WriteInt32(action)) { + LOGE("write action failed"); + return DM_WRITE_FAILED; + } + + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_USER_AUTH_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) @@ -226,8 +358,8 @@ ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply size_t deviceSize = sizeof(DmDeviceInfo); void *deviceInfo = (void *)data.ReadRawData(deviceSize); if (deviceInfo != nullptr && memcpy_s(&dmDeviceInfo, deviceSize, deviceInfo, deviceSize) != 0) { - reply.WriteInt32(DEVICEMANAGER_COPY_FAILED); - return DEVICEMANAGER_OK; + reply.WriteInt32(DM_IPC_COPY_FAILED); + return DM_OK; } switch (deviceState) { case DEVICE_STATE_ONLINE: @@ -239,12 +371,15 @@ ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply case DEVICE_INFO_CHANGED: DeviceManagerNotify::GetInstance().OnDeviceChanged(pkgName, dmDeviceInfo); break; + case DEVICE_INFO_READY: + DeviceManagerNotify::GetInstance().OnDeviceReady(pkgName, dmDeviceInfo); + break; default: - DMLOG(DM_LOG_ERROR, "unknown device state:%d", deviceState); + LOGE("unknown device state:%d", deviceState); break; } - reply.WriteInt32(DEVICEMANAGER_OK); - return DEVICEMANAGER_OK; + reply.WriteInt32(DM_OK); + return DM_OK; } ON_IPC_CMD(SERVER_DEVICE_FOUND, MessageParcel &data, MessageParcel &reply) @@ -255,12 +390,12 @@ ON_IPC_CMD(SERVER_DEVICE_FOUND, MessageParcel &data, MessageParcel &reply) size_t deviceSize = sizeof(DmDeviceInfo); void *deviceInfo = (void *)data.ReadRawData(deviceSize); if (deviceInfo != nullptr && memcpy_s(&dmDeviceInfo, deviceSize, deviceInfo, deviceSize) != 0) { - reply.WriteInt32(DEVICEMANAGER_COPY_FAILED); - return DEVICEMANAGER_OK; + reply.WriteInt32(DM_IPC_COPY_FAILED); + return DM_IPC_COPY_FAILED; } DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, dmDeviceInfo); - reply.WriteInt32(DEVICEMANAGER_OK); - return DEVICEMANAGER_OK; + reply.WriteInt32(DM_OK); + return DM_OK; } ON_IPC_CMD(SERVER_DISCOVER_FINISH, MessageParcel &data, MessageParcel &reply) @@ -269,122 +404,48 @@ ON_IPC_CMD(SERVER_DISCOVER_FINISH, MessageParcel &data, MessageParcel &reply) uint16_t subscribeId = data.ReadInt16(); int32_t failedReason = data.ReadInt32(); - if (failedReason == DEVICEMANAGER_OK) { + if (failedReason == DM_OK) { DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); } else { - DeviceManagerNotify::GetInstance().OnDiscoverFailed(pkgName, subscribeId, failedReason); + DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); } - reply.WriteInt32(DEVICEMANAGER_OK); - return DEVICEMANAGER_OK; + reply.WriteInt32(DM_OK); + return DM_OK; } ON_IPC_CMD(SERVER_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); std::string deviceId = data.ReadString(); - int32_t pinToken = data.ReadInt32(); + std::string token = data.ReadString(); int32_t status = data.ReadInt32(); int32_t reason = data.ReadInt32(); - - DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, pinToken, status, reason); - reply.WriteInt32(DEVICEMANAGER_OK); - return DEVICEMANAGER_OK; + DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, token, status, reason); + reply.WriteInt32(DM_OK); + return DM_OK; } -ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); std::string deviceId = data.ReadString(); int32_t resultCode = data.ReadInt32(); int32_t flag = data.ReadInt32(); - - DeviceManagerNotify::GetInstance().OnCheckAuthResult(pkgName, deviceId, resultCode, flag); - reply.WriteInt32(DEVICEMANAGER_OK); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_GET_AUTHENTCATION_INFO, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string packagename = pReq->GetPkgName(); - if (!data.WriteString(packagename)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); - DmAuthParam authParam; - authParam.direction = reply.ReadInt32(); - authParam.authType = reply.ReadInt32(); - if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - authParam.pinToken = reply.ReadInt32(); - pRsp->SetAuthParam(authParam); - return DEVICEMANAGER_OK; - } - - authParam.packageName = reply.ReadString(); - authParam.appName = reply.ReadString(); - authParam.appDescription = reply.ReadString(); - authParam.business = reply.ReadInt32(); - authParam.pincode = reply.ReadInt32(); - - int32_t appIconLen = reply.ReadInt32(); - uint8_t *appIconBuffer = nullptr; - int32_t appThumbnailLen = reply.ReadInt32(); - uint8_t *appThumbBuffer = nullptr; - if (appIconLen > 0) { - appIconBuffer = (uint8_t *)reply.ReadRawData(appIconLen); - } - if (appThumbnailLen > 0) { - appThumbBuffer = (uint8_t *)reply.ReadRawData(appThumbnailLen); - } - authParam.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); - pRsp->SetAuthParam(authParam); - return DEVICEMANAGER_OK; + DeviceManagerNotify::GetInstance().OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); + reply.WriteInt32(DM_OK); + return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr pBaseReq, MessageParcel &data) +ON_IPC_CMD(SERVER_DEVICE_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) { - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - int32_t action = pReq->GetOperation(); - - if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(action)) { - DMLOG(DM_LOG_ERROR, "write extra failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) -{ - DMLOG(DM_LOG_INFO, "OnFaCallBack"); std::string packagename = data.ReadString(); std::string paramJson = data.ReadString(); - DMLOG(DM_LOG_INFO, "OnFaCallBack Packagename is %s", packagename.c_str()); - DMLOG(DM_LOG_INFO, "OnFaCallBack Json is %s", paramJson.c_str()); DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); - - if (!reply.WriteInt32(DEVICEMANAGER_OK)) { - DMLOG(DM_LOG_ERROR, "write return failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + if (!reply.WriteInt32(DM_OK)) { + LOGE("write return failed"); + return DM_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 94f03d156..f1c36875e 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,65 +15,64 @@ #include "device_manager_notify.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" -#include "nlohmann/json.hpp" -#include "constants.h" #include "device_manager.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); -void DeviceManagerNotify::RegisterDeathRecipientCallback(std::string &pkgName, - std::shared_ptr dmInitCallback) +void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, + std::shared_ptr dmInitCallback) { std::lock_guard autoLock(lock_); dmInitCallback_[pkgName] = dmInitCallback; } -void DeviceManagerNotify::UnRegisterDeathRecipientCallback(std::string &pkgName) +void DeviceManagerNotify::UnRegisterDeathRecipientCallback(const std::string &pkgName) { std::lock_guard autoLock(lock_); dmInitCallback_.erase(pkgName); } -void DeviceManagerNotify::RegisterDeviceStateCallback(std::string &pkgName, - std::shared_ptr callback) +void DeviceManagerNotify::RegisterDeviceStateCallback(const std::string &pkgName, + std::shared_ptr callback) { std::lock_guard autoLock(lock_); deviceStateCallback_[pkgName] = callback; } -void DeviceManagerNotify::UnRegisterDeviceStateCallback(std::string &pkgName) +void DeviceManagerNotify::UnRegisterDeviceStateCallback(const std::string &pkgName) { std::lock_guard autoLock(lock_); deviceStateCallback_.erase(pkgName); } -void DeviceManagerNotify::RegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId, - std::shared_ptr callback) +void DeviceManagerNotify::RegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId, + std::shared_ptr callback) { std::lock_guard autoLock(lock_); - if (deviceDiscoverCallbacks_.count(pkgName) == 0) { - deviceDiscoverCallbacks_[pkgName] = std::map>(); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + deviceDiscoveryCallbacks_[pkgName] = std::map>(); } - deviceDiscoverCallbacks_[pkgName][subscribeId] = callback; + deviceDiscoveryCallbacks_[pkgName][subscribeId] = callback; } -void DeviceManagerNotify::UnRegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId) +void DeviceManagerNotify::UnRegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId) { std::lock_guard autoLock(lock_); - if (deviceDiscoverCallbacks_.count(pkgName) > 0) { - deviceDiscoverCallbacks_[pkgName].erase(subscribeId); - if (deviceDiscoverCallbacks_[pkgName].empty()) { - deviceDiscoverCallbacks_.erase(pkgName); + if (deviceDiscoveryCallbacks_.count(pkgName) > 0) { + deviceDiscoveryCallbacks_[pkgName].erase(subscribeId); + if (deviceDiscoveryCallbacks_[pkgName].empty()) { + deviceDiscoveryCallbacks_.erase(pkgName); } } } -void DeviceManagerNotify::RegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId, - std::shared_ptr callback) +void DeviceManagerNotify::RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback) { std::lock_guard autoLock(lock_); if (authenticateCallback_.count(pkgName) == 0) { @@ -82,7 +81,7 @@ void DeviceManagerNotify::RegisterAuthenticateCallback(std::string &pkgName, std authenticateCallback_[pkgName][deviceId] = callback; } -void DeviceManagerNotify::UnRegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId) +void DeviceManagerNotify::UnRegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId) { std::lock_guard autoLock(lock_); if (authenticateCallback_.count(pkgName) > 0) { @@ -93,185 +92,192 @@ void DeviceManagerNotify::UnRegisterAuthenticateCallback(std::string &pkgName, s } } -void DeviceManagerNotify::UnRegisterPackageCallback(std::string &pkgName) +void DeviceManagerNotify::UnRegisterPackageCallback(const std::string &pkgName) { std::lock_guard autoLock(lock_); deviceStateCallback_.erase(pkgName); - deviceDiscoverCallbacks_.erase(pkgName); + deviceDiscoveryCallbacks_.erase(pkgName); authenticateCallback_.erase(pkgName); dmInitCallback_.erase(pkgName); } -void DeviceManagerNotify::RegisterCheckAuthenticationCallback(std::string &pkgName, std::string &authPara, - std::shared_ptr callback) +void DeviceManagerNotify::RegisterVerifyAuthenticationCallback(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) { std::lock_guard autoLock(lock_); - checkauthcallback_[pkgName] = callback; + verifyAuthCallback_[pkgName] = callback; } -void DeviceManagerNotify::UnRegisterCheckAuthenticationCallback(std::string &pkgName) +void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::string &pkgName) { std::lock_guard autoLock(lock_); - checkauthcallback_.erase(pkgName); + verifyAuthCallback_.erase(pkgName); } -void DeviceManagerNotify::RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback) +void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) { std::lock_guard autoLock(lock_); - dmFaCallback_[packageName] = callback; + dmFaCallback_[pkgName] = callback; } -void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(std::string &pkgName) +void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) { std::lock_guard autoLock(lock_); + if (dmFaCallback_.count(pkgName) == 0) { + LOGE("DeviceManager UnRegisterDeviceManagerFaCallback not register"); + return; + } dmFaCallback_.erase(pkgName); } - void DeviceManagerNotify::OnRemoteDied() { - DMLOG(DM_LOG_WARN, "DeviceManager : OnRemoteDied"); + LOGW("DeviceManager : OnRemoteDied"); for (auto iter : dmInitCallback_) { iter.second->OnRemoteDied(); } } -void DeviceManagerNotify::OnDeviceOnline(std::string &pkgName, const DmDeviceInfo &deviceInfo) +void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDeviceOnline pkgName:%s", pkgName.c_str()); + LOGI("DeviceManager OnDeviceOnline pkgName:%s", pkgName.c_str()); std::lock_guard autoLock(lock_); if (deviceStateCallback_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceOnlinecallback not register"); + LOGE("DeviceManager OnDeviceOnlinecallback not register"); return; } deviceStateCallback_[pkgName]->OnDeviceOnline(deviceInfo); } -void DeviceManagerNotify::OnDeviceOffline(std::string &pkgName, const DmDeviceInfo &deviceInfo) +void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDeviceOffline pkgName:%s", pkgName.c_str()); + LOGI("DeviceManager OnDeviceOffline pkgName:%s", pkgName.c_str()); std::lock_guard autoLock(lock_); if (deviceStateCallback_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceOfflinecallback not register"); + LOGE("DeviceManager OnDeviceOfflinecallback not register"); return; } deviceStateCallback_[pkgName]->OnDeviceOffline(deviceInfo); } -void DeviceManagerNotify::OnDeviceChanged(std::string &pkgName, const DmDeviceInfo &deviceInfo) +void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDeviceChanged pkgName:%s", pkgName.c_str()); + LOGI("DeviceManager OnDeviceChanged pkgName:%s", pkgName.c_str()); std::lock_guard autoLock(lock_); if (deviceStateCallback_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceChangedcallback not register"); + LOGE("DeviceManager OnDeviceChangedcallback not register"); return; } deviceStateCallback_[pkgName]->OnDeviceChanged(deviceInfo); } -void DeviceManagerNotify::OnDeviceFound(std::string &pkgName, uint16_t subscribeId, - const DmDeviceInfo &deviceInfo) +void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceReady pkgName:%s", pkgName.c_str()); + std::lock_guard autoLock(lock_); + if (deviceStateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceReadycallback not register"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceReady(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, + const DmDeviceInfo &deviceInfo) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDeviceFound pkgName:%s, subscribeId:%d.", pkgName.c_str(), - (int32_t)subscribeId); + LOGI("DeviceManager OnDeviceFound pkgName:%s, subscribeId:%d.", pkgName.c_str(), (int32_t)subscribeId); std::lock_guard autoLock(lock_); - if (deviceDiscoverCallbacks_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceFound: no register discoverCallback for this package"); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for this package"); return; } - std::map> &discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceFound: no register discoverCallback for subscribeId %d", - subscribeId); + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } iter->second->OnDeviceFound(subscribeId, deviceInfo); } -void DeviceManagerNotify::OnDiscoverFailed(std::string &pkgName, uint16_t subscribeId, int32_t failedReason) +void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDiscoverFailed pkgName:%s, subscribeId %d, reason %d", - pkgName.c_str(), subscribeId, failedReason); + LOGI("DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", pkgName.c_str(), subscribeId, + failedReason); std::lock_guard autoLock(lock_); - if (deviceDiscoverCallbacks_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverFailed: no register discoverCallback for this package"); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for this package"); return; } - std::map> &discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverFailed: no register discoverCallback for subscribeId %d", - subscribeId); + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } - iter->second->OnDiscoverFailed(subscribeId, failedReason); + iter->second->OnDiscoveryFailed(subscribeId, failedReason); } -void DeviceManagerNotify::OnDiscoverySuccess(std::string &pkgName, uint16_t subscribeId) +void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDiscoverySuccess pkgName:%s, subscribeId:%d.", pkgName.c_str(), - subscribeId); + LOGI("DeviceManager OnDiscoverySuccess pkgName:%s, subscribeId:%d.", pkgName.c_str(), subscribeId); std::lock_guard autoLock(lock_); - if (deviceDiscoverCallbacks_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverySuccess: no register discoverCallback for this package"); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for this package"); return; } - std::map> &discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverySuccess: no register discoverCallback for subscribeId %d", - subscribeId); + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } iter->second->OnDiscoverySuccess(subscribeId); } -void DeviceManagerNotify::OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, - uint32_t status, uint32_t reason) +void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::string &deviceId, + const std::string &token, uint32_t status, uint32_t reason) { - DMLOG(DM_LOG_INFO, "DeviceManagerNotify::OnAuthResult pkgName:%s, status:%d, reason:%d", - pkgName.c_str(), status, reason); + LOGI("DeviceManagerNotify::OnAuthResult pkgName:%s, status:%d, reason:%d", pkgName.c_str(), status, reason); std::lock_guard autoLock(lock_); if (authenticateCallback_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnAuthResult: no register authCallback for this package"); + LOGE("DeviceManager OnAuthResult: no register authCallback for this package"); return; } std::map> &authCallMap = authenticateCallback_[pkgName]; auto iter = authCallMap.find(deviceId); if (iter == authCallMap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnAuthResult: no register authCallback for deviceID "); + LOGE("DeviceManager OnAuthResult: no register authCallback for deviceID "); return; } - iter->second->OnAuthResult(deviceId, pinToken, status, reason); + iter->second->OnAuthResult(deviceId, token, status, reason); authenticateCallback_[pkgName].erase(deviceId); if (authenticateCallback_[pkgName].empty()) { authenticateCallback_.erase(pkgName); } } -void DeviceManagerNotify::OnCheckAuthResult(std::string &pkgName, std::string &deviceId, int32_t resultCode, - int32_t flag) +void DeviceManagerNotify::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, int32_t flag) { - DMLOG(DM_LOG_INFO, "DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", - pkgName.c_str(), resultCode, flag); + LOGI("DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", pkgName.c_str(), resultCode, + flag); std::lock_guard autoLock(lock_); - if (checkauthcallback_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register authCallback for this package"); + if (verifyAuthCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnCheckAuthResult: no register authCallback for this package"); return; } - - checkauthcallback_[pkgName]->OnCheckAuthResult(deviceId, resultCode, flag); - checkauthcallback_.erase(pkgName); + verifyAuthCallback_[pkgName]->OnVerifyAuthResult(deviceId, resultCode, flag); + verifyAuthCallback_.erase(pkgName); } void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) { - DMLOG(DM_LOG_INFO, "DeviceManager OnFaCallback pkgName:%s", pkgName.c_str()); + LOGI("DeviceManager OnFaCallback pkgName:%s", pkgName.c_str()); std::lock_guard autoLock(lock_); if (dmFaCallback_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager DmFaCallback not register"); + LOGE("DeviceManager DmFaCallback not register"); return; } dmFaCallback_[pkgName]->OnCall(paramJson); diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 3ed612208..9bbe372f6 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -16,17 +16,18 @@ import("//foundation/distributedhardware/devicemanager/devicemanager.gni") ohos_shared_library("devicemanager") { include_dirs = [ + "include", + "${common_path}/include", + "${common_path}/include/ipc", + "${utils_path}/include", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc", + "${innerkits_path}/native_cpp/include/ipc/standard", "//third_party/node/src", "//third_party/json/include", - "${common_path}/include", "//foundation/ace/napi/native_engine", "//foundation/ace/napi/interfaces/kits", "//utils/native/base/include", - "include", - "${utils_path}/include/log", - "${common_path}/include/ipc", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/standard", ] sources = [ @@ -63,4 +64,4 @@ ohos_shared_library("devicemanager") { group("devicemanager_native_js") { deps = [ ":devicemanager" ] -} +} \ No newline at end of file diff --git a/interfaces/kits/js/include/dm_native_event.h b/interfaces/kits/js/include/dm_native_event.h index 6a3858bdd..3d619bf99 100644 --- a/interfaces/kits/js/include/dm_native_event.h +++ b/interfaces/kits/js/include/dm_native_event.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,12 +13,13 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_NATIVE_EVENT_H -#define OHOS_DEVICE_MANAGER_NATIVE_EVENT_H +#ifndef OHOS_DM_NATIVE_EVENT_H +#define OHOS_DM_NATIVE_EVENT_H #include #include #include + #include "napi/native_api.h" struct DmEventListener { @@ -41,4 +42,4 @@ protected: std::map> eventMap_; }; -#endif /* OHOS_DEVICE_MANAGER_NATIVE_EVENT_H */ \ No newline at end of file +#endif /* OHOS_DM_NATIVE_EVENT_H */ \ No newline at end of file diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index c232985c0..ddf8e7473 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H -#define OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H +#ifndef OHOS_DM_NATIVE_DEVICEMANAGER_JS_H +#define OHOS_DM_NATIVE_DEVICEMANAGER_JS_H #include #include -#include "napi/native_api.h" -#include "napi/native_node_api.h" + #include "device_manager_callback.h" -#include "dm_native_event.h" +#include "dm_app_image_info.h" #include "dm_device_info.h" +#include "dm_native_event.h" #include "dm_subscribe_info.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" #include "nlohmann/json.hpp" -#include "dm_device_info.h" - #define DM_NAPI_BUF_LENGTH (256) struct AsyncCallbackInfo { @@ -40,6 +40,22 @@ struct AsyncCallbackInfo { int32_t status = -1; }; +struct DeviceInfoAsyncCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + + std::string bundleName; + size_t bundleNameLen = 0; + OHOS::DistributedHardware::DmDeviceInfo deviceInfo; + std::vector devList; + std::string extra; + // OHOS::DistributedHardware::DmFilterOptions filter; + napi_ref callback = nullptr; + napi_value thisVar = nullptr; + napi_deferred deferred = nullptr; + int32_t status = -1; + int32_t isList = 0; +}; struct AuthAsyncCallbackInfo { napi_env env = nullptr; @@ -50,17 +66,16 @@ struct AuthAsyncCallbackInfo { int32_t authType = -1; }; -enum DmNapiDevStateChangeAction { - ONLINE = 0, - READY = 1, - OFFLINE = 2, - CHANGE = 3 -}; +enum DmNapiDevStateChangeAction { ONLINE = 0, READY = 1, OFFLINE = 2, CHANGE = 3 }; class DmNapiInitCallback : public OHOS::DistributedHardware::DmInitCallback { public: - explicit DmNapiInitCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiInitCallback() {} + explicit DmNapiInitCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + virtual ~DmNapiInitCallback() + { + } void OnRemoteDied() override; private: @@ -69,8 +84,10 @@ private: class DmNapiDeviceStateCallback : public OHOS::DistributedHardware::DeviceStateCallback { public: - explicit DmNapiDeviceStateCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiDeviceStateCallback() {}; + explicit DmNapiDeviceStateCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + virtual ~DmNapiDeviceStateCallback(){}; void OnDeviceOnline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; void OnDeviceReady(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; void OnDeviceOffline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; @@ -80,12 +97,14 @@ private: std::string bundleName_; }; -class DmNapiDiscoverCallback : public OHOS::DistributedHardware::DiscoverCallback { +class DmNapiDiscoveryCallback : public OHOS::DistributedHardware::DiscoveryCallback { public: - explicit DmNapiDiscoverCallback(std::string &bundleName) : refCount_(0), bundleName_(bundleName) {} - virtual ~DmNapiDiscoverCallback() {}; + explicit DmNapiDiscoveryCallback(std::string &bundleName) : refCount_(0), bundleName_(bundleName) + { + } + virtual ~DmNapiDiscoveryCallback(){}; void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; - void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) override; + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; void OnDiscoverySuccess(uint16_t subscribeId) override; void IncreaseRefCount(); void DecreaseRefCount(); @@ -96,31 +115,37 @@ private: std::string bundleName_; }; -class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { +class DmNapiDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceManagerFaCallback { public: - explicit DmNapiAuthenticateCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiAuthenticateCallback() {}; - void OnAuthResult(std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) override; + explicit DmNapiDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + virtual ~DmNapiDeviceManagerFaCallback(){}; + void OnCall(const std::string ¶mJson) override; private: std::string bundleName_; }; -class DmNapiCheckAuthCallback : public OHOS::DistributedHardware::CheckAuthCallback { +class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { public: - explicit DmNapiCheckAuthCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiCheckAuthCallback() {}; - void OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) override; + explicit DmNapiAuthenticateCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + virtual ~DmNapiAuthenticateCallback(){}; + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override; private: std::string bundleName_; }; -class DmNapiDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceManagerFaCallback { +class DmNapiVerifyAuthCallback : public OHOS::DistributedHardware::VerifyAuthCallback { public: - explicit DmNapiDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiDeviceManagerFaCallback() {}; - void OnCall(std::string ¶mJson) override; + explicit DmNapiVerifyAuthCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + virtual ~DmNapiVerifyAuthCallback(){}; + void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) override; private: std::string bundleName_; @@ -134,58 +159,80 @@ public: static napi_value Constructor(napi_env env, napi_callback_info info); static napi_value CreateDeviceManager(napi_env env, napi_callback_info info); static napi_value ReleaseDeviceManager(napi_env env, napi_callback_info info); + static napi_value SetUserOperationSync(napi_env env, napi_callback_info info); static napi_value GetTrustedDeviceListSync(napi_env env, napi_callback_info info); + static napi_value GetTrustedDeviceList(napi_env env, napi_callback_info info); + static napi_value GetLocalDeviceInfoSync(napi_env env, napi_callback_info info); + static napi_value GetLocalDeviceInfo(napi_env env, napi_callback_info info); + static napi_value UnAuthenticateDevice(napi_env env, napi_callback_info info); static napi_value StartDeviceDiscoverSync(napi_env env, napi_callback_info info); static napi_value StopDeviceDiscoverSync(napi_env env, napi_callback_info info); static napi_value AuthenticateDevice(napi_env env, napi_callback_info info); static napi_value VerifyAuthInfo(napi_env env, napi_callback_info info); static napi_value JsOn(napi_env env, napi_callback_info info); static napi_value JsOff(napi_env env, napi_callback_info info); - static napi_value SetUserOperationSync(napi_env env, napi_callback_info info); static napi_value GetAuthenticationParamSync(napi_env env, napi_callback_info info); static void HandleCreateDmCallBack(const napi_env &env, AsyncCallbackInfo *asCallbackInfo); static DeviceManagerNapi *GetDeviceManagerNapi(std::string &buldleName); static void CreateDmCallback(std::string &bundleName, std::string &eventType); static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); static void DeviceInfoToJsArray(const napi_env &env, - const std::vector& vecDevInfo, - const int32_t idx, napi_value &arrayResult); - static void DmAuthParamToJsAuthParam(const napi_env &env, - const OHOS::DistributedHardware::DmAuthParam &authParam, napi_value ¶mResult); + const std::vector &vecDevInfo, + const int32_t idx, napi_value &arrayResult); + static void DmAuthParamToJsAuthParam(const napi_env &env, const OHOS::DistributedHardware::DmAuthParam &authParam, + napi_value ¶mResult); static void SetValueInt32(const napi_env &env, const std::string &fieldStr, const int32_t intValue, - napi_value &result); + napi_value &result); static void SetValueUtf8String(const napi_env &env, const std::string &fieldStr, const std::string &str, - napi_value &result); - static void JsObjectToString(const napi_env &env, const napi_value &object, - const std::string &fieldStr, char *dest, const int32_t destLen); - static void JsObjectToBool(const napi_env &env, const napi_value &object, - const std::string &fieldStr, bool& fieldRef); + napi_value &result); + static void JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr, char *dest, + const int32_t destLen); + static void JsObjectToBool(const napi_env &env, const napi_value &object, const std::string &fieldStr, + bool &fieldRef); static void JsObjectToInt(const napi_env &env, const napi_value &object, const std::string &fieldStr, - int& fieldRef); + int &fieldRef); static std::string JsObjectToString(const napi_env &env, const napi_value &object); static int32_t JsToDmSubscribeInfo(const napi_env &env, const napi_value &object, - OHOS::DistributedHardware::DmSubscribeInfo& info); + OHOS::DistributedHardware::DmSubscribeInfo &info); static void JsToDmDeviceInfo(const napi_env &env, const napi_value &object, - OHOS::DistributedHardware::DmDeviceInfo& info); - static void JsToDmAppImageInfoAndDmExtra(const napi_env &env, const napi_value &object, - OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType); + OHOS::DistributedHardware::DmDeviceInfo &info); + static void JsToDmExtra(const napi_env &env, const napi_value &object, std::string &extra, int32_t &authType); static void JsToDmAuthInfo(const napi_env &env, const napi_value &object, std::string &extra); static void JsToDmBuffer(const napi_env &env, const napi_value &object, const std::string &fieldStr, - uint8_t **bufferPtr, int32_t &bufferLen); + uint8_t **bufferPtr, int32_t &bufferLen); static void JsToJsonObject(const napi_env &env, const napi_value &object, const std::string &fieldStr, - nlohmann::json &jsonObj); - static void JsToDmTokenInfo(const napi_env &env, const napi_value &object, - const std::string &fieldStr, nlohmann::json &jsonObj); + nlohmann::json &jsonObj); + static void JsToDmTokenInfo(const napi_env &env, const napi_value &object, const std::string &fieldStr, + nlohmann::json &jsonObj); static void JsToDmAuthExtra(const napi_env &env, const napi_value ¶m, nlohmann::json &jsonObj); + // static void JsToDmFilterOptions(const napi_env &env, const napi_value &object, + // OHOS::DistributedHardware::DmFilterOptions &filterOptions); + static void DmDeviceInfotoJsDeviceInfo(const napi_env &env, + const OHOS::DistributedHardware::DmDeviceInfo &vecDevInfo, + napi_value &result); void OnDeviceStateChange(DmNapiDevStateChangeAction action, - const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); + const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); - void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason); - void OnAuthResult(const std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason); + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason); + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason); void OnVerifyResult(const std::string &deviceId, int32_t resultCode, int32_t flag); void OnDmfaCall(const std::string ¶mJson); - static void DmAuthParamToJsAuthParamy(const napi_env &env, - const OHOS::DistributedHardware::DmAuthParam &authParam, napi_value ¶mResult); + +private: + static napi_value JsOffFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]); + static napi_value JsOnFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]); + static void CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + static void CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + static void CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + static void CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + static napi_value CallDeviceList(napi_env env, napi_callback_info info, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + static void CallGetLocalDeviceInfoSync(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + static void CallGetLocalDeviceInfo(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); private: napi_env env_; @@ -196,4 +243,4 @@ private: static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; }; -#endif // OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H +#endif // OHOS_DM_NATIVE_DEVICEMANAGER_JS_H diff --git a/interfaces/kits/js/src/dm_native_event.cpp b/interfaces/kits/js/src/dm_native_event.cpp index 70084134b..205fcddc9 100644 --- a/interfaces/kits/js/src/dm_native_event.cpp +++ b/interfaces/kits/js/src/dm_native_event.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,7 +15,7 @@ #include "dm_native_event.h" -#include "device_manager_log.h" +#include "dm_log.h" using namespace OHOS::DistributedHardware; @@ -38,7 +38,7 @@ DmNativeEvent::~DmNativeEvent() void DmNativeEvent::On(std::string &eventType, napi_value handler) { - DMLOG(DM_LOG_INFO, "DmNativeEvent On in for event: %s", eventType.c_str()); + LOGI("DmNativeEvent On in for event: %s", eventType.c_str()); auto listener = std::make_shared(); listener->eventType = eventType; napi_create_reference(env_, handler, 1, &listener->handlerRef); @@ -47,17 +47,17 @@ void DmNativeEvent::On(std::string &eventType, napi_value handler) void DmNativeEvent::Off(std::string &eventType) { - DMLOG(DM_LOG_INFO, "DmNativeEvent Off in for event: %s", eventType.c_str()); + LOGI("DmNativeEvent Off in for event: %s", eventType.c_str()); napi_handle_scope scope = nullptr; napi_open_handle_scope(env_, &scope); if (scope == nullptr) { - DMLOG(DM_LOG_ERROR, "scope is nullptr"); + LOGE("scope is nullptr"); return; } auto iter = eventMap_.find(eventType); if (iter == eventMap_.end()) { - DMLOG(DM_LOG_ERROR, "eventType %s not find", eventType.c_str()); + LOGE("eventType %s not find", eventType.c_str()); return; } auto listener = iter->second; @@ -68,38 +68,38 @@ void DmNativeEvent::Off(std::string &eventType) void DmNativeEvent::OnEvent(const std::string &eventType, size_t argc, const napi_value *argv) { - DMLOG(DM_LOG_INFO, "OnEvent for %s", eventType.c_str()); + LOGI("OnEvent for %s", eventType.c_str()); napi_handle_scope scope = nullptr; napi_open_handle_scope(env_, &scope); if (scope == nullptr) { - DMLOG(DM_LOG_ERROR, "scope is nullptr"); + LOGE("scope is nullptr"); return; } auto iter = eventMap_.find(eventType); if (iter == eventMap_.end()) { - DMLOG(DM_LOG_ERROR, "eventType %s not find", eventType.c_str()); + LOGE("eventType %s not find", eventType.c_str()); return; } auto listener = iter->second; napi_value thisVar = nullptr; napi_status status = napi_get_reference_value(env_, thisVarRef_, &thisVar); if (status != napi_ok) { - DMLOG(DM_LOG_ERROR, "napi_get_reference_value thisVar for %s failed, status=%d", eventType.c_str(), status); + LOGE("napi_get_reference_value thisVar for %s failed, status=%d", eventType.c_str(), status); return; } napi_value handler = nullptr; status = napi_get_reference_value(env_, listener->handlerRef, &handler); if (status != napi_ok) { - DMLOG(DM_LOG_ERROR, "napi_get_reference_value handler for %s failed, status=%d", eventType.c_str(), status); + LOGE("napi_get_reference_value handler for %s failed, status=%d", eventType.c_str(), status); return; } napi_value callResult = nullptr; status = napi_call_function(env_, thisVar, handler, argc, argv, &callResult); if (status != napi_ok) { - DMLOG(DM_LOG_ERROR, "napi_call_function for %s failed, status=%d", eventType.c_str(), status); + LOGE("napi_call_function for %s failed, status=%d", eventType.c_str(), status); return; } napi_close_handle_scope(env_, scope); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index bb38a37fd..3a4184de8 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,49 +16,45 @@ #include "native_devicemanager_js.h" #include -#include "nlohmann/json.hpp" #include "device_manager.h" -#include "device_manager_log.h" -#include "constants.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" using namespace OHOS::DistributedHardware; namespace { -#define GET_PARAMS(env, info, num) \ - size_t argc = num; \ - napi_value argv[num] = { nullptr }; \ - napi_value thisVar = nullptr; \ - void *data = nullptr; \ +#define GET_PARAMS(env, info, num) \ + size_t argc = num; \ + napi_value argv[num] = {nullptr}; \ + napi_value thisVar = nullptr; \ + void *data = nullptr; \ NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)) const std::string DM_NAPI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange"; const std::string DM_NAPI_EVENT_DEVICE_FOUND = "deviceFound"; -const std::string DM_NAPI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFail"; -const std::string DM_NAPI_EVENT_DMFA_CALLBACK = "dmFaCallback"; +const std::string DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL = "discoveryFail"; const std::string DM_NAPI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; -const char *DM_CAPABILITY_OSD = "osdCapability"; const std::string DEVICE_MANAGER_NAPI_CLASS_NAME = "DeviceManager"; +const std::string DM_NAPI_EVENT_DMFA_CALLBACK = "dmFaCallback"; const int32_t DM_NAPI_ARGS_ONE = 1; const int32_t DM_NAPI_ARGS_TWO = 2; const int32_t DM_NAPI_ARGS_THREE = 3; const int32_t DM_NAPI_SUB_ID_MAX = 65535; -const int32_t DM_AUTH_TYPE_PINCODE = 1; const int32_t DM_AUTH_DIRECTION_CLIENT = 1; -const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0; -const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_OSD = 1; - std::map g_deviceManagerMap; std::map> g_initCallbackMap; std::map> g_deviceStateCallbackMap; -std::map> g_discoverCallbackMap; +std::map> g_DiscoveryCallbackMap; std::map> g_authCallbackMap; -std::map> g_checkAuthCallbackMap; +std::map> g_verifyAuthCallbackMap; std::map> g_dmfaCallbackMap; -} +} // namespace napi_ref DeviceManagerNapi::sConstructor_ = nullptr; AuthAsyncCallbackInfo DeviceManagerNapi::authAsyncCallbackInfo_; @@ -68,7 +64,7 @@ void DmNapiInitCallback::OnRemoteDied() { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnRemoteDied, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnRemoteDied, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnEvent("serviceDie", 0, nullptr); @@ -78,7 +74,7 @@ void DmNapiDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDeviceOnline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDeviceOnline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::ONLINE, deviceInfo); @@ -88,7 +84,7 @@ void DmNapiDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDeviceOnline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDeviceOnline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::READY, deviceInfo); @@ -98,7 +94,7 @@ void DmNapiDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDeviceOffline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDeviceOffline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::OFFLINE, deviceInfo); @@ -108,90 +104,81 @@ void DmNapiDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDeviceChanged, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDeviceChanged, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::CHANGE, deviceInfo); } -void DmNapiDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +void DmNapiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDeviceFound, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDeviceFound, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } - DMLOG(DM_LOG_INFO, "OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); + LOGI("OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); deviceManagerNapi->OnDeviceFound(subscribeId, deviceInfo); } -void DmNapiDiscoverCallback::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) +void DmNapiDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDiscoverFailed, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDiscoveryFailed, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } - deviceManagerNapi->OnDiscoverFailed(subscribeId, failedReason); + deviceManagerNapi->OnDiscoveryFailed(subscribeId, failedReason); } -void DmNapiDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) +void DmNapiDiscoveryCallback::OnDiscoverySuccess(uint16_t subscribeId) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDiscoverySuccess, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDiscoverySuccess, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } - DMLOG(DM_LOG_INFO, "DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); + LOGI("DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); } -void DmNapiDiscoverCallback::IncreaseRefCount() +void DmNapiDiscoveryCallback::IncreaseRefCount() { refCount_++; } -void DmNapiDiscoverCallback::DecreaseRefCount() +void DmNapiDiscoveryCallback::DecreaseRefCount() { refCount_--; } -int32_t DmNapiDiscoverCallback::GetRefCount() +int32_t DmNapiDiscoveryCallback::GetRefCount() { return refCount_; } -void DmNapiAuthenticateCallback::OnAuthResult(std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) +void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnAuthResult, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnAuthResult, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } - deviceManagerNapi->OnAuthResult(deviceId, pinToken, status, reason); + deviceManagerNapi->OnAuthResult(deviceId, token, status, reason); } -void DmNapiCheckAuthCallback::OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) +void DmNapiVerifyAuthCallback::OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnCheckAuthResult, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnCheckAuthResult, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnVerifyResult(deviceId, resultCode, flag); } -void DmNapiDeviceManagerFaCallback::OnCall(std::string ¶mJson) -{ - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); - if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnCall, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); - return; - } - deviceManagerNapi->OnDmfaCall(paramJson); -} - DeviceManagerNapi::DeviceManagerNapi(napi_env env, napi_value thisVar) : DmNativeEvent(env, thisVar) { env_ = env; @@ -214,7 +201,8 @@ DeviceManagerNapi *DeviceManagerNapi::GetDeviceManagerNapi(std::string &buldleNa return iter->second; } -void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action, const DmDeviceInfo &deviceInfo) +void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action, + const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) { napi_value result = nullptr; napi_create_object(env_, &result); @@ -232,7 +220,7 @@ void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action, c void DeviceManagerNapi::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { - DMLOG(DM_LOG_INFO, "OnDeviceFound for subscribeId %d", (int32_t)subscribeId); + LOGI("OnDeviceFound for subscribeId %d", (int32_t)subscribeId); napi_value result = nullptr; napi_create_object(env_, &result); SetValueInt32(env_, "subscribeId", (int)subscribeId, result); @@ -247,9 +235,9 @@ void DeviceManagerNapi::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo & OnEvent("deviceFound", DM_NAPI_ARGS_ONE, &result); } -void DeviceManagerNapi::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) +void DeviceManagerNapi::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) { - DMLOG(DM_LOG_INFO, "OnDiscoverFailed for subscribeId %d", (int32_t)subscribeId); + LOGI("OnDiscoveryFailed for subscribeId %d", (int32_t)subscribeId); napi_value result = nullptr; napi_create_object(env_, &result); SetValueInt32(env_, "subscribeId", (int)subscribeId, result); @@ -257,32 +245,21 @@ void DeviceManagerNapi::OnDiscoverFailed(uint16_t subscribeId, int32_t failedRea OnEvent("discoverFail", DM_NAPI_ARGS_ONE, &result); } -void DeviceManagerNapi::OnDmfaCall(const std::string ¶mJson) -{ - DMLOG(DM_LOG_INFO, "OnCall for paramJson"); - napi_value result = nullptr; - napi_create_object(env_, &result); - SetValueUtf8String(env_, "param", paramJson, result); - OnEvent("dmFaCallback", DM_NAPI_ARGS_ONE, &result); -} - -void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) +void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) { - DMLOG(DM_LOG_INFO, "OnAuthResult for status: %d, reason: %d", status, reason); + LOGI("OnAuthResult for status: %d, reason: %d", status, reason); napi_value thisVar = nullptr; napi_get_reference_value(env_, thisVarRef_, &thisVar); - napi_value result[DM_NAPI_ARGS_TWO] = { 0 }; + napi_value result[DM_NAPI_ARGS_TWO] = {0}; if (status == 0) { - DMLOG(DM_LOG_INFO, "OnAuthResult success"); + LOGI("OnAuthResult success"); napi_get_undefined(env_, &result[0]); napi_create_object(env_, &result[1]); SetValueUtf8String(env_, "deviceId", deviceId, result[1]); - if (authAsyncCallbackInfo_.authType == DM_AUTH_TYPE_PINCODE) { - SetValueInt32(env_, "pinTone", pinToken, result[1]); - } } else { - DMLOG(DM_LOG_INFO, "OnAuthResult failed"); + LOGI("OnAuthResult failed"); napi_create_object(env_, &result[0]); SetValueInt32(env_, "code", status, result[0]); SetValueInt32(env_, "reason", reason, result[0]); @@ -296,17 +273,17 @@ void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, int32_t pinTok napi_call_function(env_, nullptr, handler, DM_NAPI_ARGS_TWO, &result[0], &callResult); napi_delete_reference(env_, verifyAsyncCallbackInfo_.callback); } else { - DMLOG(DM_LOG_ERROR, "handler is nullptr"); + LOGE("handler is nullptr"); } g_authCallbackMap.erase(bundleName_); } void DeviceManagerNapi::OnVerifyResult(const std::string &deviceId, int32_t resultCode, int32_t flag) { - DMLOG(DM_LOG_INFO, "OnVerifyResult for resultCode: %d, flag: %d", resultCode, flag); + LOGI("OnVerifyResult for resultCode: %d, flag: %d", resultCode, flag); napi_value thisVar = nullptr; napi_get_reference_value(env_, thisVarRef_, &thisVar); - napi_value result[DM_NAPI_ARGS_TWO] = { 0 }; + napi_value result[DM_NAPI_ARGS_TWO] = {0}; if (resultCode == 0) { napi_get_undefined(env_, &result[0]); napi_create_object(env_, &result[1]); @@ -325,13 +302,13 @@ void DeviceManagerNapi::OnVerifyResult(const std::string &deviceId, int32_t resu napi_call_function(env_, nullptr, handler, DM_NAPI_ARGS_TWO, &result[0], &callResult); napi_delete_reference(env_, verifyAsyncCallbackInfo_.callback); } else { - DMLOG(DM_LOG_ERROR, "handler is nullptr"); + LOGE("handler is nullptr"); } - g_checkAuthCallbackMap.erase(bundleName_); + g_verifyAuthCallbackMap.erase(bundleName_); } void DeviceManagerNapi::SetValueUtf8String(const napi_env &env, const std::string &fieldStr, const std::string &str, - napi_value &result) + napi_value &result) { napi_value value = nullptr; napi_create_string_utf8(env, str.c_str(), NAPI_AUTO_LENGTH, &value); @@ -339,16 +316,15 @@ void DeviceManagerNapi::SetValueUtf8String(const napi_env &env, const std::strin } void DeviceManagerNapi::SetValueInt32(const napi_env &env, const std::string &fieldStr, const int32_t intValue, - napi_value &result) + napi_value &result) { napi_value value = nullptr; napi_create_int32(env, intValue, &value); napi_set_named_property(env, result, fieldStr.c_str(), value); } -void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, - const std::vector &vecDevInfo, - const int32_t idx, napi_value &arrayResult) +void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, const std::vector &vecDevInfo, + const int32_t idx, napi_value &arrayResult) { napi_value result = nullptr; napi_create_object(env, &result); @@ -359,20 +335,19 @@ void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, napi_status status = napi_set_element(env, arrayResult, idx, result); if (status != napi_ok) { - DMLOG(DM_LOG_ERROR, "DmDeviceInfo To JsArray set element error: %d", status); + LOGE("DmDeviceInfo To JsArray set element error: %d", status); } } -void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, - const DmAuthParam &authParam, napi_value ¶mResult) +void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam, + napi_value ¶mResult) { - DMLOG(DM_LOG_INFO, "DmAuthParamToJsAuthParamy in"); - SetValueInt32(env, "authType", authParam.authType, paramResult); - napi_value extraInfo = nullptr; napi_create_object(env, &extraInfo); SetValueInt32(env, "direction", authParam.direction, extraInfo); - SetValueInt32(env, "pinToken", authParam.pinToken, extraInfo); + SetValueInt32(env, "authType", authParam.authType, paramResult); + SetValueInt32(env, "pinToken", stoi(authParam.authToken), extraInfo); + if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; @@ -391,8 +366,8 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, napi_value appIconBuffer = nullptr; napi_create_arraybuffer(env, appIconLen, &appIcon, &appIconBuffer); if (appIcon != nullptr && - memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), - appIconLen) == 0) { + memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), + appIconLen) == 0) { napi_value appIconArray = nullptr; napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); napi_set_named_property(env, paramResult, "appIcon", appIconArray); @@ -406,7 +381,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); if (appThumbnail != nullptr && memcpy_s(appThumbnail, appThumbnailLen, - reinterpret_cast(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) { + reinterpret_cast(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) { napi_value appThumbnailArray = nullptr; napi_create_typedarray(env, napi_uint8_array, appThumbnailLen, appThumbnailBuffer, 0, &appThumbnailArray); napi_set_named_property(env, paramResult, "appThumbnail", appThumbnailArray); @@ -414,8 +389,8 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, } } -void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, - const std::string &fieldStr, char *dest, const int32_t destLen) +void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr, + char *dest, const int32_t destLen) { bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); @@ -429,13 +404,13 @@ void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value & size_t result = 0; NAPI_CALL_RETURN_VOID(env, napi_get_value_string_utf8(env, field, dest, destLen, &result)); } else { - DMLOG(DM_LOG_ERROR, "devicemanager napi js to str no property: %s", fieldStr.c_str()); + LOGE("devicemanager napi js to str no property: %s", fieldStr.c_str()); } } std::string DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value ¶m) { - DMLOG(DM_LOG_INFO, "JsObjectToString in."); + LOGI("JsObjectToString in."); size_t size = 0; if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) { return ""; @@ -461,8 +436,8 @@ std::string DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_ return value; } -void DeviceManagerNapi::JsObjectToInt(const napi_env &env, const napi_value &object, - const std::string &fieldStr, int32_t &fieldRef) +void DeviceManagerNapi::JsObjectToInt(const napi_env &env, const napi_value &object, const std::string &fieldStr, + int32_t &fieldRef) { bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); @@ -475,12 +450,12 @@ void DeviceManagerNapi::JsObjectToInt(const napi_env &env, const napi_value &obj NAPI_ASSERT_RETURN_VOID(env, valueType == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, field, &fieldRef); } else { - DMLOG(DM_LOG_ERROR, "devicemanager napi js to int no property: %s", fieldStr.c_str()); + LOGE("devicemanager napi js to int no property: %s", fieldStr.c_str()); } } -void DeviceManagerNapi::JsObjectToBool(const napi_env &env, const napi_value &object, - const std::string &fieldStr, bool &fieldRef) +void DeviceManagerNapi::JsObjectToBool(const napi_env &env, const napi_value &object, const std::string &fieldStr, + bool &fieldRef) { bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); @@ -493,17 +468,16 @@ void DeviceManagerNapi::JsObjectToBool(const napi_env &env, const napi_value &ob NAPI_ASSERT_RETURN_VOID(env, valueType == napi_boolean, "Wrong argument type. Bool expected."); napi_get_value_bool(env, field, &fieldRef); } else { - DMLOG(DM_LOG_ERROR, "devicemanager napi js to bool no property: %s", fieldStr.c_str()); + LOGE("devicemanager napi js to bool no property: %s", fieldStr.c_str()); } } -int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_value &object, - DmSubscribeInfo &info) +int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_value &object, DmSubscribeInfo &info) { int32_t subscribeId = -1; JsObjectToInt(env, object, "subscribeId", subscribeId); if (subscribeId < 0 || subscribeId > DM_NAPI_SUB_ID_MAX) { - DMLOG(DM_LOG_ERROR, "DeviceManagerNapi::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId); + LOGE("DeviceManagerNapi::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId); return -1; } @@ -532,20 +506,19 @@ int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_v return 0; } -void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value &object, - DmDeviceInfo &info) +void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value &object, DmDeviceInfo &info) { JsObjectToString(env, object, "deviceId", info.deviceId, sizeof(info.deviceId)); JsObjectToString(env, object, "deviceName", info.deviceName, sizeof(info.deviceName)); int32_t deviceType = -1; JsObjectToInt(env, object, "deviceType", deviceType); - info.deviceTypeId = (DMDeviceType)deviceType; + info.deviceTypeId = (DmDeviceType)deviceType; } -void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const napi_value &object, - DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) +void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &object, std::string &extra, + int32_t &authType) { - DMLOG(DM_LOG_INFO, "JsToDmAppImageInfoAndDmExtra in."); + LOGI("JsToDmExtra in."); int32_t authTypeTemp = -1; JsObjectToInt(env, object, "authType", authTypeTemp); authType = authTypeTemp; @@ -557,8 +530,7 @@ void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const uint8_t *appThumbnailBufferPtr = nullptr; int32_t appThumbnailBufferLen = 0; JsToDmBuffer(env, object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); - - appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); + // appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); if (appIconBufferPtr != nullptr) { free(appIconBufferPtr); appIconBufferPtr = nullptr; @@ -574,17 +546,17 @@ void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const JsToJsonObject(env, object, "extraInfo", jsonObj); extra = jsonObj.dump(); - DMLOG(DM_LOG_INFO, "appIconLen %d, appThumbnailLen %d", appIconBufferLen, appThumbnailBufferLen); + LOGI("appIconLen %d, appThumbnailLen %d", appIconBufferLen, appThumbnailBufferLen); } -void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &object, - const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen) +void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &object, const std::string &fieldStr, + uint8_t **bufferPtr, int32_t &bufferLen) { - DMLOG(DM_LOG_INFO, "JsToDmBuffer in."); + LOGI("JsToDmBuffer in."); bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); if (!hasProperty) { - DMLOG(DM_LOG_ERROR, "devicemanager napi js to str no property: %s", fieldStr.c_str()); + LOGE("devicemanager napi js to str no property: %s", fieldStr.c_str()); return; } @@ -595,19 +567,18 @@ void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &obje napi_value buffer = nullptr; size_t offset = 0; uint8_t *data = nullptr; - napi_get_typedarray_info(env, field, &type, - &length, reinterpret_cast(&data), &buffer, &offset); + napi_get_typedarray_info(env, field, &type, &length, reinterpret_cast(&data), &buffer, &offset); if (type != napi_uint8_array || length == 0 || data == nullptr) { - DMLOG(DM_LOG_ERROR, "Invaild AppIconInfo"); + LOGE("Invaild AppIconInfo"); return; } - *bufferPtr = (uint8_t*)calloc(sizeof(uint8_t), length); + *bufferPtr = (uint8_t *)calloc(sizeof(uint8_t), length); if (*bufferPtr == nullptr) { - DMLOG(DM_LOG_ERROR, "low memory, calloc return nullptr, length is %d, filed %s", length, fieldStr.c_str()); + LOGE("low memory, calloc return nullptr, length is %d, filed %s", length, fieldStr.c_str()); return; } if (memcpy_s(*bufferPtr, length, data, length) != 0) { - DMLOG(DM_LOG_ERROR, "memcpy_s failed, filed %s", fieldStr.c_str()); + LOGE("memcpy_s failed, filed %s", fieldStr.c_str()); free(*bufferPtr); *bufferPtr = nullptr; return; @@ -615,14 +586,14 @@ void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &obje bufferLen = length; } -void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &object, - const std::string &fieldStr, nlohmann::json &jsonObj) +void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &object, const std::string &fieldStr, + nlohmann::json &jsonObj) { - DMLOG(DM_LOG_INFO, "JsToJsonObject in."); + LOGI("JsToJsonObject in."); bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); if (!hasProperty) { - DMLOG(DM_LOG_ERROR, "devicemanager napi js to str no property: %s", fieldStr.c_str()); + LOGE("devicemanager napi js to str no property: %s", fieldStr.c_str()); return; } @@ -633,7 +604,7 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob uint32_t jsProCount = 0; napi_get_property_names(env, jsonField, &jsProNameList); napi_get_array_length(env, jsProNameList, &jsProCount); - DMLOG(DM_LOG_INFO, "Property size=%d.", jsProCount); + LOGI("Property size=%d.", jsProCount); napi_value jsProName = nullptr; napi_value jsProValue = nullptr; @@ -645,29 +616,29 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob switch (jsValueType) { case napi_string: { std::string natValue = JsObjectToString(env, jsProValue); - DMLOG(DM_LOG_INFO, "Property name=%s, string, value=%s", strProName.c_str(), natValue.c_str()); + LOGI("Property name=%s, string, value=%s", strProName.c_str(), natValue.c_str()); jsonObj[strProName] = natValue; break; } case napi_boolean: { bool elementValue = false; napi_get_value_bool(env, jsProValue, &elementValue); - DMLOG(DM_LOG_INFO, "Property name=%s, boolean, value=%d.", strProName.c_str(), elementValue); + LOGI("Property name=%s, boolean, value=%d.", strProName.c_str(), elementValue); jsonObj[strProName] = elementValue; break; } case napi_number: { int32_t elementValue = 0; if (napi_get_value_int32(env, jsProValue, &elementValue) != napi_ok) { - DMLOG(DM_LOG_ERROR, "Property name=%s, Property int32_t parse error", strProName.c_str()); + LOGE("Property name=%s, Property int32_t parse error", strProName.c_str()); } else { jsonObj[strProName] = elementValue; - DMLOG(DM_LOG_INFO, "Property name=%s, number, value=%d.", strProName.c_str(), elementValue); + LOGI("Property name=%s, number, value=%d.", strProName.c_str(), elementValue); } break; } default: { - DMLOG(DM_LOG_ERROR, "Property name=%s, value type not support.", strProName.c_str()); + LOGE("Property name=%s, value type not support.", strProName.c_str()); break; } } @@ -676,27 +647,32 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &object, std::string &extra) { - DMLOG(DM_LOG_INFO, "%s called.", __func__); + LOGI("%s called.", __func__); int32_t authType = -1; int32_t token = -1; JsObjectToInt(env, object, "authType", authType); JsObjectToInt(env, object, "token", token); - nlohmann::json jsonObj; jsonObj[AUTH_TYPE] = authType; - if (authType == DM_AUTH_TYPE_PINCODE) { - jsonObj[PIN_TOKEN] = token; - } else { - jsonObj[TOKEN] = token; - } + jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); extra = jsonObj.dump(); } +void DeviceManagerNapi::DmDeviceInfotoJsDeviceInfo(const napi_env &env, const DmDeviceInfo &vecDevInfo, + napi_value &result) +{ + napi_create_object(env, &result); + + SetValueUtf8String(env, "deviceId", vecDevInfo.deviceId, result); + SetValueUtf8String(env, "deviceName", vecDevInfo.deviceName, result); + SetValueInt32(env, "deviceType", (int)vecDevInfo.deviceTypeId, result); +} + void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &eventType) { - DMLOG(DM_LOG_ERROR, "CreateDmCallback for bunderName %s eventType %s", bundleName.c_str(), eventType.c_str()); + LOGE("CreateDmCallback for bundleName %s eventType %s", bundleName.c_str(), eventType.c_str()); if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) { auto iter = g_deviceStateCallbackMap.find(bundleName); if (iter == g_deviceStateCallbackMap.end()) { @@ -704,7 +680,7 @@ void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &e std::string extra = ""; int32_t ret = DeviceManager::GetInstance().RegisterDevStateCallback(bundleName, extra, callback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; } g_deviceStateCallbackMap[bundleName] = callback; @@ -712,18 +688,18 @@ void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &e return; } - if (eventType == DM_NAPI_EVENT_DEVICE_FOUND || eventType == DM_NAPI_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; + if (eventType == DM_NAPI_EVENT_DEVICE_FOUND || eventType == DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL) { + std::shared_ptr DiscoveryCallback = nullptr; + auto iter = g_DiscoveryCallbackMap.find(bundleName); + if (iter == g_DiscoveryCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + g_DiscoveryCallbackMap[bundleName] = callback; + DiscoveryCallback = callback; } else { - discoverCallback = iter->second; + DiscoveryCallback = iter->second; } - discoverCallback->IncreaseRefCount(); + DiscoveryCallback->IncreaseRefCount(); return; } @@ -733,7 +709,7 @@ void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &e auto callback = std::make_shared(bundleName); int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName, callback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "RegisterDeviceManagerFaCallback failed for bunderName %s", bundleName.c_str()); + LOGE("RegisterDeviceManagerFaCallback failed for bunderName %s", bundleName.c_str()); return; } g_dmfaCallbackMap[bundleName] = callback; @@ -747,29 +723,29 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) { auto iter = g_deviceStateCallbackMap.find(bundleName); if (iter == g_deviceStateCallbackMap.end()) { - DMLOG(DM_LOG_ERROR, "ReleaseDmCallback: cannot find stateCallback for bunderName %s", bundleName.c_str()); + LOGE("ReleaseDmCallback: cannot find stateCallback for bunderName %s", bundleName.c_str()); return; } int32_t ret = DeviceManager::GetInstance().UnRegisterDevStateCallback(bundleName); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; } g_deviceStateCallbackMap.erase(bundleName); return; } - if (eventType == DM_NAPI_EVENT_DEVICE_FOUND || eventType == DM_NAPI_EVENT_DEVICE_DISCOVER_FAIL) { - std::shared_ptr discoverCallback = nullptr; - auto iter = g_discoverCallbackMap.find(bundleName); - if (iter == g_discoverCallbackMap.end()) { + if (eventType == DM_NAPI_EVENT_DEVICE_FOUND || eventType == DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL) { + std::shared_ptr DiscoveryCallback = nullptr; + auto iter = g_DiscoveryCallbackMap.find(bundleName); + if (iter == g_DiscoveryCallbackMap.end()) { return; } - discoverCallback = iter->second; - discoverCallback->DecreaseRefCount(); - if (discoverCallback->GetRefCount() == 0) { - g_discoverCallbackMap.erase(bundleName); + DiscoveryCallback = iter->second; + DiscoveryCallback->DecreaseRefCount(); + if (DiscoveryCallback->GetRefCount() == 0) { + g_DiscoveryCallbackMap.erase(bundleName); } return; } @@ -777,12 +753,12 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & if (eventType == DM_NAPI_EVENT_DMFA_CALLBACK) { auto iter = g_dmfaCallbackMap.find(bundleName); if (iter == g_dmfaCallbackMap.end()) { - DMLOG(DM_LOG_ERROR, "cannot find dmFaCallback for bunderName %s", bundleName.c_str()); + LOGE("cannot find dmFaCallback for bunderName %s", bundleName.c_str()); return; } int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; } g_dmfaCallbackMap.erase(bundleName); @@ -790,11 +766,34 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & } } +napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_callback_info info) +{ + LOGI("GetAuthenticationParamSync in"); + size_t argc = 0; + napi_value thisVar = nullptr; + napi_value resultParam = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); + NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + DmAuthParam authParam; + int32_t ret = DeviceManager::GetInstance().GetFaParam(deviceManagerWrapper->bundleName_, authParam); + if (ret != 0) { + LOGE("GetAuthenticationParam for %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); + napi_get_undefined(env, &resultParam); + return resultParam; + } + napi_create_object(env, &resultParam); + DmAuthParamToJsAuthParam(env, authParam, resultParam); + return resultParam; +} + napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "SetUserOperationSync in"); + LOGI("SetUserOperationSync in"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); - napi_valuetype valueType = napi_undefined; + napi_valuetype valueType; napi_typeof(env, argv[0], &valueType); NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Object expected."); @@ -804,83 +803,439 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); int32_t ret = DeviceManager::GetInstance().SetUserOperation(deviceManagerWrapper->bundleName_, action); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "SetUserOperation for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); + LOGE("SetUserOperation for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } napi_value result = nullptr; napi_get_undefined(env, &result); return result; } -napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_callback_info info) +void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) { - DMLOG(DM_LOG_INFO, "GetAuthenticationParamSync in"); - size_t argc = 0; - napi_value thisVar = nullptr; - napi_value resultParam = nullptr; + for (unsigned int i = 0; i < deviceInfoAsyncCallbackInfo->devList.size(); i++) { + LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ", + deviceInfoAsyncCallbackInfo->devList[i].deviceId, deviceInfoAsyncCallbackInfo->devList[i].deviceName, + deviceInfoAsyncCallbackInfo->devList[i].deviceTypeId); + } - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); - NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); + napi_value array[DM_NAPI_ARGS_TWO] = {0}; + if (deviceInfoAsyncCallbackInfo->status == 0) { + if (deviceInfoAsyncCallbackInfo->devList.size() > 0) { + bool isArray = false; + napi_create_array(env, &array[1]); + napi_is_array(env, array[1], &isArray); + if (isArray == false) { + LOGE("napi_create_array fail"); + } + for (unsigned int i = 0; i != deviceInfoAsyncCallbackInfo->devList.size(); ++i) { + DeviceInfoToJsArray(env, deviceInfoAsyncCallbackInfo->devList, i, array[1]); + } + napi_resolve_deferred(env, deviceInfoAsyncCallbackInfo->deferred, array[1]); + LOGE("devList is OK"); + } else { + LOGE("devList is null"); + } + } else { + napi_create_object(env, &array[0]); + SetValueInt32(env, "code", status, array[0]); + napi_reject_deferred(env, deviceInfoAsyncCallbackInfo->deferred, array[0]); + } +} - DeviceManagerNapi *deviceManagerWrapper = nullptr; - napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); +void DmNapiDeviceManagerFaCallback::OnCall(const std::string ¶mJson) +{ + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); + if (deviceManagerNapi == nullptr) { + LOGE("OnCall, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerNapi->OnDmfaCall(paramJson); +} - DmAuthParam authParam; - int32_t ret = DeviceManager::GetInstance().GetAuthenticationParam(deviceManagerWrapper->bundleName_, authParam); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "GetAuthenticationParam for %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); - napi_get_undefined(env, &resultParam); - return resultParam; +void DeviceManagerNapi::OnDmfaCall(const std::string ¶mJson) +{ + LOGI("OnCall for paramJson"); + napi_value result; + napi_create_object(env_, &result); + SetValueUtf8String(env_, "param", paramJson, result); + OnEvent("dmFaCallback", DM_NAPI_ARGS_ONE, &result); +} + +void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) +{ + for (unsigned int i = 0; i < deviceInfoAsyncCallbackInfo->devList.size(); i++) { + LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ", + deviceInfoAsyncCallbackInfo->devList[i].deviceId, deviceInfoAsyncCallbackInfo->devList[i].deviceName, + deviceInfoAsyncCallbackInfo->devList[i].deviceTypeId); } + napi_value callResult = nullptr; + napi_value handler = nullptr; + napi_value array[DM_NAPI_ARGS_TWO] = {0}; + + if (deviceInfoAsyncCallbackInfo->status == 0) { + if (deviceInfoAsyncCallbackInfo->devList.size() > 0) { + bool isArray = false; + napi_create_array(env, &array[1]); + napi_is_array(env, array[1], &isArray); + if (isArray == false) { + LOGE("napi_create_array fail"); + } - napi_create_object(env, &resultParam); - DmAuthParamToJsAuthParamy(env, authParam, resultParam); - return resultParam; + for (size_t i = 0; i != deviceInfoAsyncCallbackInfo->devList.size(); ++i) { + DeviceInfoToJsArray(env, deviceInfoAsyncCallbackInfo->devList, i, array[1]); + } + LOGE("devList is OK"); + } else { + LOGE("devList is null"); + } + } else { + napi_create_object(env, &array[0]); + SetValueInt32(env, "code", status, array[0]); + } + + napi_get_reference_value(env, deviceInfoAsyncCallbackInfo->callback, &handler); + if (handler != nullptr) { + napi_call_function(env, nullptr, handler, DM_NAPI_ARGS_TWO, &array[0], &callResult); + napi_delete_reference(env, deviceInfoAsyncCallbackInfo->callback); + } else { + LOGE("handler is nullptr"); + } +} + +void DeviceManagerNapi::CallGetLocalDeviceInfoSync(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) +{ + napi_value result[DM_NAPI_ARGS_TWO] = {0}; + + LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ", + deviceInfoAsyncCallbackInfo->deviceInfo.deviceId, deviceInfoAsyncCallbackInfo->deviceInfo.deviceName, + deviceInfoAsyncCallbackInfo->deviceInfo.deviceTypeId); + + if (deviceInfoAsyncCallbackInfo->status == 0) { + DmDeviceInfotoJsDeviceInfo(env, deviceInfoAsyncCallbackInfo->deviceInfo, result[1]); + } else { + napi_create_object(env, &result[0]); + SetValueInt32(env, "code", status, result[0]); + napi_reject_deferred(env, deviceInfoAsyncCallbackInfo->deferred, result[0]); + } +} + +void DeviceManagerNapi::CallGetLocalDeviceInfo(napi_env env, napi_status &status, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) +{ + napi_value result[DM_NAPI_ARGS_TWO] = {0}; + LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ", + deviceInfoAsyncCallbackInfo->deviceInfo.deviceId, deviceInfoAsyncCallbackInfo->deviceInfo.deviceName, + deviceInfoAsyncCallbackInfo->deviceInfo.deviceTypeId); + napi_value callResult = nullptr; + napi_value handler = nullptr; + + if (deviceInfoAsyncCallbackInfo->status == 0) { + DmDeviceInfotoJsDeviceInfo(env, deviceInfoAsyncCallbackInfo->deviceInfo, result[1]); + } else { + napi_create_object(env, &result[0]); + SetValueInt32(env, "code", status, result[0]); + } + + napi_get_reference_value(env, deviceInfoAsyncCallbackInfo->callback, &handler); + if (handler != nullptr) { + napi_call_function(env, nullptr, handler, DM_NAPI_ARGS_TWO, &result[0], &callResult); + napi_delete_reference(env, deviceInfoAsyncCallbackInfo->callback); + } else { + LOGE("handler is nullptr"); + } +} + +void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) +{ + napi_value resourceName; + napi_create_string_latin1(env, "GetLocalDeviceInfo", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + (void)env; + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; + int32_t ret = 0; + if (deviceInfoAsyncCallbackInfo->isList == 1) { + ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->extra, + deviceInfoAsyncCallbackInfo->devList); + } else { + ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->deviceInfo); + } + if (ret != 0) { + LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", + deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); + deviceInfoAsyncCallbackInfo->status = -1; + return; + } + deviceInfoAsyncCallbackInfo->status = 0; + LOGE("GetTrustedDeviceList status %d", deviceInfoAsyncCallbackInfo->status); + }, + [](napi_env env, napi_status status, void *data) { + (void)status; + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; + if (deviceInfoAsyncCallbackInfo->isList == 1) { + CallGetTrustedDeviceListStatusSync(env, status, deviceInfoAsyncCallbackInfo); + } else { + CallGetLocalDeviceInfoSync(env, status, deviceInfoAsyncCallbackInfo); + } + napi_delete_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); + delete deviceInfoAsyncCallbackInfo; + }, + (void *)deviceInfoAsyncCallbackInfo, &deviceInfoAsyncCallbackInfo->asyncWork); + napi_queue_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); +} + +void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) +{ + napi_value resourceName; + napi_create_string_latin1(env, "GetLocalDeviceInfo", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; + int32_t ret = 0; + if (deviceInfoAsyncCallbackInfo->isList == 1) { + ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->extra, + deviceInfoAsyncCallbackInfo->devList); + } else { + ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->deviceInfo); + } + if (ret != 0) { + LOGE("CallAsyncWork for bunderName %s failed, ret %d", deviceInfoAsyncCallbackInfo->bundleName.c_str(), + ret); + deviceInfoAsyncCallbackInfo->status = -1; + return; + } + deviceInfoAsyncCallbackInfo->status = 0; + LOGE("CallAsyncWork status %d", deviceInfoAsyncCallbackInfo->status); + }, + [](napi_env env, napi_status status, void *data) { + (void)status; + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; + if (deviceInfoAsyncCallbackInfo->isList == 1) { + CallGetTrustedDeviceListStatus(env, status, deviceInfoAsyncCallbackInfo); + } else { + CallGetLocalDeviceInfo(env, status, deviceInfoAsyncCallbackInfo); + } + napi_delete_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); + delete deviceInfoAsyncCallbackInfo; + }, + (void *)deviceInfoAsyncCallbackInfo, &deviceInfoAsyncCallbackInfo->asyncWork); + napi_queue_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); +} + +napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info info, + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) +{ + napi_value result = nullptr; + std::string extra = ""; + deviceInfoAsyncCallbackInfo->extra = extra; + GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[0], &eventHandleType); + if (eventHandleType == napi_function) { + LOGE("CallDeviceList for argc %d Type = %d", argc, (int)eventHandleType); + napi_create_reference(env, argv[0], 1, &deviceInfoAsyncCallbackInfo->callback); + CallAsyncWork(env, deviceInfoAsyncCallbackInfo); + napi_get_undefined(env, &result); + return result; + } else { + LOGE("CallDeviceList for argc %d Type = %d", argc, (int)eventHandleType); + // DmFilterOptions filterOptions; + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + deviceInfoAsyncCallbackInfo->deferred = deferred; + char extraString[20]; + JsObjectToString(env, argv[0], "extra", extraString, sizeof(extraString)); + deviceInfoAsyncCallbackInfo->extra = extraString; + CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); + return promise; + } } napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "GetTrustedDeviceList in"); - size_t argc = 0; + LOGI("GetTrustedDeviceListSync in"); + napi_value result = nullptr; napi_value thisVar = nullptr; - napi_value array = nullptr; + DmDeviceInfo deviceInfo; + LOGI("DeviceManager::GetTrustedDeviceListSync deviceId:%s deviceName:%s deviceTypeId:%d ", deviceInfo.deviceId, + deviceInfo.deviceName, deviceInfo.deviceTypeId); + size_t argc = 0; + bool isArray = false; + napi_create_array(env, &result); + napi_is_array(env, result, &isArray); + if (isArray == false) { + LOGE("napi_create_array fail"); + } NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); - NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); - + NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); std::string extra = ""; - std::vector devList; + std::vector devList; int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceManagerWrapper->bundleName_, extra, devList); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); - return array; + LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); + return result; } - + LOGI("DeviceManager::GetTrustedDeviceListSync"); if (devList.size() > 0) { - bool isArray = false; - napi_create_array(env, &array); - napi_is_array(env, array, &isArray); - if (isArray == false) { - DMLOG(DM_LOG_ERROR, "napi_create_array fail"); - } - for (size_t i = 0; i != devList.size(); ++i) { - DeviceInfoToJsArray(env, devList, i, array); + DeviceInfoToJsArray(env, devList, i, result); } - } else { - DMLOG(DM_LOG_ERROR, "devList is null"); + } + return result; +} + +napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_info info) +{ + LOGI("GetTrustedDeviceList in"); + napi_value result = nullptr; + napi_value thisVar = nullptr; + size_t argc = 0; + std::vector devList; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); + + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + auto *deviceInfoAsyncCallbackInfo = new DeviceInfoAsyncCallbackInfo(); + deviceInfoAsyncCallbackInfo->env = env; + deviceInfoAsyncCallbackInfo->devList = devList; + deviceInfoAsyncCallbackInfo->isList = 1; + deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; + LOGE("GetTrustedDeviceList for argc %d", argc); + if (argc == 0) { + std::string extra = ""; + deviceInfoAsyncCallbackInfo->extra = extra; + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + deviceInfoAsyncCallbackInfo->deferred = deferred; + CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); + return promise; + } else if (argc == 1) { + return CallDeviceList(env, info, deviceInfoAsyncCallbackInfo); + } else if (argc == 2) { + // DmFilterOptions filterOptions; + GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + LOGE("GetTrustedDeviceList for argc %d Type = %d", argc, (int)valueType); + NAPI_ASSERT(env, valueType == napi_string, "Wrong argument type, string expected."); + + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[1], &eventHandleType); + LOGE("GetTrustedDeviceList for argc %d Type = %d", argc, (int)eventHandleType); + NAPI_ASSERT(env, eventHandleType == napi_function, "Wrong argument type. Object expected."); + char extra[20]; + JsObjectToString(env, argv[0], "extra", extra, sizeof(extra)); + deviceInfoAsyncCallbackInfo->extra = extra; + napi_create_reference(env, argv[1], 1, &deviceInfoAsyncCallbackInfo->callback); + CallAsyncWork(env, deviceInfoAsyncCallbackInfo); + napi_get_undefined(env, &result); + return result; + } + napi_get_undefined(env, &result); + return result; +} +napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback_info info) +{ + LOGI("GetLocalDeviceInfoSync in"); + napi_value result = nullptr; + napi_value thisVar = nullptr; + DmDeviceInfo deviceInfo; + LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ", deviceInfo.deviceId, + deviceInfo.deviceName, deviceInfo.deviceTypeId); + size_t argc = 0; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); + NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceManagerWrapper->bundleName_, deviceInfo); + if (ret != 0) { + LOGE("GetLocalDeviceInfoSync for failed, ret %d", ret); + return result; + } + LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ", deviceInfo.deviceId, + deviceInfo.deviceName, deviceInfo.deviceTypeId); + DmDeviceInfotoJsDeviceInfo(env, deviceInfo, result); + return result; +} + +napi_value DeviceManagerNapi::GetLocalDeviceInfo(napi_env env, napi_callback_info info) +{ + LOGI("GetLocalDeviceInfo in"); + napi_value result = nullptr; + napi_value thisVar = nullptr; + size_t argc = 0; + DmDeviceInfo deviceInfo; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); + + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + auto *deviceInfoAsyncCallbackInfo = new DeviceInfoAsyncCallbackInfo(); + deviceInfoAsyncCallbackInfo->env = env; + deviceInfoAsyncCallbackInfo->deviceInfo = deviceInfo; + deviceInfoAsyncCallbackInfo->isList = 0; + deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; + LOGE("GetLocalDeviceInfo for argc %d", argc); + if (argc == 0) { + std::string extra = ""; + deviceInfoAsyncCallbackInfo->extra = extra; + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + deviceInfoAsyncCallbackInfo->deferred = deferred; + CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); + return promise; + } else if (argc == 1) { + std::string extra = ""; + deviceInfoAsyncCallbackInfo->extra = extra; + GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); + napi_create_reference(env, argv[0], 1, &deviceInfoAsyncCallbackInfo->callback); + CallAsyncWork(env, deviceInfoAsyncCallbackInfo); + napi_get_undefined(env, &result); + return result; + } + napi_get_undefined(env, &result); + return result; +} + +napi_value DeviceManagerNapi::UnAuthenticateDevice(napi_env env, napi_callback_info info) +{ + LOGI("UnAuthenticateDevice"); + napi_value result = nullptr; + napi_valuetype deviceInfoType; + GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); + napi_typeof(env, argv[0], &deviceInfoType); + NAPI_ASSERT(env, deviceInfoType == napi_string, "Wrong argument type. String expected."); + std::string deviceId = JsObjectToString(env, argv[0]); + LOGI("UnAuthenticateDevice deviceId=%s", deviceId.c_str()); + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + int32_t ret = DeviceManager::GetInstance().UnAuthenticateDevice(deviceManagerWrapper->bundleName_, deviceId); + if (ret != 0) { + LOGE("UnAuthenticateDevice for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } - return array; + napi_create_int32(env, ret, &result); + return result; } napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "StartDeviceDiscoverSync in"); + LOGI("StartDeviceDiscoverSync in"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); napi_value result = nullptr; napi_valuetype valueType = napi_undefined; @@ -890,23 +1245,24 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - std::shared_ptr discoverCallback = nullptr; - auto iter = g_discoverCallbackMap.find(deviceManagerWrapper->bundleName_); - if (iter == g_discoverCallbackMap.end()) { - discoverCallback = std::make_shared(deviceManagerWrapper->bundleName_); - g_discoverCallbackMap[deviceManagerWrapper->bundleName_] = discoverCallback; + std::shared_ptr DiscoveryCallback = nullptr; + auto iter = g_DiscoveryCallbackMap.find(deviceManagerWrapper->bundleName_); + if (iter == g_DiscoveryCallbackMap.end()) { + DiscoveryCallback = std::make_shared(deviceManagerWrapper->bundleName_); + g_DiscoveryCallbackMap[deviceManagerWrapper->bundleName_] = DiscoveryCallback; } else { - discoverCallback = iter->second; + DiscoveryCallback = iter->second; } DmSubscribeInfo subInfo; int32_t res = JsToDmSubscribeInfo(env, argv[0], subInfo); NAPI_ASSERT(env, res == 0, "Wrong subscribeId "); - int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, - subInfo, discoverCallback); + std::string extra = ""; + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, subInfo, extra, + DiscoveryCallback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); + LOGE("StartDeviceDiscovery for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); + DiscoveryCallback->OnDiscoveryFailed(subInfo.subscribeId, ret); return result; } @@ -916,24 +1272,21 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "StopDeviceDiscoverSync in"); + LOGI("StopDeviceDiscoverSync in"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); napi_value result = nullptr; napi_valuetype valueType = napi_undefined; napi_typeof(env, argv[0], &valueType); NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Object expected."); - int32_t subscribeId = 0; napi_get_value_int32(env, argv[0], &subscribeId); NAPI_ASSERT(env, subscribeId <= DM_NAPI_SUB_ID_MAX, "Wrong argument. subscribeId Too Big."); - DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(deviceManagerWrapper->bundleName_, - (int16_t)subscribeId); + int32_t ret = + DeviceManager::GetInstance().StopDeviceDiscovery(deviceManagerWrapper->bundleName_, (int16_t)subscribeId); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); + LOGE("StopDeviceDiscovery for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); return result; } @@ -945,7 +1298,7 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf { const int32_t PARAM_INDEX_ONE = 1; const int32_t PARAM_INDEX_TWO = 2; - DMLOG(DM_LOG_INFO, "AuthenticateDevice in"); + LOGI("AuthenticateDevice in"); GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); napi_value result = nullptr; napi_valuetype deviceInfoType = napi_undefined; @@ -976,25 +1329,20 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf } DmDeviceInfo deviceInfo; JsToDmDeviceInfo(env, argv[0], deviceInfo); - - DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); - std::string extra; - JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], appImageInfo, extra, authAsyncCallbackInfo_.authType); - - int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, deviceInfo, - appImageInfo, extra, authCallback); + std::string extraString; + JsToDmExtra(env, argv[PARAM_INDEX_ONE], extraString, authAsyncCallbackInfo_.authType); + int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, + extraString, authCallback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); + LOGE("AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } - napi_get_undefined(env, &result); return result; } napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "VerifyAuthInfo in"); + LOGI("VerifyAuthInfo in"); GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); napi_value result = nullptr; napi_valuetype valueType = napi_undefined; @@ -1011,42 +1359,29 @@ napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info in DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - std::shared_ptr verifyCallback = nullptr; - auto iter = g_checkAuthCallbackMap.find(deviceManagerWrapper->bundleName_); - if (iter == g_checkAuthCallbackMap.end()) { - verifyCallback = std::make_shared(deviceManagerWrapper->bundleName_); - g_checkAuthCallbackMap[deviceManagerWrapper->bundleName_] = verifyCallback; + std::shared_ptr verifyCallback = nullptr; + auto iter = g_verifyAuthCallbackMap.find(deviceManagerWrapper->bundleName_); + if (iter == g_verifyAuthCallbackMap.end()) { + verifyCallback = std::make_shared(deviceManagerWrapper->bundleName_); + g_verifyAuthCallbackMap[deviceManagerWrapper->bundleName_] = verifyCallback; } else { verifyCallback = iter->second; } std::string authParam; JsToDmAuthInfo(env, argv[0], authParam); - int32_t ret = DeviceManager::GetInstance().CheckAuthentication(deviceManagerWrapper->bundleName_, - authParam, verifyCallback); + int32_t ret = + DeviceManager::GetInstance().VerifyAuthentication(deviceManagerWrapper->bundleName_, authParam, verifyCallback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "VerifyAuthInfo for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); + LOGE("VerifyAuthInfo for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } napi_get_undefined(env, &result); return result; } -napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) +napi_value DeviceManagerNapi::JsOnFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]) { - DMLOG(DM_LOG_INFO, "JsOn in"); - GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); - NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2"); - - napi_valuetype eventValueType = napi_undefined; - napi_typeof(env, argv[0], &eventValueType); - NAPI_ASSERT(env, eventValueType == napi_string, "type mismatch for parameter 1"); - - napi_valuetype eventHandleType = napi_undefined; - napi_typeof(env, argv[1], &eventHandleType); - NAPI_ASSERT(env, eventHandleType == napi_function, "type mismatch for parameter 2"); - size_t typeLen = 0; napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen); @@ -1054,14 +1389,18 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) NAPI_ASSERT(env, typeLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN"); char type[DM_NAPI_BUF_LENGTH] = {0}; napi_get_value_string_utf8(env, argv[0], type, typeLen + 1, &typeLen); + if (num) { + // DmFilterOptions filterOptions; + // JsToDmFilterOptions(env, argv[1], filterOptions); + } std::string eventType = type; DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - DMLOG(DM_LOG_INFO, "JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), - eventType.c_str()); - deviceManagerWrapper->On(eventType, argv[1]); + LOGI("JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); + deviceManagerWrapper->On(eventType, argv[num + 1]); + CreateDmCallback(deviceManagerWrapper->bundleName_, eventType); napi_value result = nullptr; @@ -1069,26 +1408,50 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) return result; } -napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) +napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "JsOff in"); - GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); - size_t requireArgc = 1; - NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments, required 1"); + size_t argc = 0; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); + if (argc == 3) { + LOGI("JsOff in argc == 3"); + GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); + NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_THREE, "Wrong number of arguments, required 2"); + + napi_valuetype eventValueType = napi_undefined; + napi_typeof(env, argv[0], &eventValueType); + NAPI_ASSERT(env, eventValueType == napi_string, "type mismatch for parameter 1"); + + napi_valuetype valueType; + napi_typeof(env, argv[1], &valueType); + NAPI_ASSERT(env, valueType == napi_object, "type mismatch for parameter 2"); + + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[2], &eventHandleType); + NAPI_ASSERT(env, eventHandleType == napi_function, "type mismatch for parameter 3"); - napi_valuetype eventValueType = napi_undefined; - napi_typeof(env, argv[0], &eventValueType); - NAPI_ASSERT(env, eventValueType == napi_string, "type mismatch for parameter 1"); + return JsOnFrench(env, 1, thisVar, argv); + } else { + LOGI("JsOn in"); + GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); + NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2"); + + napi_valuetype eventValueType = napi_undefined; + napi_typeof(env, argv[0], &eventValueType); + NAPI_ASSERT(env, eventValueType == napi_string, "type mismatch for parameter 1"); - if (argc > requireArgc) { napi_valuetype eventHandleType = napi_undefined; napi_typeof(env, argv[1], &eventHandleType); - NAPI_ASSERT(env, eventValueType == napi_function, "type mismatch for parameter 2"); + NAPI_ASSERT(env, eventHandleType == napi_function, "type mismatch for parameter 2"); + + return JsOnFrench(env, 0, thisVar, argv); } +} +napi_value DeviceManagerNapi::JsOffFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]) +{ size_t typeLen = 0; napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen); - NAPI_ASSERT(env, typeLen > 0, "typeLen == 0"); NAPI_ASSERT(env, typeLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN"); char type[DM_NAPI_BUF_LENGTH] = {0}; @@ -1098,8 +1461,7 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - DMLOG(DM_LOG_INFO, "JsOff for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), - eventType.c_str()); + LOGI("JsOff for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); deviceManagerWrapper->Off(eventType); ReleaseDmCallback(deviceManagerWrapper->bundleName_, eventType); @@ -1108,9 +1470,52 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) return result; } +napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) +{ + size_t argc = 0; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); + if (argc == 3) { + LOGI("JsOff in argc == 3"); + GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); + size_t requireArgc = 1; + NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments, required 1"); + + napi_valuetype eventValueType = napi_undefined; + napi_typeof(env, argv[0], &eventValueType); + NAPI_ASSERT(env, eventValueType == napi_string, "type mismatch for parameter 1"); + + napi_valuetype valueType; + napi_typeof(env, argv[1], &valueType); + NAPI_ASSERT(env, valueType == napi_object, "type mismatch for parameter 2"); + + if (argc > requireArgc) { + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[2], &eventHandleType); + NAPI_ASSERT(env, eventValueType == napi_function, "type mismatch for parameter 2"); + } + return JsOffFrench(env, 1, thisVar, argv); + } else { + LOGI("JsOff in"); + GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); + size_t requireArgc = 1; + NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments, required 1"); + + napi_valuetype eventValueType = napi_undefined; + napi_typeof(env, argv[0], &eventValueType); + NAPI_ASSERT(env, eventValueType == napi_string, "type mismatch for parameter 1"); + + if (argc > requireArgc) { + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[1], &eventHandleType); + NAPI_ASSERT(env, eventValueType == napi_function, "type mismatch for parameter 2"); + } + return JsOffFrench(env, 0, thisVar, argv); + } +} napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "ReleaseDeviceManager in"); + LOGI("ReleaseDeviceManager in"); size_t argc = 0; napi_value thisVar = nullptr; napi_value result = nullptr; @@ -1120,11 +1525,10 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - DMLOG(DM_LOG_INFO, "ReleaseDeviceManager for bunderName %s", deviceManagerWrapper->bundleName_.c_str()); + LOGI("ReleaseDeviceManager for bunderName %s", deviceManagerWrapper->bundleName_.c_str()); int32_t ret = DeviceManager::GetInstance().UnInitDeviceManager(deviceManagerWrapper->bundleName_); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "ReleaseDeviceManager for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); + LOGE("ReleaseDeviceManager for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); napi_create_uint32(env, ret, &result); return result; } @@ -1132,9 +1536,9 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i g_deviceManagerMap.erase(deviceManagerWrapper->bundleName_); g_initCallbackMap.erase(deviceManagerWrapper->bundleName_); g_deviceStateCallbackMap.erase(deviceManagerWrapper->bundleName_); - g_discoverCallbackMap.erase(deviceManagerWrapper->bundleName_); + g_DiscoveryCallbackMap.erase(deviceManagerWrapper->bundleName_); g_authCallbackMap.erase(deviceManagerWrapper->bundleName_); - g_checkAuthCallbackMap.erase(deviceManagerWrapper->bundleName_); + g_verifyAuthCallbackMap.erase(deviceManagerWrapper->bundleName_); napi_get_undefined(env, &result); return result; } @@ -1151,7 +1555,7 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac std::string bundleName = std::string(asCallbackInfo->bundleName); std::shared_ptr initCallback = std::make_shared(bundleName); if (DeviceManager::GetInstance().InitDeviceManager(bundleName, initCallback) != 0) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager for bunderName %s failed", bundleName.c_str()); + LOGE("InitDeviceManager for bunderName %s failed", bundleName.c_str()); return; } g_initCallbackMap[bundleName] = initCallback; @@ -1160,18 +1564,18 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac [](napi_env env, napi_status status, void *data) { (void)status; AsyncCallbackInfo *asCallbackInfo = (AsyncCallbackInfo *)data; - napi_value result[DM_NAPI_ARGS_TWO] = { 0 }; + napi_value result[DM_NAPI_ARGS_TWO] = {0}; napi_value ctor = nullptr; napi_value argv = nullptr; napi_get_reference_value(env, sConstructor_, &ctor); napi_create_string_utf8(env, asCallbackInfo->bundleName, NAPI_AUTO_LENGTH, &argv); napi_status ret = napi_new_instance(env, ctor, DM_NAPI_ARGS_ONE, &argv, &result[1]); if (ret != napi_ok) { - DMLOG(DM_LOG_ERROR, "Create DeviceManagerNapi for bunderName %s failed", asCallbackInfo->bundleName); + LOGE("Create DeviceManagerNapi for bunderName %s failed", asCallbackInfo->bundleName); asCallbackInfo->status = -1; } if (asCallbackInfo->status == 0) { - DMLOG(DM_LOG_INFO, "InitDeviceManager for bunderName %s success", asCallbackInfo->bundleName); + LOGI("InitDeviceManager for bunderName %s success", asCallbackInfo->bundleName); napi_get_undefined(env, &result[0]); napi_value callback = nullptr; napi_value callResult = nullptr; @@ -1179,7 +1583,7 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac napi_call_function(env, nullptr, callback, DM_NAPI_ARGS_TWO, &result[0], &callResult); napi_delete_reference(env, asCallbackInfo->callback); } else { - DMLOG(DM_LOG_INFO, "InitDeviceManager for bunderName %s failed", asCallbackInfo->bundleName); + LOGI("InitDeviceManager for bunderName %s failed", asCallbackInfo->bundleName); napi_value message = nullptr; napi_create_object(env, &result[0]); napi_create_int32(env, asCallbackInfo->status, &message); @@ -1188,13 +1592,14 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac } napi_delete_async_work(env, asCallbackInfo->asyncWork); delete asCallbackInfo; - }, (void *)asCallbackInfo, &asCallbackInfo->asyncWork); + }, + (void *)asCallbackInfo, &asCallbackInfo->asyncWork); napi_queue_async_work(env, asCallbackInfo->asyncWork); } napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "CreateDeviceManager in"); + LOGI("CreateDeviceManager in"); GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2"); @@ -1209,7 +1614,7 @@ napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_in auto *asCallbackInfo = new AsyncCallbackInfo(); asCallbackInfo->env = env; napi_get_value_string_utf8(env, argv[0], asCallbackInfo->bundleName, DM_NAPI_BUF_LENGTH - 1, - &asCallbackInfo->bundleNameLen); + &asCallbackInfo->bundleNameLen); napi_create_reference(env, argv[1], 1, &asCallbackInfo->callback); HandleCreateDmCallBack(env, asCallbackInfo); @@ -1221,7 +1626,7 @@ napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_in napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "DeviceManagerNapi Constructor in"); + LOGI("DeviceManagerNapi Constructor in"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1"); @@ -1229,15 +1634,16 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) napi_typeof(env, argv[0], &valueType); NAPI_ASSERT(env, valueType == napi_string, "type mismatch for parameter 1"); - char bundleName[DM_NAPI_BUF_LENGTH] = { 0 }; + char bundleName[DM_NAPI_BUF_LENGTH] = {0}; size_t typeLen = 0; napi_get_value_string_utf8(env, argv[0], bundleName, sizeof(bundleName), &typeLen); - DMLOG(DM_LOG_INFO, "create DeviceManagerNapi for packageName:%s", bundleName); + LOGI("create DeviceManagerNapi for packageName:%s", bundleName); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); obj->bundleName_ = std::string(bundleName); g_deviceManagerMap[obj->bundleName_] = obj; - napi_wrap(env, thisVar, reinterpret_cast(obj), + napi_wrap( + env, thisVar, reinterpret_cast(obj), [](napi_env env, void *data, void *hint) { (void)env; (void)hint; @@ -1254,28 +1660,31 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) napi_property_descriptor dmProperties[] = { DECLARE_NAPI_FUNCTION("release", ReleaseDeviceManager), DECLARE_NAPI_FUNCTION("getTrustedDeviceListSync", GetTrustedDeviceListSync), + DECLARE_NAPI_FUNCTION("getTrustedDeviceList", GetTrustedDeviceList), DECLARE_NAPI_FUNCTION("startDeviceDiscovery", StartDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("stopDeviceDiscovery", StopDeviceDiscoverSync), + DECLARE_NAPI_FUNCTION("getLocalDeviceInfoSync", GetLocalDeviceInfoSync), + DECLARE_NAPI_FUNCTION("getLocalDeviceInfo", GetLocalDeviceInfo), + DECLARE_NAPI_FUNCTION("unAuthenticateDevice", UnAuthenticateDevice), DECLARE_NAPI_FUNCTION("authenticateDevice", AuthenticateDevice), DECLARE_NAPI_FUNCTION("verifyAuthInfo", VerifyAuthInfo), DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync), + DECLARE_NAPI_FUNCTION("getFaParam", GetAuthenticationParamSync), DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync), DECLARE_NAPI_FUNCTION("on", JsOn), - DECLARE_NAPI_FUNCTION("off", JsOff) - }; + DECLARE_NAPI_FUNCTION("off", JsOff)}; napi_property_descriptor static_prop[] = { DECLARE_NAPI_STATIC_FUNCTION("createDeviceManager", CreateDeviceManager), }; - DMLOG(DM_LOG_DEBUG, "DeviceManagerNapi::Init() is called!"); - NAPI_CALL(env, - napi_define_class(env, DEVICE_MANAGER_NAPI_CLASS_NAME.c_str(), NAPI_AUTO_LENGTH, Constructor, nullptr, - sizeof(dmProperties) / sizeof(dmProperties[0]), dmProperties, &dmClass)); + LOGD("DeviceManagerNapi::Init() is called!"); + NAPI_CALL(env, napi_define_class(env, DEVICE_MANAGER_NAPI_CLASS_NAME.c_str(), NAPI_AUTO_LENGTH, Constructor, + nullptr, sizeof(dmProperties) / sizeof(dmProperties[0]), dmProperties, &dmClass)); NAPI_CALL(env, napi_create_reference(env, dmClass, 1, &sConstructor_)); NAPI_CALL(env, napi_set_named_property(env, exports, DEVICE_MANAGER_NAPI_CLASS_NAME.c_str(), dmClass)); NAPI_CALL(env, napi_define_properties(env, exports, sizeof(static_prop) / sizeof(static_prop[0]), static_prop)); - DMLOG(DM_LOG_INFO, "All props and functions are configured.."); + LOGI("All props and functions are configured.."); return exports; } @@ -1284,7 +1693,7 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) */ static napi_value Export(napi_env env, napi_value exports) { - DMLOG(DM_LOG_INFO, "Export() is called!"); + LOGI("Export() is called!"); DeviceManagerNapi::Init(env, exports); return exports; } @@ -1292,21 +1701,19 @@ static napi_value Export(napi_env env, napi_value exports) /* * module define */ -static napi_module g_dmModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Export, - .nm_modname = "distributedhardware.devicemanager", - .nm_priv = ((void *)0), - .reserved = {0} - }; +static napi_module g_dmModule = {.nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Export, + .nm_modname = "distributedhardware.devicemanager", + .nm_priv = ((void *)0), + .reserved = {0}}; /* * module register */ extern "C" __attribute__((constructor)) void RegisterModule(void) { - DMLOG(DM_LOG_INFO, "RegisterModule() is called!"); + LOGI("RegisterModule() is called!"); napi_module_register(&g_dmModule); } diff --git a/ohos.build b/ohos.build index f544c0dcc..59995c055 100644 --- a/ohos.build +++ b/ohos.build @@ -12,8 +12,7 @@ "device_manager.h", "device_manager_callback.h", "dm_device_info.h", - "dm_subscribe_info.h", - "dm_app_image_info.h" + "dm_subscribe_info.h" ] } } @@ -23,7 +22,9 @@ "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager_native_js", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice:devicemanagerservice", - "//foundation/distributedhardware/devicemanager/sa_profile:dm_sa_profile" + "//foundation/distributedhardware/devicemanager/sa_profile:dm_sa_profile", + "//foundation/distributedhardware/devicemanager/ext/pin_auth:devicemanagerext_pin_auth", + "//foundation/distributedhardware/devicemanager/ext/profile:devicemanagerext_profile" ], "test_list": [ "//foundation/distributedhardware/devicemanager/test:test" diff --git a/sa_profile/4802.xml b/sa_profile/4802.xml index 398977926..d2e77008e 100644 --- a/sa_profile/4802.xml +++ b/sa_profile/4802.xml @@ -15,12 +15,12 @@ --> foundation - + 4802 libdevicemanagerservice.z.so - - - true + + + true false 1 diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn deleted file mode 100644 index 85b8e5774..000000000 --- a/services/devicemanagerservice/BUILD.gn +++ /dev/null @@ -1,190 +0,0 @@ -# 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") - -if (defined(ohos_lite)) { - executable("devicemanagerservice") { - include_dirs = [ - "include", - "include/ability", - "include/softbus", - "include/requestauth", - "include/auth", - "include/ipc", - "include/timer", - "include/message", - "include/ipc/lite", - "${utils_path}/include/cipher", - "${utils_path}/include/log", - "${utils_path}/include/ipc/lite", - "${utils_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "${common_path}/include", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/ipc/lite", - ] - - 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/distributedschedule/samgr_lite/interfaces/kits/samgr", - ] - - sources = [ - "src/ability/lite/dm_ability_manager.cpp", - "src/auth/hichain_connector.cpp", - "src/ipc/ipc_server_adapter.cpp", - "src/ipc/ipc_server_listener_adapter.cpp", - "src/ipc/lite/ipc_cmd_parser.cpp", - "src/ipc/lite/ipc_server_listener.cpp", - "src/ipc/lite/ipc_server_listenermgr.cpp", - "src/ipc/lite/ipc_server_main.cpp", - "src/ipc/lite/ipc_server_stub.cpp", - "src/message/msg_codec.cpp", - "src/message/msg_head.cpp", - "src/message/msg_request_auth.cpp", - "src/message/msg_response_auth.cpp", - "src/message/msg_sync_group.cpp", - "src/requestauth/auth_manager.cpp", - "src/requestauth/request_session.cpp", - "src/requestauth/response_session.cpp", - "src/softbus/softbus_adapter.cpp", - "src/softbus/softbus_session.cpp", - "src/timer/dm_timer.cpp", - ] - - defines = [ - "LITE_DEVICE", - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerservice\"", - "LOG_DOMAIN=0xD004100", - ] - - ldflags = dm_ldflags - - deps = [ - "${innerkits_path}/native_cpp:devicemanagersdk", - "${utils_path}:devicemanagerutils", - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//base/security/deviceauth/services:deviceauth_sdk", - "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", - "//foundation/communication/dsoftbus/sdk:softbus_client", - "//foundation/communication/ipc_lite:liteipc_adapter", - "//foundation/distributedschedule/samgr_lite/samgr:samgr", - "//third_party/bounds_checking_function:libsec_shared", - "//third_party/mbedtls:mbedtls_shared", - "//utils/native/lite:utils", - ] - } -} else { - ohos_shared_library("devicemanagerservice") { - include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "include", - "include/ability", - "include/softbus", - "include/requestauth", - "include/auth", - "include/ipc", - "include/message", - "include/timer", - "include/ipc/standard", - "${utils_path}/include/cipher", - "${utils_path}/include/log", - "${utils_path}/include", - "${utils_path}/include/ipc/standard", - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/ipc/standard", - "//base/security/deviceauth/interfaces/innerkits", - "//base/startup/syspara_lite/adapter/native/syspara/include", - "//third_party/json/include", - ] - - sources = [ - "src/ability/standard/dm_ability_manager.cpp", - "src/auth/hichain_connector.cpp", - "src/ipc/ipc_server_adapter.cpp", - "src/ipc/ipc_server_listener_adapter.cpp", - "src/ipc/standard/ipc_cmd_parser.cpp", - "src/ipc/standard/ipc_server_client_proxy.cpp", - "src/ipc/standard/ipc_server_listener.cpp", - "src/ipc/standard/ipc_server_stub.cpp", - "src/message/msg_codec.cpp", - "src/message/msg_head.cpp", - "src/message/msg_request_auth.cpp", - "src/message/msg_response_auth.cpp", - "src/message/msg_sync_group.cpp", - "src/requestauth/auth_manager.cpp", - "src/requestauth/request_session.cpp", - "src/requestauth/response_session.cpp", - "src/softbus/softbus_adapter.cpp", - "src/softbus/softbus_session.cpp", - "src/timer/dm_timer.cpp", - ] - - deps = [ - "${innerkits_path}/native_cpp:devicemanagersdk", - "${utils_path}:devicemanagerutils", - "//base/security/deviceauth/services:deviceauth_sdk", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//utils/native/base:utils", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerservice\"", - "LOG_DOMAIN=0xD004100", - ] - - external_deps = [ - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", - "dsoftbus_standard:softbus_client", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - "startup_l2:syspara", - ] - - subsystem_name = "distributedhardware" - - part_name = "device_manager_base" - } -} diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h deleted file mode 100644 index 17a9337d5..000000000 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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_ABILITY_MANAGER_H -#define OHOS_DM_ABILITY_MANAGER_H - -#include -#include -#include -#include - -#include "single_instance.h" - -namespace OHOS { -namespace DistributedHardware { -enum AbilityRole : int32_t { - ABILITY_ROLE_PASSIVE = 0, - ABILITY_ROLE_INITIATIVE = 1, - ABILITY_ROLE_UNKNOWN = 2 -}; - -enum AbilityStatus : int32_t { - ABILITY_STATUS_FAILED = 0, - ABILITY_STATUS_SUCCESS = 1, - ABILITY_STATUS_START = 2 -}; - -typedef enum FaAction { - USER_OPERATION_TYPE_ALLOW_AUTH = 0, - USER_OPERATION_TYPE_CANCEL_AUTH = 1, - USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT = 2, - USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY = 3, - USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT = 4 -} FaAction; - -class DmAbilityManager { -DECLARE_SINGLE_INSTANCE(DmAbilityManager); -public: - AbilityRole GetAbilityRole(); - AbilityStatus StartAbility(AbilityRole role); - void StartAbilityDone(); - -private: - void waitForTimeout(uint32_t timeout_s); - -private: - sem_t mSem_; - AbilityStatus mStatus_; - AbilityRole mAbilityStatus_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif diff --git a/services/devicemanagerservice/include/auth/hichain_connector.h b/services/devicemanagerservice/include/auth/hichain_connector.h deleted file mode 100644 index e49700c97..000000000 --- a/services/devicemanagerservice/include/auth/hichain_connector.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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_HICHAIN_CONNECTOR_H -#define OHOS_HICHAIN_CONNECTOR_H - -#include -#include -#include - -#include "nlohmann/json.hpp" - -#include "device_auth.h" - -#include "single_instance.h" -#include "msg_response_auth.h" - -namespace OHOS { -namespace DistributedHardware { -enum { - HICHAIN_SUCCESS = 0, - GROUP_CREATE_FAILED = 1, - MEMBER_ADD_FAILED = 2, - CREATE_CHANNEL_FAILED = 3, -}; - -struct GroupInfo { - std::string groupName; - std::string groupId; - std::string groupOwner; - int32_t groupType; - int32_t groupVisibility; - - GroupInfo() : groupName(""), groupId(""), groupOwner(""), groupType(0), groupVisibility(0) {} -}; - -void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo); - -class HichainConnectorCallback { -public: - virtual void OnGroupCreated(int64_t requestId, const std::string &groupId) = 0; - virtual void OnMemberJoin(int64_t requestId, int32_t status) = 0; -}; - -class HichainAuthenCallBack { -public: - static bool onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - static void onSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); - 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); -}; - -class HichainConnector { -DECLARE_SINGLE_INSTANCE(HichainConnector); -public: - int32_t Init(); - bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - int64_t GenRequestId(); - void RegisterConnectorCallback(std::shared_ptr callback); - int32_t CreateGroup(int64_t requestId, const std::string &groupName); - int32_t AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth); - void GetRelatedGroups(std::string DeviceId, std::vector &groupList); - void SyncGroups(std::string deviceId, std::vector &remoteGroupIdList); - int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); - void DeleteGroup(std::string &groupId); - void OnGroupCreated(int64_t requestId, const std::string &returnData); - void GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList); - void OnMemberJoin(int64_t requestId, int32_t status); - int32_t GetGroupInfo(std::string queryParams, std::vector &groupList); - int32_t IsGroupCreated(std::string groupName, GroupInfo &groupInfo); - -private: - std::string GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth); - bool IsGroupInfoInvalid(GroupInfo &group); - -private: - std::shared_ptr hichainConnectorCallback_ = nullptr; - const DeviceGroupManager *deviceGroupManager_ = nullptr; - DeviceAuthCallback deviceAuthCallback_ ; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_HICHAIN_ADAPTER_H diff --git a/services/devicemanagerservice/include/ipc/ipc_server_adapter.h b/services/devicemanagerservice/include/ipc/ipc_server_adapter.h deleted file mode 100644 index deec8bfee..000000000 --- a/services/devicemanagerservice/include/ipc/ipc_server_adapter.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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_IPC_SERVER_ADAPTER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H - -#include - -#include "dm_app_image_info.h" -#include "dm_device_info.h" -#include "dm_subscribe_info.h" - -#include "hichain_connector.h" - -#include "single_instance.h" -#include "softbus_adapter.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcServerAdapter { -DECLARE_SINGLE_INSTANCE(IpcServerAdapter); -public: - int32_t ModuleInit(); - int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, DmDeviceInfo **info, int32_t *infoNum); - int32_t StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &dmSubscribeInfo); - int32_t StopDiscovery(std::string &pkgName, uint16_t subscribeId); - int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra); - int32_t CheckAuthentication(std::string &authPara); - int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam); - int32_t SetUserOperation(std::string &pkgName, int32_t action); - static int32_t GenRandInt(int32_t minPinToken, int32_t maxPinToken); -private: - int32_t CheckParamValid(nlohmann::json &extraJson, const DmAppImageInfo &imageInfo); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H diff --git a/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h b/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h deleted file mode 100644 index b812eca27..000000000 --- a/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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_IPC_SERVER_LISTENER_ADAPTER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H - -#include "discovery_service.h" - -#include "ipc_server_listener.h" - -#include "single_instance.h" -#include "dm_device_info.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcServerListenerAdapter { -DECLARE_SINGLE_INSTANCE(IpcServerListenerAdapter); -public: - void OnDeviceStateChange(DmDeviceState state, DmDeviceInfo &deviceInfo); - void OnDeviceFound(std::string &pkgName, uint16_t originId, DmDeviceInfo &deviceInfo); - void OnDiscoverFailed(std::string &pkgName, uint16_t originId, DiscoveryFailReason failReason); - void OnDiscoverySuccess(std::string &pkgName, uint16_t originId); - void OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, uint32_t status, uint32_t reason); - void OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag); - void OnFaCall(std::string &pkgName, std::string ¶mJson); -private: - IpcServerListener ipcServerListener_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h deleted file mode 100644 index 9503191aa..000000000 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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_IPC_SERVER_LISTENER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H - -#include - -#include "ipc_req.h" -#include "ipc_rsp.h" - -#include "ipc_server_listenermgr.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcServerListener { -public: - IpcServerListener() = default; - virtual ~IpcServerListener() = default; -public: - int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); -private: - void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity); - int32_t GetIdentityByPkgName(std::string &name, SvcIdentity *svc); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h deleted file mode 100644 index 26d2ee114..000000000 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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_IPC_SERVER_LISTENER_MGR_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H - -#include -#include -#include -#include - -#include "liteipc_adapter.h" -#include "single_instance.h" - -namespace OHOS { -namespace DistributedHardware { -typedef struct CommonSvcId { - uint32_t handle; - uint32_t token; - uint32_t cookie; - IpcContext *ipcCtx; - uint32_t cbId; -}CommonSvcId; - -class IpcServerListenermgr { -DECLARE_SINGLE_INSTANCE(IpcServerListenermgr); -public: - int32_t RegisterListener(std::string &pkgName, const CommonSvcId *svcId); - int32_t GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId); - int32_t UnregisterListener(std::string &pkgName); - const std::map &GetAllListeners(); -private: - std::map dmListenerMap_; - std::mutex lock_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h deleted file mode 100644 index 9baa73d4a..000000000 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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_IPC_SERVER_STUB_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H - -#include - -#include "liteipc_adapter.h" - -int32_t IpcServerStubInit(void); -int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply); -int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply); -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h deleted file mode 100644 index 15b5e44a4..000000000 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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_IPC_SERVER_CLIENT_PROXY_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H - -#include "ipc_remote_broker.h" -#include "iremote_proxy.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcServerClientProxy : public IRemoteProxy { -public: - explicit IpcServerClientProxy(const sptr &impl) - : IRemoteProxy(impl) {}; - ~IpcServerClientProxy() {}; - int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; -private: - static inline BrokerDelegator delegator_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h deleted file mode 100644 index 3737b7cde..000000000 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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_IPC_SERVER_LISTENER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H - -#include - -#include "ipc_req.h" -#include "ipc_rsp.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcServerListener { -public: - IpcServerListener() = default; - virtual ~IpcServerListener() = default; -public: - int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h deleted file mode 100644 index 4e653eb97..000000000 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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_IPC_SERVER_STUB_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H - -#include -#include -#include -#include -#include - -#include "nlohmann/json.hpp" - -#include "system_ability.h" -#include "thread_pool.h" -#include "iremote_stub.h" -#include "ipc_remote_broker.h" - -#include "single_instance.h" -#include "hichain_connector.h" - -namespace OHOS { -namespace DistributedHardware { -enum class ServiceRunningState { - STATE_NOT_START, - STATE_RUNNING -}; - -class AppDeathRecipient : public IRemoteObject::DeathRecipient { -public: - void OnRemoteDied(const wptr &remote) override; - AppDeathRecipient() = default; - ~AppDeathRecipient() = default; -}; - -class IpcServerStub : public SystemAbility, public IRemoteStub { -DECLARE_SYSTEM_ABILITY(IpcServerStub); -DECLARE_SINGLE_INSTANCE_BASE(IpcServerStub); -public: - void OnStart() override; - void OnStop() override; - int32_t OnRemoteRequest(uint32_t code, - MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; - int32_t RegisterDeviceManagerListener(std::string &pkgName, sptr listener); - int32_t UnRegisterDeviceManagerListener(std::string &pkgName); - ServiceRunningState QueryServiceState() const; - const std::map> &GetDmListener(); - const sptr GetDmListener(std::string pkgName) const; -private: - IpcServerStub(); - ~IpcServerStub() = default; - bool Init(); -private: - bool registerToService_; - ServiceRunningState state_; - std::mutex listenerLock_; - std::map> appRecipient_; - std::map> dmListener_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/message/msg_codec.h b/services/devicemanagerservice/include/message/msg_codec.h deleted file mode 100644 index b0b088047..000000000 --- a/services/devicemanagerservice/include/message/msg_codec.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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_MSG_CODEC_H -#define OHOS_MSG_CODEC_H - -#include -#include - -#include "nlohmann/json.hpp" - -#include "msg_request_auth.h" -#include "msg_sync_group.h" -#include "msg_response_auth.h" - -namespace OHOS { -namespace DistributedHardware { -class MsgCodec { -public: - static int32_t DecodeMsgType(std::string &jsonStr); - static std::string EncodeSyncGroup(std::vector &groupIdList, std::string &deviceId); - static std::vector EncodeReqAppAuth(std::string &token, std::string hostPkg, std::string targetPkg, - const DmDeviceInfo &devReqInfo, const DmAppImageInfo &imageInfo, std::string &extras); - static std::string EncodeAcceptRespAuth(int32_t reply, int64_t requestId, std::string &groupId, - std::string &groupName, std::string &reqDeviceId); - static std::string EncodeRefuseRespAuth(int32_t reply, std::string &reqDeviceId); - static std::shared_ptr DecodeRequestAuth(std::string &jsonStr, - std::shared_ptr msgRequestAuth); - static std::shared_ptr DecodeResponseAuth(std::string &jsonStr); - static std::shared_ptr DecodeSyncGroup(std::string &jsonStr); -}; -} -} -#endif diff --git a/services/devicemanagerservice/include/message/msg_head.h b/services/devicemanagerservice/include/message/msg_head.h deleted file mode 100644 index b79b99f3e..000000000 --- a/services/devicemanagerservice/include/message/msg_head.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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_MSG_HEAD_H -#define OHOS_MSG_HEAD_H - -#include "nlohmann/json.hpp" - -namespace OHOS { -namespace DistributedHardware { -enum DmMsgType : int32_t { - MSG_TYPE_UNKNOWN = 0, - MSG_TYPE_REQ_AUTH = 100, - MSG_TYPE_INVITE_AUTH_INFO = 102, - MSG_TYPE_RESP_AUTH = 200, - MSG_TYPE_JOIN_AUTH_INFO = 201, - MSG_TYPE_CHANNEL_CLOSED = 300, - MSG_TYPE_SYNC_GROUP = 400, - MSG_TYPE_AUTH_BY_PIN = 500, -}; - -class MsgHead { -public: - MsgHead(): mMsgType_(0), mItfVer_("") {}; - MsgHead(int32_t msg): mMsgType_(msg), mItfVer_("") {}; - ~MsgHead() = default; - void Encode(nlohmann::json &json); - static std::shared_ptr Decode(nlohmann::json &json); - int32_t GetMsgType(); -private: - int32_t mMsgType_; - std::string mItfVer_; -}; -} -} -#endif \ No newline at end of file diff --git a/services/devicemanagerservice/include/message/msg_request_auth.h b/services/devicemanagerservice/include/message/msg_request_auth.h deleted file mode 100644 index 2af901915..000000000 --- a/services/devicemanagerservice/include/message/msg_request_auth.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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_MSG_REQUEST_AUTH_H -#define OHOS_MSG_REQUEST_AUTH_H - -#include -#include - -#include "nlohmann/json.hpp" - -#include "msg_head.h" -#include "dm_app_image_info.h" -#include "dm_device_info.h" -#include "constants.h" - -namespace OHOS { -namespace DistributedHardware { -class MsgRequestAuth { -public: - MsgRequestAuth() = default; - ~MsgRequestAuth() = default; - MsgRequestAuth(std::string &token, std::string hostPkgName, std::string targetPkgName, - const DmDeviceInfo &devReqInfo, const DmAppImageInfo &imageInfo, std::string &extras) : MsgRequestAuth( - token, hostPkgName, targetPkgName, GROUP_VISIBILITY_IS_PRIVATE, devReqInfo, imageInfo, extras) {}; - MsgRequestAuth(std::string &token, std::string hostPkgName, std::string targetPkgName, - const int32_t groupVisibility, const DmDeviceInfo &devReqInfo, const DmAppImageInfo &imageInfo, - std::string &extras); - std::vector Encode(); - static std::shared_ptr Decode(nlohmann::json &json, std::shared_ptr msgIn); - static void SetThumbnailSize(nlohmann::json &json, std::shared_ptr msg); - int32_t GetMsgSlice(); - int32_t GetMsgCnt(); - std::string GetRequestDeviceId(); -public: - std::shared_ptr mHead_ {nullptr}; - std::string mHostPkg_; - std::string mTargetPkg_; - std::string mDeviceName_; - std::string mToken_; - std::string mDeviceId_; - std::string mDeviceType_; - std::string mAppName_; - std::string mAppDescription_; - int32_t mAuthType_ {AUTH_TYPE_PIN}; - int32_t mGroupVisibility_ {GROUP_VISIBILITY_IS_PRIVATE}; - int32_t mMsgSlice_ {0}; - int32_t mMsgCnt_ {0}; - int32_t mThumbnailSize_ {0}; - int32_t mAppIconSize_ {0}; - DmAppImageInfo mImageInfo_; -private: - std::string ToHexString(int32_t value); - std::string EncodeDevInfo(); - static void DecodeDeviceInfo(nlohmann::json &json, std::shared_ptr msg); - int32_t GetEncodedAppInfo(const uint8_t *dataSrc, int32_t srcLen, std::string &outString); - void GetDecodeAppInfo(const std::string appString, uint8_t **outBuffer, int32_t &outBufferLen); - static bool IsMsgValid(std::shared_ptr msgIn, nlohmann::json &json, std::string &deviceId, - int32_t index); - static bool IsAppInfoValid(nlohmann::json &json); - static void SetAuthType(nlohmann::json &json, std::shared_ptr msg); -}; -} -} - - -#endif diff --git a/services/devicemanagerservice/include/message/msg_response_auth.h b/services/devicemanagerservice/include/message/msg_response_auth.h deleted file mode 100644 index cec27b713..000000000 --- a/services/devicemanagerservice/include/message/msg_response_auth.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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_MSG_RESPONSE_AUTH_H -#define OHOS_MSG_RESPONSE_AUTH_H - -#include -#include - -#include "constants.h" -#include "nlohmann/json.hpp" - -#include "msg_head.h" - -namespace OHOS { -namespace DistributedHardware { -class MsgResponseAuth { -public: - MsgResponseAuth() = default; - MsgResponseAuth(int32_t reply, std::string &reqDeviceId); - MsgResponseAuth(int32_t reply, int64_t requestId, std::string &groupId, std::string &groupName, - std::string &reqDeviceId); - ~MsgResponseAuth() = default; - void Encode(nlohmann::json &jsonObj); - int32_t Decode(nlohmann::json &jsonObj); - int32_t GetReply(); - std::string GetNetId(); - std::string GetGroupId(); - std::string GetDeviceId(); - std::string GetGroupName(); - int32_t GetPinCode(); - void SavePinCode(int32_t pinCode); - int64_t GetRequestId(); - std::vector GetSyncGroupList(); -private: - std::shared_ptr mHead_ {nullptr}; - int32_t mReply_ {SESSION_REPLY_UNKNOWN}; - std::string mNetId_; - std::string mGroupId_; - std::string mGroupName_; - std::string mDeviceId_; - int32_t mPinCode_ {-1}; - int64_t mRequestId_ {-1}; - std::vector mSyncGroupList_; -}; -} -} -#endif diff --git a/services/devicemanagerservice/include/message/msg_sync_group.h b/services/devicemanagerservice/include/message/msg_sync_group.h deleted file mode 100644 index a19d8ff54..000000000 --- a/services/devicemanagerservice/include/message/msg_sync_group.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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_MSG_SYNC_GROUP_H -#define OHOS_MSG_SYNC_GROUP_H - -#include -#include - -#include "nlohmann/json.hpp" - -#include "msg_head.h" - -namespace OHOS { -namespace DistributedHardware { -class MsgSyncGroup { -public: - MsgSyncGroup() {}; - MsgSyncGroup(std::vector &groupList, std::string &deviceId); - ~MsgSyncGroup() = default; - void Encode(nlohmann::json &json); - int32_t Decode(nlohmann::json &json); - std::string GetDeviceId(); - std::vector GetGroupIdList(); - -private: - std::shared_ptr mHead_; - std::string mDeviceId_; - std::vector mGroupIdList_; -}; -} -} -#endif \ No newline at end of file diff --git a/services/devicemanagerservice/include/requestauth/auth_manager.h b/services/devicemanagerservice/include/requestauth/auth_manager.h deleted file mode 100644 index 0fb99a70f..000000000 --- a/services/devicemanagerservice/include/requestauth/auth_manager.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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_AUTH_MANAGER_H -#define OHOS_AUTH_MANAGER_H - -#include -#include - -#include "nlohmann/json.hpp" - -#include "single_instance.h" -#include "dm_device_info.h" -#include "dm_app_image_info.h" -#include "request_session.h" -#include "response_session.h" - -namespace OHOS { -namespace DistributedHardware { -class AuthManager { - DECLARE_SINGLE_INSTANCE(AuthManager); -public: - void AuthDeviceGroup(std::string &hostPkgName, const DmDeviceInfo &devReqInfo, const DmAppImageInfo &imageInfo, - std::string &extras); - void OnReceiveMsg(long long channelId, std::string &message); - int32_t CheckAuthentication(std::string &authPara); - int32_t GetAuthenticationParam(DmAuthParam &authParam); - void OnUserOperate(int32_t action); - int32_t GetPincode(int64_t requestId); - std::string GetAuthPara(); - int32_t GetDisplayOwner(); - void NotifyHostOnCheckAuthResult(int64_t requestId, int errorCode); - -private: - void SyncDmPrivateGroup(std::string &message); - void AuthAppGroup(std::string &hostPkgName, const DmDeviceInfo &devReqInfo, const DmAppImageInfo &imageInfo, - std::string &extrasJson); - void OnReceiveMessage(long long channelId, std::string &message, int32_t msgType); - bool CanStartNewSession(); - void MoveSessionToWaitScanMap(); - int32_t CheckAuthenticationByPin(nlohmann::json &authJson); - void OnPinInputResult(int32_t pinCode, int32_t pinToken); - -private: - std::string authParam_ = ""; - int32_t displayOwner_ = 0; - std::shared_ptr mPendingReqSessionPtr_ {nullptr}; - std::shared_ptr mPendingRespSessionPtr {}; - std::map> mWaitScanReqSessionMap_ = {}; -}; -} -} -#endif diff --git a/services/devicemanagerservice/include/requestauth/request_session.h b/services/devicemanagerservice/include/requestauth/request_session.h deleted file mode 100644 index b08b81ce6..000000000 --- a/services/devicemanagerservice/include/requestauth/request_session.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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_REQUEST_SESSION_H -#define OHOS_REQUEST_SESSION_H - -#include -#include - -#include "single_instance.h" -#include "dm_app_image_info.h" -#include "dm_device_info.h" -#include "msg_response_auth.h" - -namespace OHOS { -namespace DistributedHardware { -class RequestSession { -public: - RequestSession(std::string &hostPkgName, std::string &targetPkgName, const DmDeviceInfo &devReqInfo, - const DmAppImageInfo &imageInfo); - ~RequestSession() = default; - std::vector GetRequestCommand(std::string &extrasJson); - int32_t GetPinToken(); - void SetChannelId(long long channelId); - void Release(); - bool IsFinished(); - bool IsMyChannelId(long long channelId); - void OnReceiveMsg(std::string &msg); - bool IsWaitingForScan(); - std::string GetToken(); - bool IsMyPinToken(int32_t pinToken); - void OnReceivePinCode(int32_t pinCode); - void NotifyHostAppAuthResult(int32_t errorCode); - void OnUserOperate(int32_t action); - int64_t GetRequestId(); - std::string GetRequestDeviceId(); - -private: - int32_t StartFaService(); - std::string GetHostPkgName(); - std::string GetTargetPkgName(); - int32_t GetSessionType(); - void CloseChannel(); - int32_t ParseRespMsg(std::string &msg); - void SyncDmPrivateGroup(std::vector &remoteGroupList); - -private: - enum StatusType : int32_t { - STATUS_INIT = 0, - STATUS_WAITING_REPLY = 2, - STATUS_WATING_SCAN_OR_INPUT = 3, - STATUS_WAITING_ADD_GROUP = 4, - STATUS_FINISH = 6, - }; - int32_t mSessionType_ {SESSION_TYPE_IS_APP_AUTH}; - int32_t mStatus_ {StatusType::STATUS_INIT}; - std::string mHostPkgName_; - std::string mTargetPkgName; - std::string mToken_; - int32_t mPinToken_ {MIN_PIN_TOKEN}; - DmDeviceInfo mDevInfo_; - DmAppImageInfo mImageInfo_; - long long mChannelId_ {-1}; - bool mIsChannelOpened_ {false}; - std::string mRemoteDeviceId_; - std::string mRemoteNetId_; - std::string mRemoteGroupId_; - std::string mRemoteGroupName_; - int64_t mRequestId_ {-1}; - std::shared_ptr responseMsgPtr_; -}; -} -} -#endif diff --git a/services/devicemanagerservice/include/requestauth/response_session.h b/services/devicemanagerservice/include/requestauth/response_session.h deleted file mode 100644 index ee80835b2..000000000 --- a/services/devicemanagerservice/include/requestauth/response_session.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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_RESPONSE_SESSION_H -#define OHOS_RESPONSE_SESSION_H - -#include -#include -#include -#include - -#include "single_instance.h" -#include "dm_device_info.h" -#include "msg_response_auth.h" -#include "msg_request_auth.h" -#include "hichain_connector.h" -#include "dm_timer.h" - -namespace OHOS { -namespace DistributedHardware { -enum ResponseSessionStatus : int32_t { - SESSION_INIT = 0, - SESSION_WAITTING_USER_CONFIRM = 1, - SESSION_WAITTING_GROUP_CREATED = 2, - SESSION_WAITTING_PIN_CODE = 3 -}; - -class ResponseSession : public HichainConnectorCallback, public std::enable_shared_from_this { -public: - ResponseSession(); - virtual ~ResponseSession() {}; - int32_t SendResponseMessage(int32_t reply); - void OnUserOperate(int32_t action); - void OnGroupCreated(int64_t requestId, const std::string &groupId) override; - void OnMemberJoin(int64_t requestId, int32_t status) override; - void BuildAuthenticationInfo(DmAuthParam &authParam); - void OnReceiveMsg(long long channelId, std::string &message); - int64_t GetRequestId(); - int32_t GetPinCodeByReqId(int64_t requestId); - bool IsMyChannelId(long long channelId); - void Release(); - void CancelDisplay(); - int32_t GetStatus(); - -private: - int32_t DecodeReqMsg(std::string &message); - int32_t StartFaService(); - std::string GenerateGroupName(); - void OnUserConfirm(); - void OnUserReject(int32_t errorCode); - int32_t GeneratePincode(); - -private: - int64_t mRequestId_; - std::string mGroupId_; - std::string mGroupName_; - std::string mReqDeviceId_; - sem_t mSem_; - std::shared_ptr mMsgRequestAuthPtr_; - int64_t mChannelId_; - int32_t mPincode_; - int32_t mSessionStatus_; - std::shared_ptr mReceiveTimerPtr_; - std::shared_ptr mMemberJoinTimerPtr_; -}; -} // namespace DistributedHardware -} // namespace OHOS - - -#endif diff --git a/services/devicemanagerservice/include/softbus/softbus_adapter.h b/services/devicemanagerservice/include/softbus/softbus_adapter.h deleted file mode 100644 index 25f472ff3..000000000 --- a/services/devicemanagerservice/include/softbus/softbus_adapter.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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_SOFTBUS_ADAPTER_H -#define OHOS_DEVICE_MANAGER_SOFTBUS_ADAPTER_H - -#include -#include -#include -#include -#include -#include "softbus_bus_center.h" -#include "discovery_service.h" -#include "dm_device_info.h" -#include "dm_subscribe_info.h" - -namespace OHOS { -namespace DistributedHardware { -class PublishServiceCallBack { -public: - static void OnPublishSuccess(int32_t publishId); - static void OnPublishFail(int32_t publishId, PublishFailReason reason); -}; - -class SoftbusAdapter { -public: - static int32_t Init(); - static int32_t GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum); - static int32_t StartDiscovery(std::string &pkgName, SubscribeInfo *info); - static int32_t StopDiscovery(std::string &pkgName, uint16_t subscribeId); - static bool IsDeviceOnLine(std::string &deviceId); - static int32_t GetConnectionIpAddr(std::string deviceId, std::string &ipAddr); - static ConnectionAddr *GetConnectAddr(std::string deviceId); -public: - 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 OnSoftbusDiscoverFailed(int32_t subscribeId, DiscoveryFailReason failReason); - static void OnSoftbusDiscoverySuccess(int32_t subscribeId); -private: - static bool GetsubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId); - static bool GetpkgNameBySubscribeId(int32_t adapterId, std::string &pkgName); - static void SaveDiscoverDeviceInfo(const DeviceInfo *deviceInfo); - static void RemoveDiscoverDeviceInfo(const std::string deviceId); - static void NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo); - static void DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo); - static ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); -private: - struct SubscribeInfoAdapter { - SubscribeInfo info; - uint16_t subscribeIdOrigin; - uint16_t subscribeIdPrefix; - }; - static std::map>> subscribeInfos_; - static std::map> discoverDeviceInfoMap_; - static std::vector> discoverDeviceInfoVector_; - static uint16_t subscribeIdPrefix; - static std::mutex lock_; - static INodeStateCb softbusNodeStateCb_; - static IDiscoveryCallback softbusDiscoverCallback_; - static IPublishCallback servicePublishCallback_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_SOFTBUS_ADAPTER_H diff --git a/services/devicemanagerservice/include/softbus/softbus_session.h b/services/devicemanagerservice/include/softbus/softbus_session.h deleted file mode 100644 index 03610be2c..000000000 --- a/services/devicemanagerservice/include/softbus/softbus_session.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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_SOFTBUS_SESSION_H -#define OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H - -#include -#include -#include - -#include "session.h" -#include "single_instance.h" -#include "softbus_common.h" - -namespace OHOS { -namespace DistributedHardware { -class SoftbusSession { -DECLARE_SINGLE_INSTANCE_BASE(SoftbusSession); -public: - int32_t Start(); - int32_t OnSessionOpened(int32_t sessionId, int32_t result); - void OnSessionClosed(int32_t sessionId); - void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); - void CloseSession(int32_t sessionId); - int32_t SendMessages(const char *deviceId, std::vector &messages); - int32_t SendMsg(int32_t sessionId, std::string &message); - void GetPeerDeviceId(int32_t sessionId, std::string &peerDevId); -private: - SoftbusSession() = default; - ~SoftbusSession(); -private: - int32_t SendData(int32_t sessionId, const void *data, int32_t len); -private: - const char *PKG_NAME = "ohos.distributedhardware.devicemanager"; - const char *SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; - std::set sessionIdSet_; - std::vector messages_ {}; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H diff --git a/services/devicemanagerservice/include/timer/dm_timer.h b/services/devicemanagerservice/include/timer/dm_timer.h deleted file mode 100644 index 61b763e99..000000000 --- a/services/devicemanagerservice/include/timer/dm_timer.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 TIMER_H -#define TIMER_H -#include -#include -#include -#include -#include -#include -#include -#include - -#include "device_manager_log.h" - - -namespace OHOS { -namespace DistributedHardware { -typedef void (*TimeoutHandle)(void *data); - -#define MAXEVENTS 255 - -enum DmTimerStatus : int32_t { - DM_STATUS_INIT = 0, - DM_STATUS_RUNNING = 1, - DM_STATUS_BUSY = 2, - DM_STATUS_CREATE_ERROR = 3, - DM_STATUS_FINISH = 6, -}; - -class DmTimer { -public: - DmTimer(std::string &name); - ~DmTimer(); - DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data); - void Stop(int32_t code); - void WiteforTimeout(); - -private: - int32_t CreateTimeFd(); - void Release(); - -private: - DmTimerStatus mStatus_; - uint32_t mTimeOutSec_; - TimeoutHandle mHandle_; - void *mHandleData_; - int32_t mTimeFd_[2]; - struct epoll_event mEv_; - struct epoll_event mEvents_[MAXEVENTS]; - int32_t mEpFd_; - std::thread mThread_; - std::string mTimerName_; -}; -} -} -#endif - diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp deleted file mode 100644 index 3b5885159..000000000 --- a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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_ability_manager.h" - -#include "semaphore.h" - -#include "constants.h" -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(DmAbilityManager); - -AbilityRole DmAbilityManager::GetAbilityRole() -{ - return mAbilityStatus_; -} - -AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) -{ - // not support for L1 yet, do nothing. jsut save status and role - mAbilityStatus_ = role; - mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; - return mStatus_; -} - -void DmAbilityManager::waitForTimeout(uint32_t timeout_s) -{ - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - ts.tv_sec += timeout_s; - sem_timedwait(&mSem_, &ts); -} - -void DmAbilityManager::StartAbilityDone() -{ - mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; - sem_post(&mSem_); -} -} -} diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp deleted file mode 100644 index 8cf00eccc..000000000 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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_ability_manager.h" - -#include "auth_manager.h" -#include "ability_manager_client.h" -#include "ability_record.h" -#include "ability_manager_service.h" -#include "parameter.h" -#include "semaphore.h" - -#include "constants.h" -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { -const int32_t ABILITY_START_TIMEOUT = 3; // 3 second -} -IMPLEMENT_SINGLE_INSTANCE(DmAbilityManager); - -AbilityRole DmAbilityManager::GetAbilityRole() -{ - return mAbilityStatus_; -} - -AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) -{ - std::string roleStr; - if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { - roleStr = "initiative"; - } else if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { - roleStr = "passive"; - } else { - DMLOG(DM_LOG_ERROR, "StartAbility, failed, role unknown"); - return AbilityStatus::ABILITY_STATUS_FAILED; - } - - DMLOG(DM_LOG_ERROR, "StartAbility, role %s", roleStr.c_str()); - mAbilityStatus_ = role; - - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string deviceId = localDeviceId; - std::string bundleName = "com.ohos.devicemanagerui"; - std::string abilityName = "com.ohos.devicemanagerui.MainAbility"; - int32_t displayOwner = (role == AbilityRole::ABILITY_ROLE_INITIATIVE) ? - AuthManager::GetInstance().GetDisplayOwner() : DISPLAY_OWNER_SYSTEM; - - mStatus_ = AbilityStatus::ABILITY_STATUS_START; - AAFwk::Want want; - AppExecFwk::ElementName element(deviceId, bundleName, abilityName); - want.SetElement(element); - if (displayOwner == DISPLAY_OWNER_OTHER) { - return AbilityStatus::ABILITY_STATUS_SUCCESS; - } - AAFwk::AbilityManagerClient::GetInstance()->Connect(); - ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); - if (result == OHOS::ERR_OK) { - DMLOG(DM_LOG_INFO, "Start Ability succeed"); - } else { - DMLOG(DM_LOG_INFO, "Start Ability faild"); - mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; - return mStatus_; - } - waitForTimeout(ABILITY_START_TIMEOUT); - return mStatus_; -} - -void DmAbilityManager::waitForTimeout(uint32_t timeout_s) -{ - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - ts.tv_sec += timeout_s; - sem_timedwait(&mSem_, &ts); -} - -void DmAbilityManager::StartAbilityDone() -{ - mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; - sem_post(&mSem_); -} -} -} diff --git a/services/devicemanagerservice/src/auth/hichain_connector.cpp b/services/devicemanagerservice/src/auth/hichain_connector.cpp deleted file mode 100644 index 88516aebd..000000000 --- a/services/devicemanagerservice/src/auth/hichain_connector.cpp +++ /dev/null @@ -1,490 +0,0 @@ -/* - * 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 "hichain_connector.h" - -#include -#include -#include -#include - -#include "nlohmann/json.hpp" - -#include "parameter.h" - -#include "anonymous_string.h" -#include "device_manager_log.h" -#include "encrypt_utils.h" -#include "softbus_adapter.h" -#include "constants.h" -#include "ipc_server_listener_adapter.h" -#include "ipc_check_authenticate_req.h" -#include "softbus_session.h" -#include "auth_manager.h" -#include "ipc_server_stub.h" -#include "dm_ability_manager.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { -const std::string DEVICE_ID = "DEVICE_ID"; -const std::string WIFI_IP = "WIFI_IP"; -const std::string WIFI_PORT = "WIFI_PORT"; -const std::string BR_MAC = "BR_MAC"; -const std::string BLE_MAC = "BLE_MAC"; -const std::string ETH_IP = "ETH_IP"; -const std::string ETH_PORT = "ETH_PORT"; -const std::string DEVICE_MANAGER_APP = "ohos.distributedhardware.devicemanager"; -const std::string DEVICE_MANAGER_GROUPNAME = "DMPeerToPeerGroup"; - -const int64_t MIN_REQUEST_ID = 1000000000; -const int64_t MAX_REQUEST_ID = 9999999999; -const int32_t FIELD_EXPIRE_TIME_VALUE = 7; -} - -IMPLEMENT_SINGLE_INSTANCE(HichainConnector); - -void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) -{ - if (jsonObject.find(FIELD_GROUP_NAME) != jsonObject.end()) { - groupInfo.groupName = jsonObject.at(FIELD_GROUP_NAME).get(); - } - - if (jsonObject.find(FIELD_GROUP_ID) != jsonObject.end()) { - groupInfo.groupId = jsonObject.at(FIELD_GROUP_ID).get(); - } - - if (jsonObject.find(FIELD_GROUP_OWNER) != jsonObject.end()) { - groupInfo.groupOwner = jsonObject.at(FIELD_GROUP_OWNER).get(); - } - - if (jsonObject.find(FIELD_GROUP_TYPE) != jsonObject.end()) { - groupInfo.groupType = jsonObject.at(FIELD_GROUP_TYPE).get(); - } - - if (jsonObject.find(FIELD_GROUP_VISIBILITY) != jsonObject.end()) { - groupInfo.groupVisibility = jsonObject.at(FIELD_GROUP_VISIBILITY).get(); - } -} - -int HichainConnector::Init() -{ - DMLOG(DM_LOG_INFO, "HichainConnector::init, init device auth service."); - InitDeviceAuthService(); - - deviceGroupManager_ = GetGmInstance(); - if (deviceGroupManager_ == nullptr) { - DMLOG(DM_LOG_INFO, "HichainConnector::init, failed to init group manager!"); - return -1; - } - - deviceAuthCallback_.onTransmit = nullptr; - deviceAuthCallback_.onFinish = HichainAuthenCallBack::onFinish; - deviceAuthCallback_.onError = HichainAuthenCallBack::onError; - deviceAuthCallback_.onRequest = HichainAuthenCallBack::onRequest; - - deviceGroupManager_->regCallback(DEVICE_MANAGER_APP.c_str(), &deviceAuthCallback_); - DMLOG(DM_LOG_INFO, "HichainConnector::init, init hichain adapter success."); - return 0; -} - -int64_t HichainConnector::GenRequestId() -{ - return EncryptUtils::GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); -} - -int32_t HichainConnector::CreateGroup(int64_t requestId, const std::string &groupName) -{ - if (deviceGroupManager_ == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::CreateGroup group manager is null, requestId %lld.", requestId); - return FAIL; - } - - GroupInfo groupInfo; - if (IsGroupCreated(groupName, groupInfo)) { - DeleteGroup(groupInfo.groupId); - } - - DMLOG(DM_LOG_INFO, "HichainConnector::CreateGroup requestId %lld", requestId); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string sLocalDeviceID = localDeviceId; - - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - jsonObj[FIELD_DEVICE_ID] = sLocalDeviceID; - jsonObj[FIELD_GROUP_NAME] = groupName; - jsonObj[FIELD_USER_TYPE] = 0; - jsonObj[FIELD_GROUP_VISIBILITY] = GROUP_VISIBILITY_PUBLIC; - jsonObj[FIELD_EXPIRE_TIME] = FIELD_EXPIRE_TIME_VALUE; - int32_t ret = deviceGroupManager_->createGroup(requestId, DEVICE_MANAGER_APP.c_str(), jsonObj.dump().c_str()); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "Faild to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); - return ret; - } - - return SUCCESS; -} - -int32_t HichainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInfo) -{ - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(); - - std::vector groupList; - if (GetGroupInfo(queryParams, groupList)) { - groupInfo = groupList[0]; - return true; - } - - return false; -} - -int32_t HichainConnector::GetGroupInfo(std::string queryParams, std::vector &groupList) -{ - char *groupVec = nullptr; - uint32_t num = 0; - - int32_t ret = deviceGroupManager_->getGroupInfo(DEVICE_MANAGER_APP.c_str(), queryParams.c_str(), &groupVec, &num); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetGroupInfo faild , ret: %d.", ret); - return false; - } - - if (groupVec == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetGroupInfo faild , returnGroups is nullptr"); - return false; - } - - if (num == 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetGroupInfo group failed, groupNum is 0."); - return false; - } - - DMLOG(DM_LOG_INFO, "HichainConnector::GetGroupInfo group(%s), groupNum(%d)", groupVec, num); - std::string relatedGroups = std::string(groupVec); - deviceGroupManager_->destroyInfo(&groupVec); - nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "returnGroups parse error"); - return false; - } - - std::vector groupInfos = jsonObject.get>(); - if (groupInfos.size() == 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetGroupInfo group failed, groupInfos is empty."); - return false; - } - - groupList = groupInfos; - return true; -} - -void HichainConnector::RegisterConnectorCallback(std::shared_ptr callback) -{ - hichainConnectorCallback_ = callback; -} - -void HichainConnector::OnGroupCreated(int64_t requestId, const std::string &returnData) -{ - if (hichainConnectorCallback_ == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated hichainConnectorCallback_ not registe."); - return; - } - - nlohmann::json jsonObject = nlohmann::json::parse(returnData); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated returnData not json."); - hichainConnectorCallback_->OnGroupCreated(requestId, ""); - return; - } - - if (jsonObject.find(FIELD_GROUP_ID) == jsonObject.end()) { - DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated failed to get groupId."); - hichainConnectorCallback_->OnGroupCreated(requestId, ""); - return; - } - - std::string groupId = jsonObject.at(FIELD_GROUP_ID).get(); - DMLOG(DM_LOG_INFO, "group create success, groupId:%s.", GetAnonyString(groupId).c_str()); - hichainConnectorCallback_->OnGroupCreated(requestId, groupId); -} - -void HichainConnector::OnMemberJoin(int64_t requestId, int32_t status) -{ - AbilityRole role = DmAbilityManager::GetInstance().GetAbilityRole(); - DMLOG(DM_LOG_INFO, "HichainConnector::OnMemberJoin:: role = %d", (int32_t)role); - - if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { - AuthManager::GetInstance().NotifyHostOnCheckAuthResult(requestId, status); - return; - } - - if (hichainConnectorCallback_ == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::OnMemberJoin hichainConnectorCallback_ not registe."); - return; - } - hichainConnectorCallback_->OnMemberJoin(requestId, status); -} - -int32_t HichainConnector::AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth) -{ - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber"); - if (deviceGroupManager_ == nullptr) { - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber group manager is null."); - return -1; - } - - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string connectInfo = GetConnectPara(deviceId, msgResponseAuth); - - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_ID] = msgResponseAuth->GetGroupId(); - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - jsonObj[FIELD_PIN_CODE] = std::to_string(msgResponseAuth->GetPinCode()).c_str(); - jsonObj[FIELD_IS_ADMIN] = false; - jsonObj[FIELD_DEVICE_ID] = localDeviceId; - jsonObj[FIELD_GROUP_NAME] = msgResponseAuth->GetGroupName(); - jsonObj[FIELD_CONNECT_PARAMS] = connectInfo.c_str(); - std::string tmpStr = jsonObj.dump(); - - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber completed"); - return deviceGroupManager_->addMemberToGroup(msgResponseAuth->GetRequestId(), DEVICE_MANAGER_APP.c_str(), - tmpStr.c_str()); -} - -std::string HichainConnector::GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth) -{ - ConnectionAddr *addrInfo = SoftbusAdapter::GetConnectAddr(deviceId); - if (addrInfo == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetConnectPara addrInfo error"); - return ""; - } - - DMLOG(DM_LOG_ERROR, "HichainConnector::GetConnectPara get addrInfo"); - nlohmann::json jsonPara; - jsonPara[DEVICE_ID] = msgResponseAuth->GetDeviceId(); - if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is ETH"); - jsonPara[ETH_IP] = addrInfo->info.ip.ip; - jsonPara[ETH_PORT] = addrInfo->info.ip.port; - } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) { - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is WIFI"); - jsonPara[WIFI_IP] = addrInfo->info.ip.ip; - jsonPara[WIFI_PORT] = addrInfo->info.ip.port; - } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) { - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is br"); - jsonPara[BR_MAC] = addrInfo->info.br.brMac; - } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) { - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is ble"); - jsonPara[BLE_MAC] = addrInfo->info.ble.bleMac; - } else { - DMLOG(DM_LOG_ERROR, "HichainConnector::AddMemeber addrInfo not right"); - return ""; - } - return jsonPara.dump(); -} - -void HichainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList) -{ - DMLOG(DM_LOG_INFO, "HichainConnector::GetRelatedGroups Start to get local related groups."); - uint32_t groupNum = 0; - char *returnGroups = nullptr; - int32_t ret = deviceGroupManager_->getRelatedGroups(DEVICE_MANAGER_APP.c_str(), deviceId.c_str(), - &returnGroups, &groupNum); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups faild , ret: %d.", ret); - return; - } - - if (returnGroups == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups faild , returnGroups is nullptr"); - return; - } - - if (groupNum == 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups group failed, groupNum is 0."); - return; - } - - std::string relatedGroups = std::string(returnGroups); - nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "returnGroups parse error"); - return; - } - - std::vector groupInfos = jsonObject.get>(); - if (groupInfos.size() == 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups group failed, groupInfos is empty."); - return; - } - - groupList = groupInfos; - return; -} - -void HichainConnector::GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList) -{ - if (groupList.empty()) { - DMLOG(DM_LOG_ERROR, "groupList is empty."); - return; - } - - for (auto group : groupList) { - if (IsGroupInfoInvalid(group)) { - continue; - } - syncGroupList.push_back(group.groupId); - } -} - -bool HichainConnector::IsGroupInfoInvalid(GroupInfo &group) -{ - if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC || - group.groupOwner != DEVICE_MANAGER_APP) { - return true; - } - return false; -} - -void HichainConnector::SyncGroups(std::string deviceId, std::vector &remoteGroupIdList) -{ - std::vector groupInfoList; - GetRelatedGroups(deviceId, groupInfoList); - for (auto &groupInfo : groupInfoList) { - if (IsGroupInfoInvalid(groupInfo)) { - continue; - } - - auto iter = std::find(remoteGroupIdList.begin(), remoteGroupIdList.end(), groupInfo.groupId); - if (iter == remoteGroupIdList.end()) { - (void)DelMemberFromGroup(groupInfo.groupId, deviceId); - } - } -} - -int32_t HichainConnector::DelMemberFromGroup(std::string groupId, std::string deviceId) -{ - int64_t requestId = GenRequestId(); - DMLOG(DM_LOG_INFO, "Start to delete memeber from group, requestId %lld, deviceId %s, groupId %s", - requestId, GetAnonyString(deviceId).c_str(), GetAnonyString(groupId).c_str()); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_ID] = groupId; - jsonObj[FIELD_DELETE_ID] = deviceId; - std::string deleteParams = jsonObj.dump(); - - int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DEVICE_MANAGER_APP.c_str(), - deleteParams.c_str()); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::DelMemberFromGroup faild , ret: %d.", ret); - return ret; - } - return 0; -} - -void HichainConnector::DeleteGroup(std::string &groupId) -{ - int64_t requestId = GenRequestId(); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); - - int32_t ret = deviceGroupManager_->deleteGroup(requestId, DEVICE_MANAGER_APP.c_str(), disbandParams.c_str()); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::DeleteGroup faild , ret: %d.", ret); - } -} - -void HichainAuthenCallBack::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) -{ - std::string data = ""; - if (returnData != nullptr) { - data = std::string(returnData); - } - - DMLOG(DM_LOG_INFO, "HichainAuthenCallBack::onFinish reqId:%lld, operation:%d", requestId, operationCode); - if (operationCode == GroupOperationCode::MEMBER_JOIN) { - DMLOG(DM_LOG_INFO, "Add Member To Group success"); - HichainConnector::GetInstance().OnMemberJoin(requestId, SUCCESS); - } - - if (operationCode == GroupOperationCode::GROUP_CREATE) { - DMLOG(DM_LOG_INFO, "Create group success"); - HichainConnector::GetInstance().OnGroupCreated(requestId, data); - } - - if (operationCode == GroupOperationCode::MEMBER_DELETE) { - DMLOG(DM_LOG_INFO, "Delete Member from group success"); - } - - if (operationCode == GroupOperationCode::GROUP_DISBAND) { - DMLOG(DM_LOG_INFO, "Disband group success"); - } -} - -void HichainAuthenCallBack::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, - const char *errorReturn) -{ - (void)errorReturn; - DMLOG(DM_LOG_INFO, "HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", - requestId, operationCode, errorCode); - - if (operationCode == GroupOperationCode::MEMBER_JOIN) { - DMLOG(DM_LOG_ERROR, "Add Member To Group failed"); - HichainConnector::GetInstance().OnMemberJoin(requestId, FAIL); - } - - if (operationCode == GroupOperationCode::GROUP_CREATE) { - DMLOG(DM_LOG_ERROR, "Create group failed"); - HichainConnector::GetInstance().OnGroupCreated(requestId, "{}"); - } - - if (operationCode == GroupOperationCode::MEMBER_DELETE) { - DMLOG(DM_LOG_ERROR, "Delete Member from group failed"); - } - - if (operationCode == GroupOperationCode::GROUP_DISBAND) { - DMLOG(DM_LOG_ERROR, "Disband group failed"); - } -} - -char *HichainAuthenCallBack::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams) -{ - if (operationCode != GroupOperationCode::MEMBER_JOIN) { - DMLOG(DM_LOG_ERROR, "HichainAuthenCallBack::onRequest operationCode %d", operationCode); - return nullptr; - } - - int32_t pinCode = AuthManager::GetInstance().GetPincode(requestId); - nlohmann::json jsonObj; - if (pinCode == FAIL) { - jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED; - } else { - jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; - } - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str(); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - jsonObj[FIELD_DEVICE_ID] = localDeviceId; - - std::string jsonStr = jsonObj.dump(); - char *buffer = strdup(jsonStr.c_str()); - return buffer; -} -} -} diff --git a/services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp b/services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp deleted file mode 100644 index 584da618b..000000000 --- a/services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - * 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 "securec.h" - -#include "anonymous_string.h" -#include "auth_manager.h" -#include "constants.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "dm_ability_manager.h" -#include "encrypt_utils.h" -#include "ipc_server_adapter.h" -#include "ipc_server_listener.h" - -namespace OHOS { -namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(IpcServerAdapter); - -int32_t IpcServerAdapter::CheckParamValid(nlohmann::json &extraJson, const DmAppImageInfo &imageInfo) -{ - if (!extraJson.contains(APP_NAME_KEY) || - !extraJson.contains(APP_DESCRIPTION_KEY) || - !extraJson.contains(AUTH_TYPE)) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; - } - - std::string appName = extraJson[APP_NAME_KEY]; - std::string appDescription = extraJson[APP_DESCRIPTION_KEY]; - - if (appName.empty() || appDescription.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid app image info"); - return DEVICEMANAGER_INVALID_VALUE; - } - if (extraJson[AUTH_TYPE] != AUTH_TYPE_PIN) { - DMLOG(DM_LOG_ERROR, "invalid auth type, only support pin auth"); - return DEVICEMANAGER_INVALID_VALUE; - } - return DEVICEMANAGER_OK; -} - -int32_t IpcServerAdapter::GenRandInt(int32_t randMin, int32_t randMax) -{ - std::random_device randDevice; - std::mt19937 genRand(randDevice()); - std::uniform_int_distribution disRand(randMin, randMax); - return disRand(genRand); -} - -int32_t IpcServerAdapter::ModuleInit() -{ - if (SoftbusAdapter::Init() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "softbus adapter init failed"); - return DEVICEMANAGER_INIT_FAILED; - } - if (HichainConnector::GetInstance().Init() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "hichain connector init failed"); - return DEVICEMANAGER_INIT_FAILED; - } - return DEVICEMANAGER_OK; -} - -int32_t IpcServerAdapter::GetTrustedDeviceList(std::string &pkgName, std::string &extra, - DmDeviceInfo **info, int32_t *infoNum) -{ - if (info == nullptr || infoNum == nullptr) { - return DEVICEMANAGER_NULLPTR; - } - DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); - NodeBasicInfo *nodeInfo = nullptr; - *info = nullptr; - *infoNum = 0; - int32_t ret = SoftbusAdapter::GetTrustDevices(pkgName, &nodeInfo, infoNum); - if (ret != DEVICEMANAGER_OK || *infoNum <= 0 || nodeInfo == nullptr) { - DMLOG(DM_LOG_ERROR, "GetTrustDevices errCode:%d, num:%d", ret, *infoNum); - return ret; - } - *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (*infoNum)); - if (*info == nullptr) { - FreeNodeInfo(nodeInfo); - return DEVICEMANAGER_MALLOC_ERROR; - } - for (int32_t i = 0; i < *infoNum; ++i) { - NodeBasicInfo *nodeBasicInfo = nodeInfo + i; - DmDeviceInfo *deviceInfo = *info + i; - if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, - std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - if (memcpy_s(deviceInfo->deviceName, sizeof(deviceInfo->deviceName), nodeBasicInfo->deviceName, - std::min(sizeof(deviceInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - deviceInfo->deviceTypeId = (DMDeviceType)nodeBasicInfo->deviceTypeId; - } - FreeNodeInfo(nodeInfo); - DMLOG(DM_LOG_INFO, "success, pkgName:%s, deviceCount %d", pkgName.c_str(), *infoNum); - return DEVICEMANAGER_OK; -} - -int32_t IpcServerAdapter::StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &dmSubscribeInfo) -{ - DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), - (int32_t)dmSubscribeInfo.subscribeId); - - DMLOG(DM_LOG_INFO, "capability: %s", dmSubscribeInfo.capability); - SubscribeInfo subscribeInfo; - - subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; - subscribeInfo.mode = (DiscoverMode)dmSubscribeInfo.mode; - subscribeInfo.medium = (ExchanageMedium)dmSubscribeInfo.medium; - subscribeInfo.freq = (ExchangeFreq)dmSubscribeInfo.freq; - subscribeInfo.isSameAccount = dmSubscribeInfo.isSameAccount; - subscribeInfo.isWakeRemote = dmSubscribeInfo.isWakeRemote; - subscribeInfo.capability = dmSubscribeInfo.capability; - subscribeInfo.capabilityData = nullptr; - subscribeInfo.dataLen = 0; - return SoftbusAdapter::StartDiscovery(pkgName, &subscribeInfo); -} - -int32_t IpcServerAdapter::StopDiscovery(std::string &pkgName, uint16_t subscribeId) -{ - DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), (int32_t)subscribeId); - return SoftbusAdapter::StopDiscovery(pkgName, subscribeId); -} - -int32_t IpcServerAdapter::AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra) -{ - if (pkgName.empty() || extra.empty()) { - DMLOG(DM_LOG_ERROR, "invalid para"); - return DEVICEMANAGER_INVALID_VALUE; - } - nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice extra jsonStr error"); - return DEVICEMANAGER_INVALID_VALUE; - } - int32_t ret = CheckParamValid(jsonObject, imageInfo); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice para invalid, ret %d", ret); - return ret; - } - DMLOG(DM_LOG_INFO, "AuthenticateDevice In, pkgName: %s, deviceId %s", pkgName.c_str(), - GetAnonyString(deviceInfo.deviceId).c_str()); - - AuthManager::GetInstance().AuthDeviceGroup(pkgName, deviceInfo, imageInfo, extra); - return DEVICEMANAGER_OK; -} - -int32_t IpcServerAdapter::CheckAuthentication(std::string &authPara) -{ - if (authPara.empty()) { - DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication check authPara failed"); - return DEVICEMANAGER_INVALID_VALUE; - } - DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication"); - return AuthManager::GetInstance().CheckAuthentication(authPara); -} - -int32_t IpcServerAdapter::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) -{ - if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "invalid para"); - return DEVICEMANAGER_INVALID_VALUE; - } - - DmAbilityManager::GetInstance().StartAbilityDone(); - AuthManager::GetInstance().GetAuthenticationParam(authParam); - return DEVICEMANAGER_OK; -} - -int32_t IpcServerAdapter::SetUserOperation(std::string &pkgName, int32_t action) -{ - if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "invalid para"); - return DEVICEMANAGER_INVALID_VALUE; - } - - AuthManager::GetInstance().OnUserOperate(action); - return SUCCESS; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp b/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp deleted file mode 100644 index 2fd07e261..000000000 --- a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ipc_server_listener_adapter.h" - -#include - -#include "securec.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "anonymous_string.h" - -#include "ipc_notify_auth_result_req.h" -#include "ipc_notify_check_auth_result_req.h" -#include "ipc_notify_device_found_req.h" -#include "ipc_notify_device_state_req.h" -#include "ipc_notify_discover_result_req.h" -#include "ipc_notify_dmfa_result_req.h" - -namespace OHOS { -namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(IpcServerListenerAdapter); - -void IpcServerListenerAdapter::OnDeviceStateChange(DmDeviceState state, DmDeviceInfo &deviceInfo) -{ - DMLOG(DM_LOG_INFO, "OnDeviceStateChange"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - - pReq->SetDeviceState(state); - pReq->SetDeviceInfo(deviceInfo); - ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); -} - -void IpcServerListenerAdapter::OnDeviceFound(std::string &pkgName, uint16_t originId, - DmDeviceInfo &deviceInfo) -{ - DMLOG(DM_LOG_INFO, "call OnDeviceFound for %s, originId %d, deviceId %s", - pkgName.c_str(), originId, GetAnonyString(std::string(deviceInfo.deviceId)).c_str()); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - - pReq->SetPkgName(pkgName); - pReq->SetSubscribeId(originId); - pReq->SetDeviceInfo(deviceInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); -} - -void IpcServerListenerAdapter::OnDiscoverFailed(std::string &pkgName, uint16_t originId, - DiscoveryFailReason failReason) -{ - DMLOG(DM_LOG_INFO, "OnDiscoverFailed"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - - pReq->SetPkgName(pkgName); - pReq->SetSubscribeId(originId); - pReq->SetResult(failReason); - ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); -} - -void IpcServerListenerAdapter::OnDiscoverySuccess(std::string &pkgName, uint16_t originId) -{ - DMLOG(DM_LOG_INFO, "OnDiscoverySuccess"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - - pReq->SetPkgName(pkgName); - pReq->SetSubscribeId(originId); - pReq->SetResult(DEVICEMANAGER_OK); - ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); -} - -void IpcServerListenerAdapter::OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, - uint32_t status, uint32_t reason) -{ - DMLOG(DM_LOG_INFO, "%s, package: %s, deviceId: %s", __FUNCTION__, pkgName.c_str(), - GetAnonyString(deviceId).c_str()); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - - pReq->SetPkgName(pkgName); - pReq->SetDeviceId(deviceId); - pReq->SetPinToken(pinToken); - pReq->SetStatus(status); - pReq->SetReason(reason); - ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); -} - -void IpcServerListenerAdapter::OnCheckAuthResult(std::string &authParam, int32_t resultCode, - int32_t flag) -{ - DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", - GetAnonyString(authParam).c_str(), resultCode); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - - pReq->SetDeviceId(authParam); - pReq->SetResult(resultCode); - pReq->SetFlag(flag); - ipcServerListener_.SendAll(SERVER_CHECK_AUTH_RESULT, pReq, pRsp); -} - -void IpcServerListenerAdapter::OnFaCall(std::string &pkgName, std::string ¶mJson) -{ - DMLOG(DM_LOG_INFO, "OnFaCall in"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - - pReq->SetPkgName(pkgName); - pReq->SetJsonParam(paramJson); - ipcServerListener_.SendRequest(SERVER_DEVICEMANAGER_FA_NOTIFY, pReq, pRsp); -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp deleted file mode 100644 index b71b3edfd..000000000 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/* - * 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 "constants.h" -#include "ipc_cmd_register.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" - -#include "ipc_def.h" -#include "ipc_notify_auth_result_req.h" -#include "ipc_notify_check_auth_result_req.h" -#include "ipc_notify_device_found_req.h" -#include "ipc_notify_device_state_req.h" -#include "ipc_notify_discover_result_req.h" -#include "ipc_notify_dmfa_result_req.h" -#include "ipc_server_adapter.h" -#include "ipc_server_stub.h" - -namespace OHOS { -namespace DistributedHardware { -ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - int32_t deviceState = pReq->GetDeviceState(); - DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, pkgName.c_str()); - IpcIoPushInt32(&request, deviceState); - IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, pkgName.c_str()); - IpcIoPushUint16(&request, subscribeId); - IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - int32_t result = pReq->GetResult(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, pkgName.c_str()); - IpcIoPushUint16(&request, subscribeId); - IpcIoPushInt32(&request, result); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string deviceId = pReq->GetDeviceId(); - int32_t pinToken = pReq->GetPinToken(); - int32_t status = pReq->GetStatus(); - int32_t reason = pReq->GetReason(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, pkgName.c_str()); - IpcIoPushString(&request, deviceId.c_str()); - IpcIoPushInt32(&request, pinToken); - IpcIoPushInt32(&request, status); - IpcIoPushInt32(&request, reason); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string deviceId = pReq->GetDeviceId(); - int32_t result = pReq->GetResult(); - int32_t flag = pReq->GetFlag(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, pkgName.c_str()); - IpcIoPushString(&request, deviceId.c_str()); - IpcIoPushInt32(&request, result); - IpcIoPushInt32(&request, flag); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; -} - -ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) -{ - DMLOG(DM_LOG_INFO, "enter GetTrustedDeviceList."); - size_t len = 0; - std::string pkgName = (const char *)IpcIoPopString(&req, &len); - std::string extra = (const char *)IpcIoPopString(&req, &len); - DmDeviceInfo *info = nullptr; - int32_t infoNum = 0; - int32_t ret = IpcServerAdapter::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); - IpcIoPushInt32(&reply, infoNum); - if (infoNum > 0) { - IpcIoPushFlatObj(&reply, info, sizeof(DmDeviceInfo) * infoNum); - free(info); - } - IpcIoPushInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(REGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) -{ - int32_t errCode = RegisterDeviceManagerListener(&req, &reply); - IpcIoPushInt32(&reply, errCode); -} - -ON_IPC_SERVER_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) -{ - int32_t errCode = UnRegisterDeviceManagerListener(&req, &reply); - IpcIoPushInt32(&reply, errCode); -} - -ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) -{ - DMLOG(DM_LOG_INFO, "StartDeviceDiscovery service listener."); - size_t len = 0; - std::string pkgName = (const char *)IpcIoPopString(&req, &len); - uint32_t size = 0; - DmSubscribeInfo *pDmSubscribeInfo = (DmSubscribeInfo*)IpcIoPopFlatObj(&req, &size); - - int32_t ret = IpcServerAdapter::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo); - IpcIoPushInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) -{ - DMLOG(DM_LOG_INFO, "StopDeviceDiscovery service listener."); - size_t len = 0; - std::string pkgName = (const char *)IpcIoPopString(&req, &len); - uint16_t subscribeId = IpcIoPopUint16(&req); - int32_t ret = IpcServerAdapter::GetInstance().StopDiscovery(pkgName, subscribeId); - IpcIoPushInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) -{ - DMLOG(DM_LOG_INFO, "AuthenticateDevice service listener."); - size_t len = 0; - std::string pkgName = (const char *)IpcIoPopString(&req, &len); - size_t extraLen = 0; - std::string extra = (const char *)IpcIoPopString(&req, &extraLen); - uint32_t size; - DmDeviceInfo *deviceInfo = (DmDeviceInfo*)IpcIoPopFlatObj(&req, &size); - DmAppImageInfo imageInfo(nullptr, 0, nullptr, 0); - int32_t ret = IpcServerAdapter::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); - IpcIoPushInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(CHECK_AUTHENTICATION, IpcIo &req, IpcIo &reply) -{ - DMLOG(DM_LOG_INFO, "CheckAuthentication service listener."); - size_t authParaLen = 0; - std::string authPara = (const char *)IpcIoPopString(&req, &authParaLen); - int32_t ret = IpcServerAdapter::GetInstance().CheckAuthentication(authPara); - IpcIoPushInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) -{ - size_t len = 0; - std::string packName = (const char *)IpcIoPopString(&req, &len); - DmAuthParam authParam = {0}; - DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); - IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); - if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - IpcIoPushInt32(&reply, authParam.direction); - IpcIoPushInt32(&reply, authParam.authType); - IpcIoPushInt32(&reply, authParam.pinToken); - DMLOG(DM_LOG_DEBUG, "DeviceManagerStub::is Client so just return direction"); - return; - } - - int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); - int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); - - IpcIoPushInt32(&reply, authParam.direction); - IpcIoPushInt32(&reply, authParam.authType); - IpcIoPushString(&reply, authParam.packageName.c_str()); - IpcIoPushString(&reply, authParam.appName.c_str()); - IpcIoPushString(&reply, authParam.appDescription.c_str()); - IpcIoPushInt32(&reply, authParam.business); - IpcIoPushInt32(&reply, authParam.pincode); - IpcIoPushInt32(&reply, appIconLen); - IpcIoPushInt32(&reply, appThumbnailLen); - - if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { - IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppIcon(), appIconLen); - } - - if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { - IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppThumbnail(), appThumbnailLen); - } -} - -ON_IPC_SERVER_CMD(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo &req, IpcIo &reply) -{ - size_t len = 0; - std::string packName = (const char *)IpcIoPopString(&req, &len); - int32_t action = IpcIoPopInt32(&reply); - IpcServerAdapter::GetInstance().SetUserOperation(packName, action); - - IpcIoPushInt32(&reply, action); -} - -ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, IpcIo& request, - uint8_t *buffer, size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string packagname = pReq->GetPkgName(); - std::string paramJson = pReq->GetJsonParam(); - IpcIoPushString(&request, packagname.c_str()); - IpcIoPushString(&request, paramJson.c_str()); - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp deleted file mode 100644 index 7fe96002c..000000000 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ipc_server_listener.h" - -#include "device_manager_log.h" -#include "device_manager_errno.h" - -#include "ipc_cmd_register.h" -#include "ipc_def.h" -#include "ipc_server_listenermgr.h" -#include "ipc_server_adapter.h" - -namespace OHOS { -namespace DistributedHardware { -void IpcServerListener::CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity) -{ - identity->handle = svcId->handle; - identity->token = svcId->token; - identity->cookie = svcId->cookie; -#ifdef __LINUX__ - identity->ipcContext = svcId->ipcCtx; -#endif -} - -int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity *svc) -{ - CommonSvcId svcId; - if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "get identity failed."); - return DEVICEMANAGER_FAILED; - } - CommonSvcToIdentity(&svcId, svc); - return DEVICEMANAGER_OK; -} - -int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - std::string pkgName = req->GetPkgName(); - SvcIdentity svc; - if (GetIdentityByPkgName(pkgName, &svc) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "ondevice found callback get listener failed."); - return DEVICEMANAGER_FAILED; - } - - IpcIo io; - uint8_t data[MAX_DM_IPC_LEN] = {0}; - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_DEBUG, "SetRequest failed cmdCode:%d", cmdCode); - return DEVICEMANAGER_FAILED; - } - if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); - } - return DEVICEMANAGER_OK; -} - -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); - for (auto &kv : listenerMap) { - SvcIdentity svc; - IpcIo io; - uint8_t data[MAX_DM_IPC_LEN] = {0}; - std::string pkgName = kv.first; - - req->SetPkgName(pkgName); - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_DEBUG, "SetRequest failed cmdCode:%d", cmdCode); - continue; - } - CommonSvcId svcId = kv.second; - CommonSvcToIdentity(&svcId, &svc); - if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); - } - } - return DEVICEMANAGER_OK; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp deleted file mode 100644 index 59aec4fda..000000000 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ipc_server_listenermgr.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(IpcServerListenermgr); - -int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const CommonSvcId *svcId) -{ - if (pkgName == "" || svcId == nullptr) { - DMLOG(DM_LOG_ERROR, "invalid param"); - return DEVICEMANAGER_FAILED; - } - DMLOG(DM_LOG_INFO, "new listener register:%s", pkgName.c_str()); - std::lock_guard autoLock(lock_); - dmListenerMap_[pkgName] = *svcId; - return DEVICEMANAGER_OK; -} - -int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId) -{ - if (pkgName == "" || svcId == nullptr) { - DMLOG(DM_LOG_ERROR, "invalid param"); - return DEVICEMANAGER_FAILED; - } - std::lock_guard autoLock(lock_); - std::map::iterator iter = dmListenerMap_.find(pkgName); - if (iter == dmListenerMap_.end()) { - DMLOG(DM_LOG_ERROR, "listener not found for pkg:%s", pkgName.c_str()); - return DEVICEMANAGER_FAILED; - } - *svcId = iter->second; - return DEVICEMANAGER_OK; -} - -int32_t IpcServerListenermgr::UnregisterListener(std::string &pkgName) -{ - std::lock_guard autoLock(lock_); - dmListenerMap_.erase(pkgName); - return DEVICEMANAGER_OK; -} - -const std::map &IpcServerListenermgr::GetAllListeners() -{ - return dmListenerMap_; -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp deleted file mode 100644 index 565cfe637..000000000 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 - -#include "device_manager_log.h" -#include "device_manager_errno.h" - -#include "ipc_server_stub.h" -#include "ipc_server_adapter.h" - -using namespace OHOS::DistributedHardware; - -static void InitAll() -{ - const int32_t DM_SERVICE_INIT_DELAY = 2; - - sleep(DM_SERVICE_INIT_DELAY); - if (IpcServerStubInit() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "IpcServerStubInit failed"); - return; - } - if (IpcServerAdapter::GetInstance().ModuleInit() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "module init failed"); - return; - } - DMLOG(DM_LOG_INFO, "DM ipc server Init success"); -} - -int32_t main(int32_t argc, char *argv[]) -{ - (void)argc; - (void)argv; - InitAll(); - while (1) { - pause(); - } - return 0; -} \ No newline at end of file diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp deleted file mode 100644 index 458164274..000000000 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ipc_server_stub.h" - -#include "securec.h" - -#include "liteipc_adapter.h" -#include "ohos_init.h" -#include "samgr_lite.h" -#include "iproxy_server.h" - -#include "device_manager_log.h" -#include "device_manager_errno.h" -#include "dm_subscribe_info.h" - -#include "ipc_cmd_register.h" -#include "ipc_def.h" -#include "ipc_server_listenermgr.h" -#include "ipc_server_adapter.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 int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, void *arg) -{ - (void)context; - (void)ipcMsg; - (void)data; - if (arg == NULL) { - DMLOG(DM_LOG_ERROR, "package name is NULL."); - return DEVICEMANAGER_INVALID_PARAM; - } - CommonSvcId svcId = {0}; - std::string pkgName = (const char *)arg; - if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "not found client by package name."); - free(arg); - arg = NULL; - return DEVICEMANAGER_FAILED; - } - IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); - free(arg); - arg = NULL; -#ifdef __LINUX__ - BinderRelease(svcId.ipcCtx, svcId.handle); -#endif - SvcIdentity sid = {0}; - sid.handle = svcId.handle; - sid.token = svcId.token; - sid.cookie = svcId.cookie; - UnregisterDeathCallback(sid, svcId.cbId); - return DEVICEMANAGER_OK; -} - -int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) -{ - DMLOG(DM_LOG_INFO, "register service listener."); - size_t len = 0; - uint8_t *name = IpcIoPopString(req, &len); - SvcIdentity *svc = IpcIoPopSvc(req); - if (name == NULL || svc == NULL || len == 0) { - DMLOG(DM_LOG_ERROR, "get para failed"); - return DEVICEMANAGER_INVALID_PARAM; - } - - CommonSvcId svcId = {0}; - svcId.handle = svc->handle; - svcId.token = svc->token; - svcId.cookie = svc->cookie; - - SvcIdentity sid = *svc; -#ifdef __LINUX__ - svcId.ipcCtx = svc->ipcContext; - BinderAcquire(svcId.ipcCtx, svcId.handle); - free(svc); - svc = NULL; -#endif - char *pkgName = (char *)malloc(len + 1); - if (pkgName == NULL) { - DMLOG(DM_LOG_ERROR, "malloc failed!"); - return DEVICEMANAGER_MALLOC_ERROR; - } - if (strcpy_s(pkgName, len + 1, (const char *)name) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "strcpy_s failed!"); - free(pkgName); - return DEVICEMANAGER_COPY_FAILED; - } - uint32_t cbId = 0; - RegisterDeathCallback(NULL, sid, DeathCb, pkgName, &cbId); - svcId.cbId = cbId; - std::string strPkgName = (const char *)name; - return IpcServerListenermgr::GetInstance().RegisterListener(strPkgName, &svcId); -} - -int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) -{ - DMLOG(DM_LOG_INFO, "unregister service listener."); - size_t len = 0; - std::string pkgName = (const char *)IpcIoPopString(req, &len); - if (pkgName == "" || len == 0) { - DMLOG(DM_LOG_ERROR, "get para failed"); - return DEVICEMANAGER_FAILED; - } - CommonSvcId svcId; - if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "not found listener by package name."); - return DEVICEMANAGER_FAILED; - } - int32_t ret = IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); - if (ret == DEVICEMANAGER_OK) { -#ifdef __LINUX__ - BinderRelease(svcId.ipcCtx, svcId.handle); -#endif - SvcIdentity sid; - sid.handle = svcId.handle; - sid.token = svcId.token; - sid.cookie = svcId.cookie; - ret = UnregisterDeathCallback(sid, svcId.cbId); - } - return ret; -} - -static const char *GetName(Service *service) -{ - (void)service; - return DEVICE_MANAGER_SERVICE_NAME; -} - -static BOOL Initialize(Service *service, Identity identity) -{ - if (service == NULL) { - DMLOG(DM_LOG_WARN, "invalid param"); - return FALSE; - } - - DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; - mgrService->identity = identity; - return TRUE; -} - -static BOOL MessageHandle(Service *service, Request *request) -{ - if ((service == NULL) || (request == NULL)) { - DMLOG(DM_LOG_WARN, "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 int32_t OnRemoteRequest(IServerProxy *iProxy, int32_t funcId, void *origin, - IpcIo *req, IpcIo *reply) -{ - DMLOG(DM_LOG_INFO, "Receive funcId:%d", funcId); - (void)origin; - return IpcCmdRegister::GetInstance().OnIpcServerCmd(funcId, *req, *reply); -} - -static void HOS_SystemInit(void) -{ - SAMGR_Bootstrap(); - return; -} - -int32_t IpcServerStubInit(void) -{ - HOS_SystemInit(); - return DEVICEMANAGER_OK; -} - -static void DevMgrSvcInit(void) -{ - sleep(WAIT_FOR_SERVER); - static DeviceManagerSamgrService service = { - .GetName = GetName, - .Initialize = Initialize, - .MessageHandle = MessageHandle, - .GetTaskConfig = GetTaskConfig, - SERVER_IPROXY_IMPL_BEGIN, - .Invoke = OnRemoteRequest, - IPROXY_END, - }; - - if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) { - DMLOG(DM_LOG_ERROR, "%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME); - return; - } - if (!SAMGR_GetInstance()->RegisterDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME, GET_IUNKNOWN(service))) { - DMLOG(DM_LOG_ERROR, "%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME); - return; - } - DMLOG(DM_LOG_INFO, "%s, init success", DEVICE_MANAGER_SERVICE_NAME); -} -SYSEX_SERVICE_INIT(DevMgrSvcInit); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp deleted file mode 100644 index 5d3292e81..000000000 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* - * 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 "constants.h" -#include "ipc_cmd_register.h" -#include "ipc_def.h" -#include "ipc_notify_auth_result_req.h" -#include "ipc_notify_check_auth_result_req.h" -#include "ipc_notify_device_found_req.h" -#include "ipc_notify_device_state_req.h" -#include "ipc_notify_discover_result_req.h" -#include "ipc_server_adapter.h" -#include "ipc_server_stub.h" -#include "ipc_notify_dmfa_result_req.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - int32_t deviceState = pReq->GetDeviceState(); - DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); - if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(deviceState)) { - DMLOG(DM_LOG_ERROR, "write state failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { - DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); - if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt16(subscribeId)) { - DMLOG(DM_LOG_ERROR, "write subscribeId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { - DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - int32_t result = pReq->GetResult(); - if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt16(subscribeId)) { - DMLOG(DM_LOG_ERROR, "write subscribeId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string deviceId = pReq->GetDeviceId(); - int32_t pinToken = pReq->GetPinToken(); - int32_t status = pReq->GetStatus(); - int32_t reason = pReq->GetReason(); - if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteString(deviceId)) { - DMLOG(DM_LOG_ERROR, "write deviceId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(pinToken)) { - DMLOG(DM_LOG_ERROR, "write pinToken failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(status)) { - DMLOG(DM_LOG_ERROR, "write status failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(reason)) { - DMLOG(DM_LOG_ERROR, "write reason failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; -} - -ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string deviceId = pReq->GetDeviceId(); - int32_t result = pReq->GetResult(); - int32_t flag = pReq->GetFlag(); - if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteString(deviceId)) { - DMLOG(DM_LOG_ERROR, "write deviceId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteInt32(flag)) { - DMLOG(DM_LOG_ERROR, "write flag failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string extra = data.ReadString(); - DMLOG(DM_LOG_INFO, "pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str()); - DmDeviceInfo *info = nullptr; - int32_t infoNum = 0; - int32_t result = IpcServerAdapter::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); - reply.WriteInt32(infoNum); - if (infoNum > 0 && info != nullptr) { - if (!reply.WriteRawData(info, sizeof(DmDeviceInfo) * infoNum)) { - DMLOG(DM_LOG_ERROR, "write subscribeInfo failed"); - } - free(info); - } - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - sptr listener = data.ReadRemoteObject(); - int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - DmSubscribeInfo *subscribeInfo = (DmSubscribeInfo *)data.ReadRawData(sizeof(DmSubscribeInfo)); - int32_t result = DEVICEMANAGER_NULLPTR; - - if (subscribeInfo != nullptr) { - DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); - result = IpcServerAdapter::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo); - } - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - uint16_t subscribeId = data.ReadInt32(); - DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeId); - int32_t result = IpcServerAdapter::GetInstance().StopDiscovery(pkgName, subscribeId); - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string extra = data.ReadString(); - DmDeviceInfo *deviceInfo = (DmDeviceInfo *)data.ReadRawData(sizeof(DmDeviceInfo)); - int32_t appIconLen = data.ReadInt32(); - int32_t appThumbnailLen = data.ReadInt32(); - uint8_t *appIcon = appIconLen > 0? (uint8_t *)data.ReadRawData(appIconLen) : nullptr; - uint8_t *appThumbnail = appThumbnailLen > 0? (uint8_t *)data.ReadRawData(appThumbnailLen) : nullptr; - - DmAppImageInfo imageInfo(appIcon, appIconLen, appThumbnail, appThumbnailLen); - int32_t result = DEVICEMANAGER_OK; - - if (deviceInfo != nullptr) { - result = IpcServerAdapter::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); - } - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(CHECK_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) -{ - std::string authPara = data.ReadString(); - int32_t result = IpcServerAdapter::GetInstance().CheckAuthentication(authPara); - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) -{ - std::string packName = data.ReadString(); - DmAuthParam authParam; - int32_t ret = DEVICEMANAGER_OK; - DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); - IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); - if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || - !reply.WriteInt32(authParam.pinToken)) { - DMLOG(DM_LOG_ERROR, "DeviceManagerStub::wirte client fail"); - ret = DEVICEMANAGER_WRITE_FAILED; - } - return ret; - } - - int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); - int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); - if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || - !reply.WriteString(authParam.packageName) || !reply.WriteString(authParam.appName) || - !reply.WriteString(authParam.appDescription) || !reply.WriteInt32(authParam.business) || - !reply.WriteInt32(authParam.pincode) || !reply.WriteInt32(appIconLen) || - !reply.WriteInt32(appThumbnailLen)) { - DMLOG(DM_LOG_ERROR, "write reply failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - - if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { - if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { - DMLOG(DM_LOG_ERROR, "write appIcon failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - } - - if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { - if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { - DMLOG(DM_LOG_ERROR, "write appThumbnail failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - } - - return DEVICEMANAGER_OK; -} - -ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParcel &reply) -{ - std::string packageName = data.ReadString(); - int32_t action = data.ReadInt32(); - int result = IpcServerAdapter::GetInstance().SetUserOperation(packageName, action); - - if (!reply.WriteInt32(action)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } - return result; -} - -ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) -{ - DMLOG(DM_LOG_INFO, "OnFaCallBack"); - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string packagname = pReq->GetPkgName(); - std::string paramJson = pReq->GetJsonParam(); - if (!data.WriteString(packagname)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - if (!data.WriteString(paramJson)) { - DMLOG(DM_LOG_ERROR, "write paramJson failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; - } - return DEVICEMANAGER_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp deleted file mode 100644 index 6dc1a24c1..000000000 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ipc_server_client_proxy.h" - -#include "ipc_types.h" - -#include "ipc_cmd_register.h" -#include "ipc_def.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" - -namespace OHOS { -namespace DistributedHardware { -int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - sptr remote = Remote(); - if (remote == nullptr) { - DMLOG(DM_LOG_ERROR, "remote service null"); - return DEVICEMANAGER_NULLPTR; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_FAILED; - } - if (remote->SendRequest(cmdCode, data, reply, option) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); - return DEVICEMANAGER_IPC_FAILED; - } - return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp deleted file mode 100644 index e08eaeab5..000000000 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ipc_server_listener.h" -#include "ipc_server_stub.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - std::string pkgName = req->GetPkgName(); - sptr listener = IpcServerStub::GetInstance().GetDmListener(pkgName); - if (listener == nullptr) { - DMLOG(DM_LOG_INFO, "cannot get listener for package:%s.", pkgName.c_str()); - return DEVICEMANAGER_NULLPTR; - } - return listener->SendCmd(cmdCode, req, rsp); -} - -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - std::map> listeners = IpcServerStub::GetInstance().GetDmListener(); - for (auto iter : listeners) { - auto pkgName = iter.first; - auto remote = iter.second; - req->SetPkgName(pkgName); - sptr listener = iface_cast(remote); - listener->SendCmd(cmdCode, req, rsp); - } - return DEVICEMANAGER_OK; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp deleted file mode 100644 index 7cf317ccd..000000000 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ipc_server_stub.h" - -#include -#include - -#include "if_system_ability_manager.h" -#include "ipc_skeleton.h" -#include "ipc_types.h" -#include "iservice_registry.h" -#include "string_ex.h" -#include "system_ability_definition.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" - -#include "ipc_server_adapter.h" -#include "ipc_cmd_register.h" - -namespace OHOS { -namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(IpcServerStub); - -const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&IpcServerStub::GetInstance()); - -IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true) -{ - registerToService_ = false; - state_ = ServiceRunningState::STATE_NOT_START; -} - -void IpcServerStub::OnStart() -{ - DMLOG(DM_LOG_INFO, "IpcServerStub::OnStart start"); - if (state_ == ServiceRunningState::STATE_RUNNING) { - DMLOG(DM_LOG_DEBUG, "IpcServerStub has already started."); - return; - } - if (!Init()) { - DMLOG(DM_LOG_ERROR, "failed to init IpcServerStub"); - return; - } - state_ = ServiceRunningState::STATE_RUNNING; -} - -bool IpcServerStub::Init() -{ - DMLOG(DM_LOG_INFO, "IpcServerStub::Init ready to init."); - if (!registerToService_) { - bool ret = Publish(this); - if (!ret) { - DMLOG(DM_LOG_ERROR, "IpcServerStub::Init Publish failed!"); - return false; - } - registerToService_ = true; - } - - std::thread { - [] { - IpcServerAdapter::GetInstance().ModuleInit(); - } - }.detach(); - return true; -} - -void IpcServerStub::OnStop() -{ - DMLOG(DM_LOG_INFO, "IpcServerStub::OnStop ready to stop service."); - state_ = ServiceRunningState::STATE_NOT_START; - registerToService_ = false; -} - -int32_t IpcServerStub::OnRemoteRequest(uint32_t code, - MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - DMLOG(DM_LOG_INFO, "code = %d, flags= %d.", code, option.GetFlags()); - int32_t ret = DEVICEMANAGER_OK; - ret = IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply); - if (ret == DEVICEMANAGER_IPC_NOT_REGISTER_FUNC) { - DMLOG(DM_LOG_WARN, "unsupport code: %d", code); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - return ret; -} - -int32_t IpcServerStub::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - return DEVICEMANAGER_OK; -} - -ServiceRunningState IpcServerStub::QueryServiceState() const -{ - return state_; -} - -int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr listener) -{ - if (pkgName.empty() || listener == nullptr) { - DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); - return DEVICEMANAGER_NULLPTR; - } - - DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); - std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(pkgName); - if (iter != dmListener_.end()) { - DMLOG(DM_LOG_INFO, "RegisterDeviceManagerListener: listener already exists"); - return DEVICEMANAGER_OK; - } - - sptr appRecipient = sptr(new AppDeathRecipient()); - if (!listener->AddDeathRecipient(appRecipient)) { - DMLOG(DM_LOG_ERROR, "RegisterDeviceManagerListener: AddDeathRecipient Failed"); - } - dmListener_[pkgName] = listener; - appRecipient_[pkgName] = appRecipient; - return DEVICEMANAGER_OK; -} - -int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) -{ - if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); - return DEVICEMANAGER_NULLPTR; - } - - DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); - std::lock_guard autoLock(listenerLock_); - auto listenerIter = dmListener_.find(pkgName); - if (listenerIter == dmListener_.end()) { - DMLOG(DM_LOG_INFO, "UnRegisterDeviceManagerListener: listener not exists"); - return DEVICEMANAGER_OK; - } - - auto recipientIter = appRecipient_.find(pkgName); - if (recipientIter == appRecipient_.end()) { - DMLOG(DM_LOG_INFO, "UnRegisterDeviceManagerListener: appRecipient not exists"); - dmListener_.erase(pkgName); - return DEVICEMANAGER_OK; - } - - auto listener = listenerIter->second; - auto appRecipient = recipientIter->second; - listener->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(pkgName); - dmListener_.erase(pkgName); - return DEVICEMANAGER_OK; -} - -const std::map> &IpcServerStub::GetDmListener() -{ - return dmListener_; -} - -const sptr IpcServerStub::GetDmListener(std::string pkgName) const -{ - auto iter = dmListener_.find(pkgName); - if (iter == dmListener_.end()) { - return nullptr; - } - auto remote = iter->second; - sptr dmListener = iface_cast(remote); - return dmListener; -} - -void AppDeathRecipient::OnRemoteDied(const wptr &remote) -{ - DMLOG(DM_LOG_WARN, "AppDeathRecipient: OnRemoteDied"); - std::map> listeners = IpcServerStub::GetInstance().GetDmListener(); - std::string pkgName; - for (auto iter : listeners) { - if (iter.second == remote.promote()) { - pkgName = iter.first; - break; - } - } - if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "AppDeathRecipient: OnRemoteDied, no pkgName matched"); - return; - } - DMLOG(DM_LOG_INFO, "AppDeathRecipient: OnRemoteDied for %s", pkgName.c_str()); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/message/msg_codec.cpp b/services/devicemanagerservice/src/message/msg_codec.cpp deleted file mode 100644 index c98d5645a..000000000 --- a/services/devicemanagerservice/src/message/msg_codec.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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 "msg_codec.h" -#include "device_manager_log.h" -#include "msg_head.h" - -#include "constants.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" - -namespace OHOS { -namespace DistributedHardware { -int32_t MsgCodec::DecodeMsgType(std::string &jsonStr) -{ - nlohmann::json jsonObject = nlohmann::json::parse(jsonStr, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "DecodeMsgType jsonStr error"); - return DmMsgType::MSG_TYPE_UNKNOWN; - } - MsgHead mMsgHead; - auto msgHeadPtr = mMsgHead.Decode(jsonObject); - if (msgHeadPtr == nullptr) { - DMLOG(DM_LOG_ERROR, "mMsgHead decode error"); - return DEVICEMANAGER_NULLPTR; - } - return msgHeadPtr->GetMsgType(); -} - -std::string MsgCodec::EncodeSyncGroup(std::vector &groupIdList, std::string &deviceId) -{ - nlohmann::json jsonObject; - MsgSyncGroup mMsgSyncGroup(groupIdList, deviceId); - mMsgSyncGroup.Encode(jsonObject); - return jsonObject.dump(); -} - -std::vector MsgCodec::EncodeReqAppAuth(std::string &token, std::string hostPkg, std::string targetPkg, - const DmDeviceInfo &devReqInfo, const DmAppImageInfo &imageInfo, std::string &extras) -{ - MsgRequestAuth mMsgRequestAuth(token, hostPkg, targetPkg, devReqInfo, imageInfo, extras); - return mMsgRequestAuth.Encode(); -} - -std::string MsgCodec::EncodeAcceptRespAuth(int32_t reply, int64_t requestId, std::string &groupId, - std::string &groupName, std::string &reqDeviceId) -{ - nlohmann::json jsonObject; - MsgResponseAuth mMsgResponseAuth(reply, requestId, groupId, groupName, reqDeviceId); - mMsgResponseAuth.Encode(jsonObject); - return jsonObject.dump(); -} - -std::string MsgCodec::EncodeRefuseRespAuth(int32_t reply, std::string &reqDeviceId) -{ - nlohmann::json jsonObject; - MsgResponseAuth mMsgResponseAuth(reply, reqDeviceId); - mMsgResponseAuth.Encode(jsonObject); - return jsonObject.dump(); -} - -std::shared_ptr MsgCodec::DecodeRequestAuth(std::string &jsonStr, - std::shared_ptr msgRequestAuth) -{ - nlohmann::json jsonObject = nlohmann::json::parse(jsonStr, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "DecodeRequestAuth jsonStr error"); - return nullptr; - } - return MsgRequestAuth::Decode(jsonObject, msgRequestAuth); -} - -std::shared_ptr MsgCodec::DecodeResponseAuth(std::string &jsonStr) -{ - nlohmann::json jsonObject = nlohmann::json::parse(jsonStr, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "DecodeResponseAuth jsonStr error"); - return nullptr; - } - std::shared_ptr msgResponseAuthPtr = std::make_shared(); - if (msgResponseAuthPtr->Decode(jsonObject) == 0) { - return msgResponseAuthPtr; - } - return nullptr; -} - -std::shared_ptr MsgCodec::DecodeSyncGroup(std::string &jsonStr) -{ - nlohmann::json jsonObject = nlohmann::json::parse(jsonStr, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "DecodeSyncGroup jsonStr error"); - return nullptr; - } - std::shared_ptr msgSyncGroupPtr = std::make_shared(); - if (msgSyncGroupPtr->Decode(jsonObject) == 0) { - return msgSyncGroupPtr; - } - return nullptr; -} -} -} diff --git a/services/devicemanagerservice/src/message/msg_head.cpp b/services/devicemanagerservice/src/message/msg_head.cpp deleted file mode 100644 index 77cc84416..000000000 --- a/services/devicemanagerservice/src/message/msg_head.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 "msg_head.h" -#include "device_manager_log.h" -#include "constants.h" - -namespace OHOS { -namespace DistributedHardware { -void MsgHead::Encode(nlohmann::json &json) -{ - json[TAG_VER] = DM_ITF_VER; - json[TAG_TYPE] = mMsgType_; -} - -std::shared_ptr MsgHead::Decode(nlohmann::json &json) -{ - if (json.contains(TAG_TYPE) == false || json.contains(TAG_VER) == false) { - DMLOG(DM_LOG_ERROR, "err json string"); - return nullptr; - } - - auto msgHeadPtr = std::make_shared(); - msgHeadPtr->mItfVer_ = json[TAG_VER]; - - if (DM_ITF_VER.compare(msgHeadPtr->mItfVer_) == 0) { - msgHeadPtr->mMsgType_ = json[TAG_TYPE]; - } else { - DMLOG(DM_LOG_ERROR, "msg head version mismatch"); - msgHeadPtr->mMsgType_ = DmMsgType::MSG_TYPE_UNKNOWN; - } - return msgHeadPtr; -} - -int32_t MsgHead::GetMsgType() -{ - return mMsgType_; -} -} -} \ No newline at end of file diff --git a/services/devicemanagerservice/src/message/msg_request_auth.cpp b/services/devicemanagerservice/src/message/msg_request_auth.cpp deleted file mode 100644 index d902d86fa..000000000 --- a/services/devicemanagerservice/src/message/msg_request_auth.cpp +++ /dev/null @@ -1,381 +0,0 @@ -/* - * 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 - -#include "device_manager_log.h" -#include "constants.h" -#include "encrypt_utils.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "encrypt_utils.h" -#include "msg_request_auth.h" -#include "parameter.h" -#include "softbus_session.h" -#include "softbus_bus_center.h" -#include "msg_request_auth.h" - -namespace OHOS { -namespace DistributedHardware { -MsgRequestAuth::MsgRequestAuth(std::string &token, std::string hostPkgName, std::string targetPkgName, - const int32_t groupVisibility, const DmDeviceInfo& devReqInfo, const DmAppImageInfo &imageInfo, - std::string &extras) -{ - DMLOG(DM_LOG_INFO, "MsgRequestAuth construction started"); - nlohmann::json jsonObject = nlohmann::json::parse(extras, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "MsgRequestAuth error"); - return; - } - if (!jsonObject.contains(APP_NAME_KEY) || !jsonObject.contains(APP_DESCRIPTION_KEY)) { - DMLOG(DM_LOG_ERROR, "MsgRequestAuth, err json string"); - return; - } - - mAuthType_ = jsonObject.contains(AUTH_TYPE) ? (int32_t)jsonObject[AUTH_TYPE] : AUTH_TYPE_QR; - mHead_ = std::make_shared((mAuthType_ == AUTH_TYPE_QR) ? (DmMsgType::MSG_TYPE_REQ_AUTH) : - (DmMsgType::MSG_TYPE_AUTH_BY_PIN)); - std::string deviceManagerPkgName = "ohos.distributedhardware.devicemanager"; - NodeBasicInfo localBasicInfo; - int32_t ret = GetLocalNodeDeviceInfo(deviceManagerPkgName.c_str(), &localBasicInfo); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "GetLocalNodeDeviceInfo err: %d", ret); - return; - } - mDeviceName_ = localBasicInfo.deviceName; - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - mDeviceId_ = localDeviceId; - mToken_ = token; - mHostPkg_ = hostPkgName; - mTargetPkg_ = targetPkgName; - mGroupVisibility_ = groupVisibility; - mAppName_ = jsonObject[APP_NAME_KEY]; - mAppDescription_ = jsonObject[APP_DESCRIPTION_KEY]; - mImageInfo_ = imageInfo; - mThumbnailSize_ = mImageInfo_.GetAppThumbnailLen(); - mAppIconSize_ = mImageInfo_.GetAppIconLen(); - mDeviceType_ = ToHexString(localBasicInfo.deviceTypeId); - DMLOG(DM_LOG_INFO, "MsgRequestAuth construction completed"); -} - -int32_t MsgRequestAuth::GetEncodedAppInfo(const uint8_t *dataSrc, int32_t srcLen, std::string &outString) -{ - DMLOG(DM_LOG_INFO, "MsgRequestAuth GetEncodedAppInfo started"); - if (srcLen <= 0 || dataSrc == nullptr) { - DMLOG(DM_LOG_ERROR, "data string is empty"); - return DEVICEMANAGER_OK; - } - - int32_t tempBufLen = ((srcLen / BASE64_BYTE_LEN_3) + 1) * BASE64_BYTE_LEN_4 + 1; - char *tmpBuf = (char *)calloc(sizeof(char), tempBufLen); - if (tmpBuf == nullptr) { - DMLOG(DM_LOG_ERROR, "getEncodedAppInfoString: malloc mem error, size %d", tempBufLen); - return DEVICEMANAGER_MALLOC_ERROR; - } - - size_t outLen = 0; - int32_t ret = EncryptUtils::MbedtlsBase64Encode((uint8_t *)tmpBuf, tempBufLen, &outLen, dataSrc, (size_t)srcLen); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "MbedtlsBase64Encode error"); - free(tmpBuf); - return ENCODE_DATA_ERROR; - } - outString = tmpBuf; - free(tmpBuf); - tmpBuf = nullptr; - DMLOG(DM_LOG_INFO, "MsgRequestAuth GetEncodedAppInfo completed"); - return DEVICEMANAGER_OK; -} - -void MsgRequestAuth::GetDecodeAppInfo(const std::string appString, uint8_t **outBuffer, int32_t &outBufferLen) -{ - DMLOG(DM_LOG_INFO, "MsgRequestAuth GetDecodeAppInfo started"); - int32_t tempBufLen = appString.length() + 1; - uint8_t *buffer = (uint8_t *)calloc(sizeof(char), tempBufLen); - if (buffer == nullptr) { - DMLOG(DM_LOG_ERROR, "GetDecodeAppInfo: malloc mem error, tempBufLen %d", tempBufLen); - return; - } - - size_t outLen = 0; - int32_t ret = EncryptUtils::MbedtlsBase64Decode(buffer, tempBufLen, &outLen, - (const uint8_t*)appString.c_str(), appString.length()); - if (ret != 0 || static_cast(outLen) > tempBufLen) { - DMLOG(DM_LOG_ERROR, "MbedtlsBase64Decode failed, ret %d, outLen %d, tempBufLen %d", - ret, outLen, tempBufLen); - outBufferLen = 0; - *outBuffer = nullptr; - free(buffer); - return; - } - - DMLOG(DM_LOG_INFO, "MsgRequestAuth GetDecodeAppInfo outBufferLen %d", outBufferLen); - outBufferLen = outLen; - *outBuffer = buffer; -} - -std::string MsgRequestAuth::EncodeDevInfo() -{ - DMLOG(DM_LOG_INFO, "MsgRequestAuth EncodeDevInfo started"); - nlohmann::json jsonObj; - mHead_->Encode(jsonObj); - jsonObj[TAG_SLICE_NUM] = mMsgSlice_; - jsonObj[TAG_INDEX] = 0; - jsonObj[TAG_REQUESTER] = mDeviceName_; - jsonObj[TAG_DEVICE_ID] = mDeviceId_; - jsonObj[TAG_DEVICE_TYPE] = mDeviceType_; - jsonObj[TAG_TOKEN] = mToken_; - jsonObj[TAG_VISIBILITY] = mGroupVisibility_; - if (mGroupVisibility_ == GROUP_VISIBILITY_IS_PRIVATE) { - jsonObj[TAG_TARGET] = mTargetPkg_; - jsonObj[TAG_HOST] = mHostPkg_; - } - jsonObj[TAG_APP_NAME] = mAppName_; - jsonObj[TAG_APP_DESCRIPTION] = mAppDescription_; - - std::string appIconStr = ""; - GetEncodedAppInfo(mImageInfo_.GetAppIcon(), mImageInfo_.GetAppIconLen(), appIconStr); - jsonObj[TAG_APP_ICON] = appIconStr; - jsonObj[TAG_THUMBNAIL_SIZE] = mThumbnailSize_; - jsonObj[TAG_AUTH_TYPE] = mAuthType_; - DMLOG(DM_LOG_INFO, "MsgRequestAuth EncodeDevInfo completed"); - return jsonObj.dump(); -} - -void MsgRequestAuth::DecodeDeviceInfo(nlohmann::json &json, std::shared_ptr msg) -{ - msg->mDeviceName_ = json[TAG_REQUESTER]; - msg->mDeviceId_ = json[TAG_DEVICE_ID]; - msg->mDeviceType_ = json[TAG_DEVICE_TYPE]; - msg->mToken_ = json[TAG_TOKEN]; - msg->mGroupVisibility_ = json[TAG_VISIBILITY]; - if (msg->mGroupVisibility_ == GROUP_VISIBILITY_IS_PRIVATE) { - msg->mTargetPkg_ = json[TAG_TARGET]; - msg->mHostPkg_ = json[TAG_HOST]; - } - msg->mAppName_ = json[TAG_APP_NAME]; - msg->mAppDescription_ = json[TAG_APP_DESCRIPTION]; - - const std::string iconStr = json[TAG_APP_ICON]; - uint8_t *appIcon = nullptr; - int32_t appIconLen = 0; - msg->GetDecodeAppInfo(iconStr, &appIcon, appIconLen); - if (appIcon != nullptr) { - msg->mImageInfo_.ResetIcon(appIcon, appIconLen); - free(appIcon); - } - - SetThumbnailSize(json, msg); - msg->mAuthType_ = json[TAG_AUTH_TYPE]; -} - -std::vector MsgRequestAuth::Encode() -{ - DMLOG(DM_LOG_INFO, "MsgRequestAuth encode started"); - std::vector jsonStrs; - int32_t thumbnailSlice = - ((mThumbnailSize_ / MSG_MAX_SIZE) + (mThumbnailSize_ % MSG_MAX_SIZE) == 0 ? 0 : 1); - mMsgSlice_ = thumbnailSlice + 1; - jsonStrs.push_back(EncodeDevInfo()); - for (int32_t idx = 0; idx < thumbnailSlice; idx++) { - nlohmann::json jsonObj; - mHead_->Encode(jsonObj); - jsonObj[TAG_SLICE_NUM] = mMsgSlice_; - jsonObj[TAG_INDEX] = idx + 1; - jsonObj[TAG_DEVICE_ID] = mDeviceId_; - jsonObj[TAG_THUMBNAIL_SIZE] = mThumbnailSize_; - - // frag thumbnail by 45KB - std::string thumbnailStr = ""; - int32_t leftLen = mImageInfo_.GetAppThumbnailLen() - idx * MSG_MAX_SIZE; - int32_t sliceLen = (leftLen > MSG_MAX_SIZE) ? MSG_MAX_SIZE : leftLen; - - DMLOG(DM_LOG_INFO, "TAG_APP_THUMBNAIL encode, idx %d, encodeLen %d, mThumbnailSize_ %d", - idx, sliceLen, mThumbnailSize_); - - const uint8_t *thumbnail = mImageInfo_.GetAppThumbnail(); - GetEncodedAppInfo(thumbnail + idx * MSG_MAX_SIZE, sliceLen, thumbnailStr); - jsonObj[TAG_APP_THUMBNAIL] = thumbnailStr; - - jsonStrs.push_back(jsonObj.dump()); - } - DMLOG(DM_LOG_INFO, "MsgRequestAuth encode completed"); - return jsonStrs; -} - -std::shared_ptr MsgRequestAuth::Decode(nlohmann::json &json, std::shared_ptr msgIn) -{ - if (!json.contains(TAG_INDEX) || !json.contains(TAG_DEVICE_ID) || !json.contains(TAG_SLICE_NUM)) { - DMLOG(DM_LOG_ERROR, "err json string, first time"); - return nullptr; - } - int32_t idx = json[TAG_INDEX]; - std::string deviceId = json[TAG_DEVICE_ID]; - if (!IsMsgValid(msgIn, json, deviceId, idx)) { - auto inValidMsg = std::make_shared(); - inValidMsg->mMsgSlice_ = FAIL; - return inValidMsg; - } - - std::shared_ptr msg = msgIn; - if (msgIn == nullptr || msgIn->mMsgCnt_ == msgIn->mMsgSlice_) { - msg = std::make_shared(); - } - msg->mHead_ = MsgHead::Decode(json); - msg->mMsgSlice_ = json[TAG_SLICE_NUM]; - if (idx == 0) { - DecodeDeviceInfo(json, msg); - } else { - SetThumbnailSize(json, msg); - msg->mDeviceId_ = deviceId; - if (!json.contains(TAG_APP_THUMBNAIL)) { - DMLOG(DM_LOG_ERROR, "err json string, TAG_APP_THUMBNAIL not exit"); - return nullptr; - } - - std::string thumbnailStr = json[TAG_APP_THUMBNAIL]; - uint8_t *thumbnail = nullptr; - int32_t thumbnailLen = 0; - msg->GetDecodeAppInfo(thumbnailStr, &thumbnail, thumbnailLen); - if (thumbnail == nullptr) { - DMLOG(DM_LOG_ERROR, "TAG_APP_THUMBNAIL Decode error"); - return nullptr; - } - - DMLOG(DM_LOG_INFO, "TAG_APP_THUMBNAIL decode, idx %d, decodeLen %d, mThumbnailSize_ %d", - idx, thumbnailLen, msg->mThumbnailSize_); - if (msg->mThumbnailSize_ < thumbnailLen + (idx - 1) * MSG_MAX_SIZE) { - auto inValidReqMsg = std::make_shared(); - inValidReqMsg->mMsgSlice_ = FAIL; - free(thumbnail); - return inValidReqMsg; - } - msg->mImageInfo_.SetThumbnailData(thumbnail, thumbnailLen, (idx - 1) * MSG_MAX_SIZE, thumbnailLen); - free(thumbnail); - } - msg->mMsgCnt_++; - return msg; -} - -int32_t MsgRequestAuth::GetMsgSlice() -{ - return mMsgSlice_; -} - -int32_t MsgRequestAuth::GetMsgCnt() -{ - return mMsgCnt_; -} - -std::string MsgRequestAuth::GetRequestDeviceId() -{ - return mDeviceId_; -} - -bool MsgRequestAuth::IsMsgValid(std::shared_ptr msgIn, nlohmann::json &json, - std::string &deviceId, int32_t index) -{ - if (msgIn != nullptr && msgIn->mMsgCnt_ != msgIn->mMsgSlice_ && deviceId.compare(msgIn->mDeviceId_)) { - DMLOG(DM_LOG_ERROR, "IsMsgValid, msgIn error"); - return false; - } - - if (!json.contains(TAG_THUMBNAIL_SIZE)) { - DMLOG(DM_LOG_ERROR, "IsMsgValid, err json string"); - return false; - } - - if (index < 0 || index >= DES_SLICE_MAX_NUM) { - DMLOG(DM_LOG_ERROR, "index err"); - return false; - } - - if (index == 0) { - return IsAppInfoValid(json); - } else { - int32_t thumbnailSlice = json[TAG_THUMBNAIL_SIZE]; - if (thumbnailSlice > THUMB_MAX_LEN || thumbnailSlice < 0) { - DMLOG(DM_LOG_ERROR, "IsMsgValid, thumbnailSlice error"); - return false; - } - } - return true; -} - -bool MsgRequestAuth::IsAppInfoValid(nlohmann::json &json) -{ - if (!json.contains(TAG_REQUESTER) || !json.contains(TAG_DEVICE_TYPE) || !json.contains(TAG_TOKEN) || - !json.contains(TAG_VISIBILITY) || !json.contains(TAG_APP_NAME) || !json.contains(TAG_APP_DESCRIPTION) || - !json.contains(TAG_APP_ICON) || !json.contains(TAG_AUTH_TYPE) || !json.contains(TAG_DEVICE_ID)) { - DMLOG(DM_LOG_ERROR, "IsAppInfoValid:: err json string"); - return false; - } - - int32_t groupVisibility = json[TAG_VISIBILITY]; - if (groupVisibility == GROUP_VISIBILITY_IS_PRIVATE) { - if (!json.contains(TAG_TARGET) || !json.contains(TAG_HOST)) { - DMLOG(DM_LOG_ERROR, "IsAppInfoValid:: err json string, TAG_TARGET or TAG_HOST not contain"); - return false; - } - } - - if (json[TAG_APP_ICON].size() > ICON_MAX_LEN) { - DMLOG(DM_LOG_ERROR, "IsAppInfoValid, appIcon size error"); - return false; - } - - int32_t thumbnailSize = json[TAG_THUMBNAIL_SIZE]; - if (thumbnailSize > THUMB_MAX_LEN || thumbnailSize < 0) { - DMLOG(DM_LOG_ERROR, "IsAppInfoValid, thumbnailSize error"); - return false; - } - return true; -} - -void MsgRequestAuth::SetAuthType(nlohmann::json &json, std::shared_ptr msg) -{ - int32_t authType = json.contains(TAG_AUTH_TYPE) ? (int32_t)json[TAG_AUTH_TYPE] : AUTH_TYPE_QR; - if (authType != AUTH_TYPE_QR && authType != AUTH_TYPE_PIN) { - authType = AUTH_TYPE_QR; - } - msg->mAuthType_ = authType; -} - -void MsgRequestAuth::SetThumbnailSize(nlohmann::json &json, std::shared_ptr msg) -{ - if (!json.contains(TAG_THUMBNAIL_SIZE)) { - DMLOG(DM_LOG_ERROR, "SetThumbnailSize, err json string"); - return; - } - int32_t thumbnailSlice = json[TAG_THUMBNAIL_SIZE]; - if (msg->mThumbnailSize_ == 0) { - msg->mImageInfo_.InitThumbnail(thumbnailSlice); - msg->mThumbnailSize_ = msg->mImageInfo_.GetAppThumbnailLen(); - DMLOG(DM_LOG_INFO, "thumbnailSlice %d, mThumbnailSize_ is, %d", thumbnailSlice, msg->mThumbnailSize_); - } -} - -std::string MsgRequestAuth::ToHexString(int32_t value) -{ - std::stringstream ioss; - std::string tmpStr; - ioss << std::setiosflags(std::ios::uppercase) << std::hex << value; - ioss >> tmpStr; - return tmpStr; -} -} -} diff --git a/services/devicemanagerservice/src/message/msg_response_auth.cpp b/services/devicemanagerservice/src/message/msg_response_auth.cpp deleted file mode 100644 index b1b18492b..000000000 --- a/services/devicemanagerservice/src/message/msg_response_auth.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* - * 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 "msg_response_auth.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" -#include "constants.h" -#include "parameter.h" -#include "hichain_connector.h" -#include "anonymous_string.h" - -namespace OHOS { -namespace DistributedHardware { -MsgResponseAuth::MsgResponseAuth(int32_t reply, std::string &reqDeviceId) -{ - mHead_ = std::make_shared(MSG_TYPE_RESP_AUTH); - mReply_ = reply; - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - mDeviceId_ = localDeviceId; - std::vector groupList; - HichainConnector::GetInstance().GetRelatedGroups(reqDeviceId, groupList); - HichainConnector::GetInstance().GetSyncGroupList(groupList, mSyncGroupList_); -} - -MsgResponseAuth::MsgResponseAuth(int32_t reply, int64_t requestId, std::string &groupId, std::string &groupName, - std::string &reqDeviceId) -{ - mHead_ = std::make_shared(MSG_TYPE_RESP_AUTH); - mReply_ = reply; - mNetId_ = ""; - mGroupId_ = groupId; - mGroupName_ = groupName; - mRequestId_ = requestId; - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - mDeviceId_ = localDeviceId; - std::vector groupList; - HichainConnector::GetInstance().GetRelatedGroups(reqDeviceId, groupList); - HichainConnector::GetInstance().GetSyncGroupList(groupList, mSyncGroupList_); -} - -void MsgResponseAuth::Encode(nlohmann::json &jsonObj) -{ - DMLOG(DM_LOG_INFO, "MsgResponseAuth encode started"); - mHead_->Encode(jsonObj); - jsonObj[TAG_REPLY] = mReply_; - jsonObj[TAG_DEVICE_ID] = mDeviceId_; - jsonObj[TAG_GROUPIDS] = mSyncGroupList_; - if (mReply_ == SESSION_REPLY_ACCEPT) { - jsonObj[TAG_NET_ID] = mNetId_; - jsonObj[TAG_REQUEST_ID] = mRequestId_; - jsonObj[TAG_GROUP_ID] = mGroupId_; - jsonObj[TAG_GROUP_NAME] = mGroupName_; - DMLOG(DM_LOG_INFO, "MsgResponseAuth encode completed"); - } - DMLOG(DM_LOG_INFO, "encode mReply_ is : %d", mReply_); - DMLOG(DM_LOG_INFO, "encode deviceId is : %s", GetAnonyString(mDeviceId_).c_str()); - DMLOG(DM_LOG_INFO, "encode netId is : %s", GetAnonyString(mNetId_).c_str()); - DMLOG(DM_LOG_INFO, "encode mGroupId_ is %s", GetAnonyString(mGroupId_).c_str()); - DMLOG(DM_LOG_INFO, "encode mGroupName_ is %s", mGroupName_.c_str()); - DMLOG(DM_LOG_INFO, "encode mRequestId_ is %d", mRequestId_); -} - -int32_t MsgResponseAuth::Decode(nlohmann::json &jsonObj) -{ - DMLOG(DM_LOG_INFO, "MsgResponseAuth decode started"); - if (!jsonObj.contains(TAG_REPLY) || !jsonObj.contains(TAG_DEVICE_ID) || !jsonObj.contains(TAG_GROUPIDS)) { - DMLOG(DM_LOG_ERROR, "MsgResponseAuth::decode, err json string, first time"); - return MSG_DECODE_PARA_FAILED; - } - - MsgHead msgHead; - mHead_ = msgHead.Decode(jsonObj); - mReply_ = jsonObj[TAG_REPLY]; - mDeviceId_ = jsonObj[TAG_DEVICE_ID]; - std::vector groupList = jsonObj[TAG_GROUPIDS]; - for (auto str : groupList) { - mSyncGroupList_.push_back(str); - } - - if (mReply_ == SESSION_REPLY_ACCEPT) { - if (!jsonObj.contains(TAG_NET_ID) || !jsonObj.contains(TAG_GROUP_ID) || !jsonObj.contains(TAG_GROUP_NAME) || - !jsonObj.contains(TAG_REQUEST_ID)) { - DMLOG(DM_LOG_ERROR, "MsgResponseAuth::decode, err json string, second time"); - return MSG_DECODE_PARA_FAILED; - } - mNetId_ = jsonObj[TAG_NET_ID]; - mGroupId_ = jsonObj[TAG_GROUP_ID]; - mGroupName_ = jsonObj[TAG_GROUP_NAME]; - mRequestId_ = jsonObj[TAG_REQUEST_ID]; - } - DMLOG(DM_LOG_INFO, "decode mReply_ is : %d", mReply_); - DMLOG(DM_LOG_INFO, "decode mGroupId_ is %s", GetAnonyString(mGroupId_).c_str()); - DMLOG(DM_LOG_INFO, "decode mGroupName_ is %s", GetAnonyString(mGroupName_).c_str()); - DMLOG(DM_LOG_INFO, "decode deviceId is : %s", GetAnonyString(mDeviceId_).c_str()); - DMLOG(DM_LOG_INFO, "decode netId is : %s", GetAnonyString(mNetId_).c_str()); - DMLOG(DM_LOG_INFO, "decode mRequestId_ is %d", mRequestId_); - DMLOG(DM_LOG_INFO, "MsgResponseAuth decode completed"); - return DEVICEMANAGER_OK; -} - -int32_t MsgResponseAuth::GetReply() -{ - return mReply_; -} - -std::string MsgResponseAuth::GetNetId() -{ - return mNetId_; -} - -std::string MsgResponseAuth::GetGroupId() -{ - return mGroupId_; -} - -std::string MsgResponseAuth::GetDeviceId() -{ - return mDeviceId_; -} - -std::string MsgResponseAuth::GetGroupName() -{ - return mGroupName_; -} - -int64_t MsgResponseAuth::GetRequestId() -{ - return mRequestId_; -} - -std::vector MsgResponseAuth::GetSyncGroupList() -{ - return mSyncGroupList_; -} - -int32_t MsgResponseAuth::GetPinCode() -{ - return mPinCode_; -} - -void MsgResponseAuth::SavePinCode(int32_t pinCode) -{ - mPinCode_ = pinCode; -} -} -} diff --git a/services/devicemanagerservice/src/message/msg_sync_group.cpp b/services/devicemanagerservice/src/message/msg_sync_group.cpp deleted file mode 100644 index 5ccb56be9..000000000 --- a/services/devicemanagerservice/src/message/msg_sync_group.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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 "msg_sync_group.h" -#include "device_manager_log.h" -#include "constants.h" -#include "device_manager_errno.h" - -namespace OHOS { -namespace DistributedHardware { -MsgSyncGroup::MsgSyncGroup(std::vector &groupList, std::string &deviceId) -{ - DMLOG(DM_LOG_INFO, "MsgSyncGroup construction started"); - mHead_ = std::make_shared(DmMsgType::MSG_TYPE_SYNC_GROUP); - for (auto str: groupList) { - mGroupIdList_.push_back(str); - } - mDeviceId_ = deviceId; - DMLOG(DM_LOG_INFO, "MsgSyncGroup construction completed"); -} - -void MsgSyncGroup::Encode(nlohmann::json &json) -{ - mHead_->Encode(json); - json[TAG_DEVICE_ID] = mDeviceId_; - json[TAG_GROUPIDS] = mGroupIdList_; -} - -int32_t MsgSyncGroup::Decode(nlohmann::json &json) -{ - DMLOG(DM_LOG_INFO, "MsgSyncGroup decode started"); - if (!json.contains(TAG_DEVICE_ID) || !json.contains(TAG_GROUPIDS)) { - DMLOG(DM_LOG_ERROR, "MsgSyncGroup::decode err "); - return MSG_DECODE_PARA_FAILED; - } - - MsgHead msgHead; - mHead_ = msgHead.Decode(json); - mDeviceId_ = json[TAG_DEVICE_ID]; - mGroupIdList_ = json.at(TAG_GROUPIDS).get>(); - DMLOG(DM_LOG_INFO, "MsgSyncGroup decode completed"); - return DEVICEMANAGER_OK; -} - -std::string MsgSyncGroup::GetDeviceId() -{ - return mDeviceId_; -} - -std::vector MsgSyncGroup::GetGroupIdList() -{ - return mGroupIdList_; -} -} -} \ No newline at end of file diff --git a/services/devicemanagerservice/src/requestauth/auth_manager.cpp b/services/devicemanagerservice/src/requestauth/auth_manager.cpp deleted file mode 100644 index 82f7fb091..000000000 --- a/services/devicemanagerservice/src/requestauth/auth_manager.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/* - * 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 "auth_manager.h" -#include "anonymous_string.h" -#include "dm_ability_manager.h" -#include "constants.h" -#include "msg_codec.h" -#include "device_manager_log.h" -#include "msg_codec.h" -#include "device_manager_errno.h" -#include "softbus_session.h" -#include "encrypt_utils.h" -#include "ipc_server_listener_adapter.h" -#include "msg_sync_group.h" - -namespace OHOS { -namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(AuthManager); - -void AuthManager::AuthDeviceGroup(std::string &hostPkgName, const DmDeviceInfo &devReqInfo, - const DmAppImageInfo &imageInfo, std::string &extras) -{ - AuthAppGroup(hostPkgName, devReqInfo, imageInfo, extras); -} - -void AuthManager::OnReceiveMsg(long long channelId, std::string &message) -{ - int32_t msgType = MsgCodec::DecodeMsgType(message); - DMLOG(DM_LOG_INFO, "message type is, %d", msgType); - switch (msgType) { - case MSG_TYPE_RESP_AUTH: - case MSG_TYPE_REQ_AUTH: - case MSG_TYPE_AUTH_BY_PIN: - OnReceiveMessage(channelId, message, msgType); - break; - case MSG_TYPE_SYNC_GROUP: - SyncDmPrivateGroup(message); - break; - default: - DMLOG(DM_LOG_INFO, "msgType not support yet, msgType: %d", msgType); - break; - } -} - -void AuthManager::AuthAppGroup(std::string &hostPkgName, const DmDeviceInfo &devReqInfo, - const DmAppImageInfo &imageInfo, std::string &extrasJson) -{ - DMLOG(DM_LOG_INFO, "AuthManager::AuthAppGroup started"); - nlohmann::json jsonObject = nlohmann::json::parse(extrasJson, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "extrasJson error"); - return; - } - if (!jsonObject.contains(AUTH_TYPE)) { - DMLOG(DM_LOG_ERROR, "AuthAppGroup extrasJson error"); - return; - } - if (!jsonObject.contains(TARGET_PKG_NAME_KEY)) { - DMLOG(DM_LOG_ERROR, "TARGET_PKG_NAME is not in extrasJson"); - return; - } - std::string targetPkgName = jsonObject[TARGET_PKG_NAME_KEY]; - - if (!jsonObject.contains(DISPLAY_OWNER)) { - DMLOG(DM_LOG_WARN, "AuthAppGroup DISPLAY_OWNER error"); - displayOwner_ = DISPLAY_OWNER_SYSTEM; - } else { - displayOwner_ = jsonObject[DISPLAY_OWNER]; - } - - if (!CanStartNewSession()) { - DMLOG(DM_LOG_ERROR, "previous session not completed yet"); - mPendingReqSessionPtr_->NotifyHostAppAuthResult(ERROR_DUPLICATE_REQUEST); - return; - } - auto curSessionPtr = std::make_shared(hostPkgName, targetPkgName, devReqInfo, imageInfo); - mPendingReqSessionPtr_ = curSessionPtr; - std::vector msgInfo = curSessionPtr->GetRequestCommand(extrasJson); - int32_t channelId = SoftbusSession::GetInstance().SendMessages(devReqInfo.deviceId, msgInfo); - if (channelId > 0) { - DMLOG(DM_LOG_INFO, "open channel succeed, save channelId"); - mPendingReqSessionPtr_->SetChannelId(channelId); - return; - } - DMLOG(DM_LOG_ERROR, "open channel failed, close this session"); - mPendingReqSessionPtr_->Release(); - mPendingReqSessionPtr_->NotifyHostAppAuthResult(ERROR_START_REMOTE_DM); - mPendingReqSessionPtr_ = nullptr; -} - -bool AuthManager::CanStartNewSession() -{ - if (mPendingReqSessionPtr_ == nullptr || mPendingReqSessionPtr_->IsFinished()) { - return true; - } - return false; -} - -void AuthManager::OnUserOperate(int32_t action) -{ - if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { - if (mPendingReqSessionPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "mPendingReqSessionPtr_ not exist"); - return; - } - mPendingReqSessionPtr_->OnUserOperate(action); - return; - } - - if (mPendingRespSessionPtr == nullptr) { - DMLOG(DM_LOG_ERROR, "mPendingRespSessionPtr not exist"); - return; - } - - mPendingRespSessionPtr->OnUserOperate(action); -} - -void AuthManager::OnReceiveMessage(long long channelId, std::string &message, int32_t msgType) -{ - DMLOG(DM_LOG_INFO, "AuthManager::OnReceiveMessage started"); - if (msgType == MSG_TYPE_RESP_AUTH) { - DMLOG(DM_LOG_ERROR, "message type is MSG_TYPE_RESP_AUTH"); - if (mPendingReqSessionPtr_ == nullptr || !mPendingReqSessionPtr_->IsMyChannelId(channelId)) { - DMLOG(DM_LOG_ERROR, "receive error message"); - return; - } - mPendingReqSessionPtr_->OnReceiveMsg(message); - if (mPendingReqSessionPtr_->IsWaitingForScan()) { - DMLOG(DM_LOG_ERROR, "move Session To Wait Scan Map "); - MoveSessionToWaitScanMap(); - } - } else if (msgType == MSG_TYPE_REQ_AUTH || msgType == MSG_TYPE_AUTH_BY_PIN) { - DMLOG(DM_LOG_INFO, "message type is MSG_TYPE_REQ_AUTH"); - if (mPendingRespSessionPtr == nullptr) { - mPendingRespSessionPtr = std::make_shared(); - } - - if (!mPendingRespSessionPtr->IsMyChannelId(channelId)) { - DMLOG(DM_LOG_ERROR, "mPendingRespSessionPtr IsMyChannelId false!"); - return; - } - mPendingRespSessionPtr->OnReceiveMsg(channelId, message); - } else { - DMLOG(DM_LOG_ERROR, "error message type"); - } -} - -void AuthManager::SyncDmPrivateGroup(std::string &message) -{ - std::shared_ptr msgSyncGroupPtr = MsgCodec::DecodeSyncGroup(message); - if (msgSyncGroupPtr == nullptr) { - DMLOG(DM_LOG_ERROR, "decode syncGroup message err"); - return; - } - std::vector groupIdList = msgSyncGroupPtr->GetGroupIdList(); - HichainConnector::GetInstance().SyncGroups(msgSyncGroupPtr->GetDeviceId(), groupIdList); -} - -void AuthManager::MoveSessionToWaitScanMap() -{ - DMLOG(DM_LOG_ERROR, "AuthManager::MoveSessionToWaitScanMap"); - mWaitScanReqSessionMap_[mPendingReqSessionPtr_->GetToken()] = mPendingReqSessionPtr_; - mPendingReqSessionPtr_ = nullptr; -} - -int32_t AuthManager::CheckAuthentication(std::string &authPara) -{ - DMLOG(DM_LOG_INFO, "AuthManager::CheckAuthentication started"); - nlohmann::json authJson = nlohmann::json::parse(authPara, nullptr, false); - if (authJson.is_discarded()) { - DMLOG(DM_LOG_ERROR, "HichainAdapter::GetGroupIdByName parse group info error, json invalid."); - return AUTH_PARA_INVALID; - } - if (!authJson.contains(AUTH_TYPE) || authJson[AUTH_TYPE] != AUTH_TYPE_PIN) { - DMLOG(DM_LOG_ERROR, "error authPara msg"); - return AUTH_PARA_INVALID; - } - DMLOG(DM_LOG_INFO, "PIN Code Auth"); - authParam_ = authPara; - return CheckAuthenticationByPin(authJson); -} - -void AuthManager::NotifyHostOnCheckAuthResult(int64_t requestId, int errorCode) -{ - DMLOG(DM_LOG_INFO, "notify host checkResult, requestId: %lld, errorcode: %d", requestId, errorCode); - for (auto iter = mWaitScanReqSessionMap_.begin(); iter != mWaitScanReqSessionMap_.end(); iter++) { - auto requestSessionPtr = iter->second; - if (requestSessionPtr != nullptr && requestSessionPtr->GetRequestId() == requestId) { - std::string deviceId = requestSessionPtr->GetRequestDeviceId(); - DMLOG(DM_LOG_INFO, "notify host checkResult, deviceId: %s, requestId: %lld", - GetAnonyString(deviceId).c_str(), requestId); - IpcServerListenerAdapter::GetInstance().OnCheckAuthResult(deviceId, errorCode, 0); - return; - } - } - - DMLOG(DM_LOG_ERROR, "notify host checkResult error, requestId: %lld", requestId); -} - -int32_t AuthManager::CheckAuthenticationByPin(nlohmann::json &authJson) -{ - int32_t pinCode = authJson.contains(PIN_CODE_KEY) ? (int32_t)authJson[PIN_CODE_KEY] : DEFAULT_PIN_CODE; - int32_t pinToken = authJson.contains(PIN_TOKEN) ? (int32_t)authJson[PIN_TOKEN] : DEFAULT_PIN_TOKEN; - if (pinCode < MIN_PIN_CODE || pinCode >= (MIN_PIN_CODE + MAX_PIN_CODE)) { - DMLOG(DM_LOG_ERROR, "pinCode err, please check pinCode"); - return PIN_CODE_CHECK_FAILED; - } - - if (pinToken < MIN_PIN_TOKEN || pinToken >= (MIN_PIN_TOKEN + MAX_PIN_TOKEN)) { - DMLOG(DM_LOG_ERROR, "pinToken err, please check pinToken."); - return PIN_TOKEN_CHECK_FAILED; - } - OnPinInputResult(pinCode, pinToken); - DMLOG(DM_LOG_INFO, "CheckAuthenticationByPin authPara end"); - return DEVICEMANAGER_OK; -} - -void AuthManager::OnPinInputResult(int32_t pinCode, int32_t pinToken) -{ - DMLOG(DM_LOG_ERROR, "AuthManager::OnPinInputResult"); - for (auto iter = mWaitScanReqSessionMap_.begin(); iter != mWaitScanReqSessionMap_.end(); iter++) { - auto requestSessionPtr = iter->second; - if (requestSessionPtr != nullptr && requestSessionPtr->IsMyPinToken(pinToken)) { - DMLOG(DM_LOG_INFO, "AuthManager:: OnPinInputResult"); - requestSessionPtr->OnReceivePinCode(pinCode); - } - } -} - -int32_t AuthManager::GetAuthenticationParam(DmAuthParam &authParam) -{ - AbilityRole role = DmAbilityManager::GetInstance().GetAbilityRole(); - DMLOG(DM_LOG_INFO, "GetAuthenticationParam:: role = %d", (int32_t)role); - if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { - if (mPendingReqSessionPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "AuthManager:: Get Auth params FAIL : mPendingReqSessionPtr_(nullptr)"); - return FAIL; - } - authParam.authType = AUTH_TYPE_PIN; // Currently, only Support PinCode, authType not save. - authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole(); - authParam.pinToken = mPendingReqSessionPtr_->GetPinToken(); - DMLOG(DM_LOG_INFO, "GetAuthenticationParam, role is ABILITY_ROLE_INITIATIVE"); - return SUCCESS; - } - - if (mPendingRespSessionPtr == nullptr) { - DMLOG(DM_LOG_ERROR, "AuthManager:: Get Auth params FAIL : mPendingRespSessionPtr(nullptr)"); - return FAIL; - } - - mPendingRespSessionPtr->BuildAuthenticationInfo(authParam); - return SUCCESS; -} - -int32_t AuthManager::GetPincode(int64_t requestId) -{ - if (mPendingRespSessionPtr == nullptr) { - DMLOG(DM_LOG_ERROR, "AuthManager:: GetPincode FAIL : mPendingRespSessionPtr(nullptr)"); - return FAIL; - } - - return mPendingRespSessionPtr->GetPinCodeByReqId(requestId); -} - -std::string AuthManager::GetAuthPara() -{ - return authParam_; -} - -int32_t AuthManager::GetDisplayOwner() -{ - return displayOwner_; -} -} -} diff --git a/services/devicemanagerservice/src/requestauth/request_session.cpp b/services/devicemanagerservice/src/requestauth/request_session.cpp deleted file mode 100644 index 6b46a7fca..000000000 --- a/services/devicemanagerservice/src/requestauth/request_session.cpp +++ /dev/null @@ -1,258 +0,0 @@ -/* - * 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 "nlohmann/json.hpp" - -#include "dm_ability_manager.h" -#include "request_session.h" -#include "constants.h" -#include "device_manager_log.h" -#include "msg_codec.h" -#include "device_manager_errno.h" -#include "ipc_server_adapter.h" -#include "encrypt_utils.h" -#include "softbus_adapter.h" -#include "ipc_server_listener_adapter.h" -#include "hichain_connector.h" -#include "softbus_session.h" - -namespace OHOS { -namespace DistributedHardware { -RequestSession::RequestSession(std::string &hostPkgName, std::string &targetPkgName, const DmDeviceInfo &devReqInfo, - const DmAppImageInfo &imageInfo) -{ - DMLOG(DM_LOG_INFO, "RequestSession construction started"); - mDevInfo_ = devReqInfo; - mImageInfo_ = imageInfo; - mHostPkgName_ = hostPkgName; - mTargetPkgName = targetPkgName; - mPinToken_ = IpcServerAdapter::GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN); - char randStr[TOKEN_LEN] = {0}; - bool res = EncryptUtils::MbedtlsGenRandomStr(randStr, sizeof(randStr), false); - if (res == false) { - DMLOG(DM_LOG_ERROR, "get Random string failed"); - mToken_ = ""; - return; - } - mToken_ = randStr; - DMLOG(DM_LOG_INFO, "RequestSession construction completed"); -} - -std::vector RequestSession::GetRequestCommand(std::string &extrasJson) -{ - return MsgCodec::EncodeReqAppAuth(mToken_, mHostPkgName_, mTargetPkgName, mDevInfo_, mImageInfo_, extrasJson); -} - -int32_t RequestSession::GetPinToken() -{ - return mPinToken_; -} - -bool RequestSession::IsWaitingForScan() -{ - return mStatus_ == StatusType::STATUS_WATING_SCAN_OR_INPUT; -} - -std::string RequestSession::GetToken() -{ - return mToken_; -} - -bool RequestSession::IsMyPinToken(int32_t pinToken) -{ - return pinToken == mPinToken_; -} - -void RequestSession::OnReceivePinCode(int32_t pinCode) -{ - if (mStatus_ != StatusType::STATUS_WATING_SCAN_OR_INPUT) { - DMLOG(DM_LOG_ERROR, "mStatus_ is incorrect, mStatus_: %d", mStatus_); - return; - } - - DMLOG(DM_LOG_INFO, "RequestSession::OnReceivePinCode"); - responseMsgPtr_->SavePinCode(pinCode); - HichainConnector::GetInstance().AddMemeber(mDevInfo_.deviceId, responseMsgPtr_); - mStatus_ = StatusType::STATUS_WAITING_ADD_GROUP; -} - -void RequestSession::OnUserOperate(int32_t action) -{ - if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { - Release(); - return; - } -} - -int64_t RequestSession::GetRequestId() -{ - return mRequestId_; -} - -std::string RequestSession::GetRequestDeviceId() -{ - return mRemoteDeviceId_; -} - -int32_t RequestSession::StartFaService() -{ - DMLOG(DM_LOG_INFO, "RequestSession::StartFaService in"); - AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); - if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { - DMLOG(DM_LOG_ERROR, "RequestSession::StartFaService timeout"); - return FAIL; - } - return SUCCESS; -} - -bool RequestSession::IsFinished() -{ - if (mStatus_ == StatusType::STATUS_INIT || mStatus_ == StatusType::STATUS_FINISH) { - return true; - } - return false; -} - -bool RequestSession::IsMyChannelId(long long channelId) -{ - return channelId == mChannelId_; -} - -void RequestSession::OnReceiveMsg(std::string &msg) -{ - if (mStatus_ != StatusType::STATUS_WAITING_REPLY) { - DMLOG(DM_LOG_ERROR, "StatusType is not waiting reply"); - return; - } - int32_t reply = ParseRespMsg(msg); - DMLOG(DM_LOG_INFO, "reply is : %d", reply); - if (reply == SESSION_REPLY_ACCEPT) { - mStatus_ = StatusType::STATUS_WATING_SCAN_OR_INPUT; - CloseChannel(); - } else { - Release(); - } - NotifyHostAppAuthResult(reply); -} - -std::string RequestSession::GetHostPkgName() -{ - return mHostPkgName_; -} - -std::string RequestSession::GetTargetPkgName() -{ - return mTargetPkgName; -} - -int32_t RequestSession::GetSessionType() -{ - return mSessionType_; -} - -void RequestSession::Release() -{ - if (mStatus_ == StatusType::STATUS_FINISH || mStatus_ == StatusType::STATUS_INIT) { - DMLOG(DM_LOG_INFO, "session is already closed"); - return; - } - DMLOG(DM_LOG_INFO, "close this session"); - mStatus_ = StatusType::STATUS_FINISH; - CloseChannel(); -} - -void RequestSession::CloseChannel() -{ - if (mIsChannelOpened_) { - SoftbusSession::GetInstance().CloseSession(mChannelId_); - DMLOG(DM_LOG_ERROR, "RequestSession:: close the channel"); - mIsChannelOpened_ = false; - } -} - -int32_t RequestSession::ParseRespMsg(std::string &msg) -{ - DMLOG(DM_LOG_INFO, "ParseRespMsg started"); - auto msgResponseAuthPtr = MsgCodec::DecodeResponseAuth(msg); - if (msgResponseAuthPtr == nullptr) { - DMLOG(DM_LOG_ERROR, "DecodeResponseAuth error"); - return SESSION_REPLY_UNKNOWN; - } - responseMsgPtr_ = msgResponseAuthPtr; - int32_t reply = msgResponseAuthPtr->GetReply(); - mRemoteDeviceId_ = msgResponseAuthPtr->GetDeviceId(); - if (reply == SESSION_REPLY_ACCEPT) { - mRemoteNetId_ = msgResponseAuthPtr->GetNetId(); - mRemoteGroupId_ = msgResponseAuthPtr->GetGroupId(); - mRemoteGroupName_ = msgResponseAuthPtr->GetGroupName(); - mRequestId_ = msgResponseAuthPtr->GetRequestId(); - - auto remoteGroupList = msgResponseAuthPtr->GetSyncGroupList(); - SyncDmPrivateGroup(remoteGroupList); - DMLOG(DM_LOG_INFO, "user accepted the auth"); - } - DMLOG(DM_LOG_INFO, "ParseRespMsg completed"); - return reply; -} - -void RequestSession::SetChannelId(long long channelId) -{ - mChannelId_ = channelId; - mIsChannelOpened_ = true; - mStatus_ = StatusType::STATUS_WAITING_REPLY; -} - -void RequestSession::SyncDmPrivateGroup(std::vector &remoteGroupList) -{ - HichainConnector::GetInstance().SyncGroups(mRemoteDeviceId_, remoteGroupList); - DMLOG(DM_LOG_INFO, "RequestSession::syncDmPrivateGroup started"); - std::vector localGroups = {}; - std::vector groupList = {}; - - HichainConnector::GetInstance().GetRelatedGroups(mRemoteDeviceId_, groupList); - HichainConnector::GetInstance().GetSyncGroupList(groupList, localGroups); - if (mRemoteGroupId_ != "") { - localGroups.push_back(mRemoteGroupId_); - } - - std::string synGroupMsg = MsgCodec::EncodeSyncGroup(localGroups, mRemoteDeviceId_); - SoftbusSession::GetInstance().SendMsg(mChannelId_, synGroupMsg); - DMLOG(DM_LOG_INFO, "RequestSession::SyncDmPrivateGroup completed"); -} - -void RequestSession::NotifyHostAppAuthResult(int32_t errorCode) -{ - if (mSessionType_ != SESSION_TYPE_IS_APP_AUTH) { - DMLOG(DM_LOG_ERROR, "wrong session type: %d", mSessionType_); - return; - } - - std::string deviceId = mDevInfo_.deviceId; - if (errorCode != SESSION_REPLY_ACCEPT) { - IpcServerListenerAdapter::GetInstance().OnAuthResult(mHostPkgName_, deviceId, mPinToken_, FAIL, errorCode); - DMLOG(DM_LOG_INFO, "notify host result, errorcode: %d", errorCode); - return; - } - - if (StartFaService() != SUCCESS) { - DMLOG(DM_LOG_INFO, "RequestSession::StartFaService failed"); - return; - } - DMLOG(DM_LOG_INFO, "RequestSession::StartFaService success"); - IpcServerListenerAdapter::GetInstance().OnAuthResult(mHostPkgName_, deviceId, mPinToken_, SUCCESS, errorCode); -} -} -} diff --git a/services/devicemanagerservice/src/requestauth/response_session.cpp b/services/devicemanagerservice/src/requestauth/response_session.cpp deleted file mode 100644 index 54681ec86..000000000 --- a/services/devicemanagerservice/src/requestauth/response_session.cpp +++ /dev/null @@ -1,343 +0,0 @@ -/* - * 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 "nlohmann/json.hpp" - -#include "parameter.h" - -#include "dm_ability_manager.h" -#include "response_session.h" -#include "constants.h" -#include "msg_codec.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" -#include "encrypt_utils.h" -#include "ipc_server_adapter.h" -#include "softbus_adapter.h" -#include "softbus_session.h" -#include "hichain_connector.h" -#include "pthread.h" -#include "ipc_server_adapter.h" -#include "dm_device_info.h" -#include "ipc_server_listener_adapter.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { -const int32_t SESSION_CANCEL_TIMEOUT = 0; -const int32_t SESSION_MSG_RECEIVE_TIMEOUT = 5; -const int32_t SESSION_WAIT_MEMBER_JOIN_TIMEOUT = 120; -const int32_t CANCEL_PICODE_DISPLAY = 1; -const int32_t DEVICE_ID_HALF = 2; -} - -ResponseSession::ResponseSession() -{ - mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; - sem_init(&mSem_, 0, 0); - mRequestId_ = -1; - mGroupId_ = ""; - mGroupName_ = ""; - mReqDeviceId_ = ""; - mMsgRequestAuthPtr_ = nullptr; - mChannelId_ = -1; - mPincode_ = -1; -} - -int64_t ResponseSession::GetRequestId() -{ - return mRequestId_; -} - -int32_t ResponseSession::SendResponseMessage(int32_t reply) -{ - DMLOG(DM_LOG_INFO, "ResponseSession::SendResponseMessage in, reply:%d", reply); - std::string msg; - if (reply == SESSION_REPLY_ACCEPT) { - msg = MsgCodec::EncodeAcceptRespAuth(reply, mRequestId_, mGroupId_, mGroupName_, mReqDeviceId_); - } else { - msg = MsgCodec::EncodeRefuseRespAuth(reply, mReqDeviceId_); - } - - int32_t ret = SoftbusSession::GetInstance().SendMsg(mChannelId_, msg); - if (ret != SUCCESS) { - DMLOG(DM_LOG_INFO, "SendResponseMessage failed ret:%d, reply:%d", ret, reply); - return ret; - } - DMLOG(DM_LOG_INFO, "SendResponseMessage successed, reply:%d", reply); - return SUCCESS; -} - -void ResponseSession::OnUserOperate(int32_t action) -{ - switch (action) { - case FaAction::USER_OPERATION_TYPE_ALLOW_AUTH: { - OnUserConfirm(); - break; - } - case FaAction::USER_OPERATION_TYPE_CANCEL_AUTH: { - OnUserReject(ERROR_USER_REJECT); - break; - } - case FaAction::USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: { - OnUserReject(SESSION_REPLY_AUTH_CONFIRM_TIMEOUT); - break; - } - case FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: { - DMLOG(DM_LOG_ERROR, "cancle pincode display"); - Release(); - break; - } - default: { - DMLOG(DM_LOG_ERROR, "action %d not support", action); - break; - } - } -} - -int32_t ResponseSession::DecodeReqMsg(std::string &message) -{ - std::shared_ptr authMsg = MsgCodec::DecodeRequestAuth(message, mMsgRequestAuthPtr_); - if (authMsg == nullptr) { - DMLOG(DM_LOG_ERROR, "DecodeRequestAuth error, authMsg(nullptr)"); - return FAIL; - } - - if (authMsg->GetMsgSlice() == FAIL) { - DMLOG(DM_LOG_ERROR, "DecodeRequestAuth error, GetMsgSlice() FAIL"); - return FAIL; - } - - mMsgRequestAuthPtr_ = authMsg; - return SUCCESS; -} - -bool ResponseSession::IsMyChannelId(long long channelId) -{ - if (mSessionStatus_ == ResponseSessionStatus::SESSION_INIT) { - return true; - } - - return channelId == mChannelId_ && mChannelId_ > 0; -} - -void OnReceiveTimeOut(void *data) -{ - DMLOG(DM_LOG_ERROR, "OnReceiveTimeOut TimeOut called"); - ResponseSession *respSess = (ResponseSession*)data; - if (respSess == nullptr || respSess->GetStatus() == ResponseSessionStatus::SESSION_INIT) { - DMLOG(DM_LOG_ERROR, "respSess Status is INIT"); - return; - } - - respSess->Release(); -} - -void OnMemberJoinTimeOut(void *data) -{ - DMLOG(DM_LOG_ERROR, "OnMemberJoinTimeOut TimeOut caled"); - ResponseSession *respSess = (ResponseSession*)data; - if (respSess == nullptr || respSess->GetStatus() == ResponseSessionStatus::SESSION_INIT) { - DMLOG(DM_LOG_ERROR, "respSess Status is INIT"); - return; - } - - respSess->SendResponseMessage(SESSION_REPLY_TIMEOUT); - respSess->CancelDisplay(); - respSess->Release(); -} - -void ResponseSession::OnReceiveMsg(long long channelId, std::string &message) -{ - int32_t ret = DecodeReqMsg(message); - if (ret != SUCCESS) { - DMLOG(DM_LOG_ERROR, "DecodeReqMsg failed"); - return; - } - - if (!mReceiveTimerPtr_) { - std::string mReceiveTimerName = "mReceiveTimer"; - mReceiveTimerPtr_ = std::make_shared(mReceiveTimerName); - } - - mReceiveTimerPtr_->Start(SESSION_MSG_RECEIVE_TIMEOUT, OnReceiveTimeOut, this); - if (mMsgRequestAuthPtr_->GetMsgCnt() != mMsgRequestAuthPtr_->GetMsgSlice()) { - return; - } - - mReceiveTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT); - mReqDeviceId_ = mMsgRequestAuthPtr_->GetRequestDeviceId(); - mChannelId_ = channelId; - mPincode_ = GeneratePincode(); - if (StartFaService() != SUCCESS) { - OnUserReject(ERROR_FA_START_FAIL); - return; - } - - mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_USER_CONFIRM; - if (!mMemberJoinTimerPtr_) { - std::string mMemberJoinTimerName = "mMemberJoinTimer"; - mMemberJoinTimerPtr_ = std::make_shared(mMemberJoinTimerName); - } - - mMemberJoinTimerPtr_->Start(SESSION_WAIT_MEMBER_JOIN_TIMEOUT, OnMemberJoinTimeOut, this); -} - -int32_t ResponseSession::GetPinCodeByReqId(int64_t requestId) -{ - if (requestId != mRequestId_) { - DMLOG(DM_LOG_ERROR, "ResponseSession:: GetPinCodeByReqId FAIL : requestId(not match)"); - return FAIL; - } - return mPincode_; -} - -void ResponseSession::BuildAuthenticationInfo(DmAuthParam &authParam) -{ - DMLOG(DM_LOG_INFO, "ResponseSession::BuildAuthenticationInfo in"); - authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole(); - if (mMsgRequestAuthPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "ResponseSession::BuildAuthenticationInfo mMsgRequestAuthPtr_ is nullptr"); - return; - } - - authParam.packageName = mMsgRequestAuthPtr_->mTargetPkg_; - authParam.appName = mMsgRequestAuthPtr_->mAppName_; - authParam.appDescription = mMsgRequestAuthPtr_->mAppDescription_; - authParam.authType = mMsgRequestAuthPtr_->mAuthType_; - authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION - authParam.pincode = mPincode_; - - if (mMsgRequestAuthPtr_ != nullptr) { - authParam.imageinfo = mMsgRequestAuthPtr_->mImageInfo_; - } -} - -int32_t ResponseSession::StartFaService() -{ - DMLOG(DM_LOG_INFO, "ResponseSession::StartFaService in"); - AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_PASSIVE); - if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { - DMLOG(DM_LOG_ERROR, "ResponseSession::StartFaService timeout"); - return FAIL; - } - return SUCCESS; -} - -void ResponseSession::OnGroupCreated(int64_t requestId, const std::string &groupId) -{ - DMLOG(DM_LOG_INFO, "ResponseSession OnGroupCreated in requestId= %lld groupId = %s ", requestId, groupId.c_str()); - - if (requestId != mRequestId_ || groupId.length() == 0) { - DMLOG(DM_LOG_ERROR, "ResponseSession::OnGroupCreated failed, requestId %lld, requestId %lld, groupId %s", - requestId, mRequestId_, groupId.c_str()); - SendResponseMessage(SESSION_REPLY_CREAT_GROUP_FAILED); - CancelDisplay(); - mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; - return; - } - - // save requestId for peer to join, need to be checked in HiChain OnRequest and OnFinish(AddMemberToGroup) callback - mRequestId_ = HichainConnector::GetInstance().GenRequestId(); - mGroupId_ = groupId; - int32_t ret = SendResponseMessage(SESSION_REPLY_ACCEPT); - if (ret != SUCCESS) { - CancelDisplay(); - mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; - return; - } - - DMLOG(DM_LOG_INFO, "Send Accept Resoponse success, wait for peer to AddMemberToGroup"); - mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_PIN_CODE; -} - -void ResponseSession::OnMemberJoin(int64_t requestId, int32_t status) -{ - DMLOG(DM_LOG_INFO, "ResponseSession::OnMemberJoin, result: %d", status); - CancelDisplay(); - mMemberJoinTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT); - Release(); -} - -std::string ResponseSession::GenerateGroupName() -{ - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string sLocalDeviceID = localDeviceId; - std::string groupName = mMsgRequestAuthPtr_->mTargetPkg_ + mMsgRequestAuthPtr_->mHostPkg_ + - sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); - return groupName; -} - -void ResponseSession::OnUserConfirm() -{ - DMLOG(DM_LOG_INFO, "ResponseSession::OnUserConfirm in"); - mGroupName_ = GenerateGroupName(); - HichainConnector::GetInstance().RegisterConnectorCallback(shared_from_this()); - - // save requestId for CreateGroup, need to be checked in callback: OnGroupCreated - mRequestId_ = HichainConnector::GetInstance().GenRequestId(); - int32_t ret = HichainConnector::GetInstance().CreateGroup(mRequestId_, mGroupName_); - if (ret != SUCCESS) { - CancelDisplay(); - mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; - return; - } - mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_GROUP_CREATED; -} - -void ResponseSession::OnUserReject(int32_t errorCode) -{ - DMLOG(DM_LOG_INFO, "ResponseSession::OnUserReject in, errcode %d", errorCode); - SendResponseMessage(errorCode); - Release(); -} - -void ResponseSession::Release() -{ - DMLOG(DM_LOG_INFO, "ResponseSession::Release in"); - mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; - mRequestId_ = -1; - mGroupId_ = ""; - mGroupName_ = ""; - mReqDeviceId_ = ""; - mMsgRequestAuthPtr_ = nullptr; - mChannelId_ = -1; - mPincode_ = -1; -} - -void ResponseSession::CancelDisplay() -{ - DMLOG(DM_LOG_INFO, "Cancel PinCode Display in"); - nlohmann::json jsonObj; - jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PICODE_DISPLAY; - std::string paramJson = jsonObj.dump(); - std::string pkgName = "com.ohos.devicemanagerui"; - IpcServerListenerAdapter::GetInstance().OnFaCall(pkgName, paramJson); - DMLOG(DM_LOG_INFO, "Cancel PinCode Display success"); -} - -int32_t ResponseSession::GetStatus() -{ - return mSessionStatus_; -} - -int32_t ResponseSession::GeneratePincode() -{ - return EncryptUtils::GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/softbus/softbus_adapter.cpp b/services/devicemanagerservice/src/softbus/softbus_adapter.cpp deleted file mode 100644 index f5da3a1a3..000000000 --- a/services/devicemanagerservice/src/softbus/softbus_adapter.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/* - * 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 "softbus_adapter.h" - -#include -#include -#include - -#include - -#include "softbus_bus_center.h" - -#include "dm_device_info.h" -#include "dm_subscribe_info.h" - -#include "anonymous_string.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "softbus_session.h" -#include "system_ability_definition.h" - -#include "ipc_server_listener_adapter.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { -const std::string DEVICE_MANAGER_PACKAGE_NAME = "ohos.distributedhardware.devicemanager"; -const char *DM_CAPABILITY_OSD = "osdCapability"; -const int32_t CHECK_INTERVAL = 100000; // 100ms -const uint32_t SUBSCRIBE_ID_PREFIX_LEN = 16; -const int32_t SUBSCRIBE_ID_MASK = 0x0000FFFF; -const int32_t DISCOVER_DEVICEINFO_MAX_SIZE = 20; -} -std::map>> - SoftbusAdapter::subscribeInfos_; -std::map> SoftbusAdapter::discoverDeviceInfoMap_; -std::vector> SoftbusAdapter::discoverDeviceInfoVector_; -uint16_t SoftbusAdapter::subscribeIdPrefix = 0; -std::mutex SoftbusAdapter::lock_; -INodeStateCb SoftbusAdapter::softbusNodeStateCb_ = { - .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED, - .onNodeOnline = OnSoftBusDeviceOnline, - .onNodeOffline = OnSoftbusDeviceOffline, - .onNodeBasicInfoChanged = OnSoftbusDeviceInfoChanged -}; -IDiscoveryCallback SoftbusAdapter::softbusDiscoverCallback_ = { - .OnDeviceFound = OnSoftbusDeviceFound, - .OnDiscoverFailed = OnSoftbusDiscoverFailed, - .OnDiscoverySuccess = OnSoftbusDiscoverySuccess -}; -IPublishCallback SoftbusAdapter::servicePublishCallback_ = { - .OnPublishSuccess = PublishServiceCallBack::OnPublishSuccess, - .OnPublishFail = PublishServiceCallBack::OnPublishFail -}; - -void SoftbusAdapter::RemoveDiscoverDeviceInfo(const std::string deviceId) -{ - discoverDeviceInfoMap_.erase(deviceId); - auto iter = discoverDeviceInfoVector_.begin(); - while (iter != discoverDeviceInfoVector_.end()) { - if (strcmp(iter->get()->devId, deviceId.c_str()) == 0) { - iter = discoverDeviceInfoVector_.erase(iter); - } else { - ++iter; - } - } -} - -void SoftbusAdapter::OnSoftBusDeviceOnline(NodeBasicInfo *info) -{ - if (info == nullptr) { - DMLOG(DM_LOG_ERROR, "OnSoftBusDeviceOnline NodeBasicInfo is nullptr"); - return; - } - DmDeviceInfo dmDeviceInfo; - - NodeBasicInfoCopyToDmDevice(dmDeviceInfo, *info); - IpcServerListenerAdapter::GetInstance().OnDeviceStateChange(DmDeviceState::DEVICE_STATE_ONLINE, dmDeviceInfo); - - uint8_t udid[UDID_BUF_LEN] = {0}; - int32_t ret = GetNodeKeyInfo(DEVICE_MANAGER_PACKAGE_NAME.c_str(), info->networkId, - NodeDeivceInfoKey::NODE_KEY_UDID, udid, sizeof(udid)); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "GetNodeKeyInfo failed"); - return; - } - std::string deviceId = (char *)udid; - DMLOG(DM_LOG_INFO, "device online, deviceId: %s", GetAnonyString(deviceId).c_str()); - RemoveDiscoverDeviceInfo(deviceId); -} - -void SoftbusAdapter::OnSoftbusDeviceOffline(NodeBasicInfo *info) -{ - if (info == nullptr) { - DMLOG(DM_LOG_ERROR, "OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); - return; - } - DmDeviceInfo dmDeviceInfo; - - NodeBasicInfoCopyToDmDevice(dmDeviceInfo, *info); - IpcServerListenerAdapter::GetInstance().OnDeviceStateChange(DmDeviceState::DEVICE_STATE_OFFLINE, dmDeviceInfo); -} - -void SoftbusAdapter::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) -{ - DMLOG(DM_LOG_INFO, "OnSoftbusDeviceInfoChanged."); - // currently do nothing - (void)type; - (void)info; -} - -void SoftbusAdapter::SaveDiscoverDeviceInfo(const DeviceInfo *deviceInfo) -{ - std::shared_ptr info = std::make_shared(); - DeviceInfo *infoPtr = info.get(); - if (memcpy_s(infoPtr, sizeof(DeviceInfo), deviceInfo, sizeof(DeviceInfo)) != 0) { - DMLOG(DM_LOG_ERROR, "SoftbusAdapter::SaveDiscoverDeviceInfo failed."); - return; - } - - std::string deviceId = deviceInfo->devId; - discoverDeviceInfoMap_[deviceId] = info; - discoverDeviceInfoVector_.push_back(info); - - // Remove the earliest element when reached the max size - if (discoverDeviceInfoVector_.size() == DISCOVER_DEVICEINFO_MAX_SIZE) { - auto iter = discoverDeviceInfoVector_.begin(); - std::string delDevId = iter->get()->devId; - discoverDeviceInfoMap_.erase(delDevId); - discoverDeviceInfoVector_.erase(iter); - } -} - -void SoftbusAdapter::OnSoftbusDeviceFound(const DeviceInfo *device) -{ - if (device == nullptr) { - DMLOG(DM_LOG_ERROR, "deviceinfo is null"); - return; - } - - std::string deviceId = device->devId; - DMLOG(DM_LOG_INFO, "SoftbusAdapter::OnSoftbusDeviceFound device %s found.", GetAnonyString(deviceId).c_str()); - if (IsDeviceOnLine(deviceId)) { - return; - } - - SaveDiscoverDeviceInfo(device); - for (auto iter = subscribeInfos_.begin(); iter != subscribeInfos_.end(); ++iter) { - auto subInfovector = iter->second; - for (auto vectorIter = subInfovector.begin(); vectorIter != subInfovector.end(); ++vectorIter) { - auto info = vectorIter->get(); - DMLOG(DM_LOG_INFO, "subscribe info capability:%s.", info->info.capability); - if (strcmp(DM_CAPABILITY_OSD, info->info.capability) != 0) { - DMLOG(DM_LOG_ERROR, "subscribe info capability invalid."); - } - uint16_t originId = (uint16_t)(((uint32_t)info->info.subscribeId) & SUBSCRIBE_ID_MASK); - std::string strPkgName = iter->first; - DmDeviceInfo dmDeviceInfo; - - DeviceInfoCopyToDmDevice(dmDeviceInfo, *device); - IpcServerListenerAdapter::GetInstance().OnDeviceFound(strPkgName, originId, dmDeviceInfo); - } - } -} - -bool SoftbusAdapter::GetpkgNameBySubscribeId(int32_t adapterId, std::string &pkgName) -{ - for (auto iter = subscribeInfos_.begin(); iter != subscribeInfos_.end(); ++iter) { - std::vector> &subinfoVector = iter->second; - auto vectorIter = subinfoVector.begin(); - for (; vectorIter != subinfoVector.end(); ++vectorIter) { - if (vectorIter->get()->info.subscribeId == adapterId) { - pkgName = iter->first; - return true; - } - } - } - return false; -} - -void SoftbusAdapter::OnSoftbusDiscoverFailed(int32_t subscribeId, DiscoveryFailReason failReason) -{ - DMLOG(DM_LOG_INFO, "In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason); - std::string pkgName; - if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { - DMLOG(DM_LOG_ERROR, "OnSoftbusDiscoverFailed: pkgName not found"); - return; - } - - uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); - IpcServerListenerAdapter::GetInstance().OnDiscoverFailed(pkgName, originId, failReason); -} - -void SoftbusAdapter::OnSoftbusDiscoverySuccess(int32_t subscribeId) -{ - DMLOG(DM_LOG_INFO, "In, subscribeId %d", subscribeId); - std::string pkgName; - if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { - DMLOG(DM_LOG_ERROR, "OnSoftbusDiscoverySuccess: pkgName not found"); - return; - } - uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); - IpcServerListenerAdapter::GetInstance().OnDiscoverySuccess(pkgName, originId); -} - -bool SoftbusAdapter::GetsubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId) -{ - DMLOG(DM_LOG_INFO, "GetsubscribeIdAdapter in, pkgName: %s, originId:%d", pkgName.c_str(), - (int32_t)originId); - auto iter = subscribeInfos_.find(pkgName); - if (iter == subscribeInfos_.end()) { - DMLOG(DM_LOG_ERROR, "subscribeInfo not find for pkgName: %s", pkgName.c_str()); - return false; - } - - std::vector> &subinfoVector = iter->second; - auto vectorIter = subinfoVector.begin(); - for (; vectorIter != subinfoVector.end(); ++vectorIter) { - if (vectorIter->get()->subscribeIdOrigin == originId) { - DMLOG(DM_LOG_ERROR, "find adapterId:%d for pkgName: %s, originId:%d", - vectorIter->get()->info.subscribeId, pkgName.c_str(), (int32_t)originId); - adapterId = vectorIter->get()->info.subscribeId; - return true; - } - } - DMLOG(DM_LOG_ERROR, "subscribe not find. pkgName: %s, originId:%d", pkgName.c_str(), (int32_t)originId); - return false; -} - -int32_t SoftbusAdapter::Init() -{ - int32_t ret; - int32_t retryTimes = 0; - do { - ret = RegNodeDeviceStateCb(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &softbusNodeStateCb_); - if (ret != DEVICEMANAGER_OK) { - ++retryTimes; - DMLOG(DM_LOG_ERROR, "RegNodeDeviceStateCb failed with ret %d, retryTimes %d", ret, retryTimes); - usleep(CHECK_INTERVAL); - } - } while (ret != DEVICEMANAGER_OK); - DMLOG(DM_LOG_INFO, "RegNodeDeviceStateCb success."); - SoftbusSession::GetInstance().Start(); - - PublishInfo dmPublishInfo; - dmPublishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; - dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; - dmPublishInfo.medium = ExchanageMedium::AUTO; - dmPublishInfo.freq = ExchangeFreq::HIGH; - dmPublishInfo.capability = DM_CAPABILITY_OSD; - dmPublishInfo.capabilityData = nullptr; - dmPublishInfo.dataLen = 0; - ret = PublishService(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &dmPublishInfo, &servicePublishCallback_); - DMLOG(DM_LOG_INFO, "service publish result is : %d", ret); - return ret; -} - -int32_t SoftbusAdapter::GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum) -{ - DMLOG(DM_LOG_INFO, "DM_GetSoftbusTrustDevices start, pkgName: %s", pkgName.c_str()); - int32_t ret = GetAllNodeDeviceInfo(DEVICE_MANAGER_PACKAGE_NAME.c_str(), info, infoNum); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "GetAllNodeDeviceInfo failed with ret %d", ret); - return ret; - } - DMLOG(DM_LOG_INFO, "success, pkgName: %s, deviceCount %d", pkgName.c_str(), *infoNum); - return DEVICEMANAGER_OK; -} - -int32_t SoftbusAdapter::StartDiscovery(std::string &pkgName, SubscribeInfo *info) -{ - std::shared_ptr subinfo = nullptr; - if (subscribeInfos_.find(pkgName) == subscribeInfos_.end()) { - subscribeInfos_[pkgName] = {}; - } - - auto iter = subscribeInfos_.find(pkgName); - std::vector> &subinfoVector = iter->second; - auto vectorIter = subinfoVector.begin(); - for (; vectorIter != subinfoVector.end(); ++vectorIter) { - if (vectorIter->get()->subscribeIdOrigin == info->subscribeId) { - subinfo = *vectorIter; - break; - } - } - if (subinfo == nullptr) { - std::lock_guard autoLock(lock_); - subinfo = std::make_shared(); - subinfo->subscribeIdOrigin = info->subscribeId; - subinfo->subscribeIdPrefix = subscribeIdPrefix++; - subinfo->info = *info; - - uint32_t uSubscribeId = static_cast(info->subscribeId); - uSubscribeId = (subinfo->subscribeIdPrefix << SUBSCRIBE_ID_PREFIX_LEN) | uSubscribeId; - subinfo->info.subscribeId = static_cast(uSubscribeId); - } - if (vectorIter == subinfoVector.end()) { - subinfoVector.push_back(subinfo); - } - DMLOG(DM_LOG_INFO, "StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", - pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); - DMLOG(DM_LOG_INFO, "Capability: %s", subinfo->info.capability); - int32_t ret = ::StartDiscovery(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &subinfo->info, &softbusDiscoverCallback_); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "StartDiscovery failed with ret %d.", ret); - return DEVICEMANAGER_DISCOVERY_FAILED; - } - return DEVICEMANAGER_OK; -} - -int32_t SoftbusAdapter::StopDiscovery(std::string &pkgName, uint16_t subscribeId) -{ - int32_t subscribeIdAdapter = -1; - if (!GetsubscribeIdAdapter(pkgName, subscribeId, subscribeIdAdapter)) { - DMLOG(DM_LOG_ERROR, "StopDiscovery failed, subscribeId not match"); - return DEVICEMANAGER_FAILED; - } - - DMLOG(DM_LOG_INFO, "StopDiscovery begin, pkgName: %s, subscribeId:%d, subscribeIdAdapter:%d", - pkgName.c_str(), (int32_t)subscribeId, subscribeIdAdapter); - int32_t ret = ::StopDiscovery(DEVICE_MANAGER_PACKAGE_NAME.c_str(), subscribeIdAdapter); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "StopDiscovery failed with ret %d", ret); - return ret; - } - - auto iter = subscribeInfos_.find(pkgName); - auto subinfoVector = iter->second; - auto vectorIter = subinfoVector.begin(); - while (vectorIter != subinfoVector.end()) { - if (vectorIter->get()->subscribeIdOrigin == subscribeId) { - vectorIter = subinfoVector.erase(vectorIter); - break; - } else { - ++vectorIter; - } - } - if (subinfoVector.empty()) { - subscribeInfos_.erase(pkgName); - } - DMLOG(DM_LOG_INFO, "DM_StopSoftbusDiscovery completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; -} - -bool SoftbusAdapter::IsDeviceOnLine(std::string &deviceId) -{ - NodeBasicInfo *info = nullptr; - int32_t infoNum = 0; - - if (GetTrustDevices(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &info, &infoNum) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine DM_GetSoftbusTrustDevices failed"); - return false; - } - - bool bDeviceOnline = false; - for (int32_t i = 0; i < infoNum; ++i) { - NodeBasicInfo *nodeBasicInfo = info + i; - if (nodeBasicInfo == nullptr) { - DMLOG(DM_LOG_ERROR, "nodeBasicInfo is empty for index %d, infoNum %d.", i, infoNum); - continue; - } - std::string networkId = nodeBasicInfo->networkId; - if (networkId == deviceId) { - DMLOG(DM_LOG_INFO, "DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str()); - bDeviceOnline = true; - break; - } - uint8_t udid[UDID_BUF_LEN] = {0}; - int32_t ret = GetNodeKeyInfo(DEVICE_MANAGER_PACKAGE_NAME.c_str(), networkId.c_str(), - NodeDeivceInfoKey::NODE_KEY_UDID, udid, sizeof(udid)); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine GetNodeKeyInfo failed"); - break; - } - - if (strcmp((char *)udid, deviceId.c_str()) == 0) { - DMLOG(DM_LOG_INFO, "DM_IsDeviceOnLine devccie %s online", GetAnonyString(deviceId).c_str()); - bDeviceOnline = true; - break; - } - } - FreeNodeInfo(info); - return bDeviceOnline; -} - -int32_t SoftbusAdapter::GetConnectionIpAddr(std::string deviceId, std::string &ipAddr) -{ - auto iter = discoverDeviceInfoMap_.find(deviceId); - if (iter == discoverDeviceInfoMap_.end()) { - DMLOG(DM_LOG_ERROR, "deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str()); - return DEVICEMANAGER_FAILED; - } - - DeviceInfo *deviceInfo = iter->second.get(); - if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { - DMLOG(DM_LOG_ERROR, "deviceInfo addrNum not valid, addrNum %d", deviceInfo->addrNum); - return DEVICEMANAGER_FAILED; - } - - for (uint32_t i = 0; i < deviceInfo->addrNum; ++i) { - // currently, only support CONNECT_ADDR_WLAN - if (deviceInfo->addr[i].type != ConnectionAddrType::CONNECTION_ADDR_WLAN && - deviceInfo->addr[i].type != ConnectionAddrType::CONNECTION_ADDR_ETH) { - continue; - } - ipAddr = deviceInfo->addr[i].info.ip.ip; - DMLOG(DM_LOG_INFO, "DM_GetConnectionIpAddr get ip ok."); - return DEVICEMANAGER_OK; - } - DMLOG(DM_LOG_ERROR, "failed to get ipAddr for deviceId %s", GetAnonyString(deviceId).c_str()); - return DEVICEMANAGER_FAILED; -} - -// eth >> wlan >> ble >> br -ConnectionAddr *SoftbusAdapter::GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type) -{ - if (deviceInfo == nullptr) { - return nullptr; - } - for (uint32_t i = 0; i < deviceInfo->addrNum; ++i) { - if (deviceInfo->addr[i].type == type) { - return &deviceInfo->addr[i]; - } - } - return nullptr; -} - -ConnectionAddr *SoftbusAdapter::GetConnectAddr(std::string deviceId) -{ - auto iter = discoverDeviceInfoMap_.find(deviceId); - if (iter == discoverDeviceInfoMap_.end()) { - DMLOG(DM_LOG_ERROR, "deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str()); - return nullptr; - } - - DeviceInfo *deviceInfo = iter->second.get(); - if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { - DMLOG(DM_LOG_ERROR, "deviceInfo addrNum not valid, addrNum %d", deviceInfo->addrNum); - return nullptr; - } - - ConnectionAddr *addr = nullptr; - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH); - if (addr != nullptr) { - DMLOG(DM_LOG_INFO, "get ETH ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); - return addr; - } - - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); - if (addr != nullptr) { - DMLOG(DM_LOG_INFO, "get WLAN ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); - return addr; - } - - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); - if (addr != nullptr) { - DMLOG(DM_LOG_INFO, "get BLE ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); - return addr; - } - - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); - if (addr != nullptr) { - DMLOG(DM_LOG_INFO, "get BR ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); - return addr; - } - - DMLOG(DM_LOG_ERROR, "failed to get ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); - return nullptr; -} - -void SoftbusAdapter::NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo) -{ - (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), nodeBasicInfo.networkId, - std::min(sizeof(dmDeviceInfo.deviceId), sizeof(nodeBasicInfo.networkId))) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - dmDeviceInfo.deviceTypeId = (DMDeviceType)nodeBasicInfo.deviceTypeId; -} - -void SoftbusAdapter::DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo) -{ - (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - dmDeviceInfo.deviceTypeId = (DMDeviceType)deviceInfo.devType; -} - -void PublishServiceCallBack::OnPublishSuccess(int32_t publishId) -{ - DMLOG(DM_LOG_INFO, "service publish succeed, publishId: %d", publishId); -} - -void PublishServiceCallBack::OnPublishFail(int32_t publishId, PublishFailReason reason) -{ - DMLOG(DM_LOG_INFO, "service publish failed, publishId: %d, reason: %d", publishId, reason); -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/softbus/softbus_session.cpp b/services/devicemanagerservice/src/softbus/softbus_session.cpp deleted file mode 100644 index 84bf739a2..000000000 --- a/services/devicemanagerservice/src/softbus/softbus_session.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* - * 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 "softbus_session.h" -#include "softbus_adapter.h" -#include "anonymous_string.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" -#include "auth_manager.h" -#include "encrypt_utils.h" -#include "constants.h" -#include "session.h" -#include "inner_session.h" - -namespace OHOS { -namespace DistributedHardware { -static int32_t SessionOpened(int32_t sessionId, int32_t result) -{ - return SoftbusSession::GetInstance().OnSessionOpened(sessionId, result); -} - -static void SessionClosed(int32_t sessionId) -{ - SoftbusSession::GetInstance().OnSessionClosed(sessionId); -} - -static void BytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) -{ - SoftbusSession::GetInstance().GetInstance().OnBytesReceived(sessionId, data, dataLen); -} - -static void MessageReceived(int32_t sessionId, const void *data, uint32_t dataLen) -{ - (void)sessionId; - (void)data; - (void)dataLen; - DMLOG(DM_LOG_INFO, "sessionId:%d, dataLen:%d", sessionId, dataLen); -} - -static void StreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, const FrameInfo *param) -{ - (void)sessionId; - (void)data; - (void)ext; - (void)param; - DMLOG(DM_LOG_INFO, "sessionId:%d", sessionId); -} - -IMPLEMENT_SINGLE_INSTANCE(SoftbusSession); - -SoftbusSession::~SoftbusSession() -{ - (void)RemoveSessionServer(PKG_NAME, SESSION_NAME); -} - -int32_t SoftbusSession::Start() -{ - DMLOG(DM_LOG_INFO, "SoftbusSession start"); - ISessionListener iSessionListener = { - .OnSessionOpened = SessionOpened, - .OnSessionClosed = SessionClosed, - .OnBytesReceived = BytesReceived, - .OnMessageReceived = MessageReceived, - .OnStreamReceived = StreamReceived - }; - int32_t ret = CreateSessionServer(PKG_NAME, SESSION_NAME, &iSessionListener); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_DEBUG, "CreateSessionServer failed"); - return DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; - } - return DEVICEMANAGER_OK; -} - -int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) -{ - if (result != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_INFO, "session open failed, sessionId %d", sessionId); - if (sessionIdSet_.count(sessionId) > 0) { - sessionIdSet_.erase(sessionId); - messages_.clear(); - } - return DEVICEMANAGER_OK; - } - - int32_t sessionSide = GetSessionSide(sessionId); - DMLOG(DM_LOG_INFO, "session open succeed, sessionId %d, sessionSide %d", sessionId, sessionSide); - if (sessionSide == AUTH_SESSION_SIDE_CLIENT) { - for (auto msg : messages_) { - int32_t ret = SendMsg(sessionId, msg); - if (ret != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_INFO, "send message failed"); - return ret; - } - } - } else { - sessionIdSet_.insert(sessionId); - } - return DEVICEMANAGER_OK; -} - -void SoftbusSession::OnSessionClosed(int32_t sessionId) -{ - DMLOG(DM_LOG_INFO, "OnSessionClosed, sessionId:%d", sessionId); - if (sessionIdSet_.count(sessionId) > 0) { - sessionIdSet_.erase(sessionId); - } -} - -void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) -{ - DMLOG(DM_LOG_INFO, "OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen); - if (sessionId < 0 || data == nullptr || dataLen <= 0) { - DMLOG(DM_LOG_INFO, "OnBytesReceived param check failed"); - return; - } - - uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); - if (buf == nullptr) { - DMLOG(DM_LOG_ERROR, "SendMsg: malloc memory failed"); - return; - } - - int32_t outLen = 0; - int32_t ret = EncryptUtils::MbedtlsDecrypt((const uint8_t*)data, dataLen, buf, dataLen, &outLen); - if (ret != DEVICEMANAGER_OK || outLen > (int32_t)dataLen) { - DMLOG(DM_LOG_ERROR, "MbedtlsDecrypt data failed"); - free(buf); - return; - } - - std::string message = (char *)buf; - AuthManager::GetInstance().OnReceiveMsg(sessionId, message); - free(buf); - DMLOG(DM_LOG_INFO, "OnBytesReceived completed"); - return; -} - -void SoftbusSession::CloseSession(int32_t sessionId) -{ - DMLOG(DM_LOG_INFO, "CloseSession in"); - ::CloseSession(sessionId); -} - -int32_t SoftbusSession::SendData(int32_t sessionId, const void *data, int32_t len) -{ - DMLOG(DM_LOG_INFO, "in, datalen:%d", len); - int32_t ret = DEVICEMANAGER_FAILED; - if (sessionIdSet_.count(sessionId) > 0) { - ret = SendBytes(sessionId, data, len); - if (ret != DEVICEMANAGER_OK) { - return DEVICEMANAGER_FAILED; - } - } else { - DMLOG(DM_LOG_INFO, "in, datalen:%d", len); - } - return ret; -} - -// send message by sessionId (channel opened) -int32_t SoftbusSession::SendMsg(int32_t sessionId, std::string &message) -{ - DMLOG(DM_LOG_ERROR, "start SendMsg"); - uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MSG_MAX_SIZE + ENCRYPT_TAG_LEN)); - if (buf == nullptr) { - DMLOG(DM_LOG_ERROR, "SendMsg: malloc memory failed"); - return DEVICEMANAGER_MALLOC_ERROR; - } - int32_t outLen = 0; - int32_t ret = EncryptUtils::MbedtlsEncrypt((const uint8_t *)message.c_str(), message.size(), buf, MSG_MAX_SIZE, - &outLen); - if (ret != DEVICEMANAGER_OK || outLen > MSG_MAX_SIZE) { - DMLOG(DM_LOG_ERROR, "MbedtlsEncrypt data failed"); - free(buf); - return ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; - } - ret = SendData(sessionId, buf, outLen); - free(buf); - return ret; -} - -// send message while the channel is not opend -int32_t SoftbusSession::SendMessages(const char *deviceId, std::vector &message) -{ - DMLOG(DM_LOG_ERROR, "open channel and start SendMsg"); - int32_t sessionId = -1; - messages_ = message; - ConnectionAddr *addrInfo = SoftbusAdapter::GetConnectAddr(deviceId); - if (addrInfo == nullptr) { - DMLOG(DM_LOG_ERROR, "GetConnectAddr error"); - return sessionId; - } - - sessionId = ::OpenAuthSession(SESSION_NAME, addrInfo, 1, nullptr); - if (sessionId < 0) { - DMLOG(DM_LOG_ERROR, "open session error, ret:%d", sessionId); - return sessionId; - } - sessionIdSet_.insert(sessionId); - DMLOG(DM_LOG_INFO, "opened auth session is:%d", sessionId); - return sessionId; -} - -void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) -{ - char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; - int32_t ret = ::GetPeerDeviceId(sessionId, &peerDeviceId[0], DEVICE_UUID_LENGTH); - if (ret == 0) { - peerDevId = peerDeviceId; - DMLOG(DM_LOG_INFO, "GetPeerDeviceId success for session:%d, peerDeviceId:%s", sessionId, - GetAnonyString(peerDevId).c_str()); - return; - } - - DMLOG(DM_LOG_ERROR, "GetPeerDeviceId failed for session:%d", sessionId); - peerDevId = ""; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/timer/dm_timer.cpp b/services/devicemanagerservice/src/timer/dm_timer.cpp deleted file mode 100644 index 8e736945a..000000000 --- a/services/devicemanagerservice/src/timer/dm_timer.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/* - * 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 - -#include "securec.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { -const int32_t MILL_SECONDS_PER_SECOND = 1000; -} -DmTimer::DmTimer(std::string &name) -{ - mStatus_ = DmTimerStatus::DM_STATUS_INIT; - mTimeOutSec_ = 0; - mHandle_ = nullptr; - mHandleData_ = nullptr; - (void)memset_s(mTimeFd_, sizeof(mTimeFd_), 0, sizeof(mTimeFd_)); - (void)memset_s(&mEv_, sizeof(mEv_), 0, sizeof(mEv_)); - (void)memset_s(mEvents_, sizeof(mEvents_), 0, sizeof(mEvents_)); - mEpFd_ = 0; - mTimerName_ = name; -} - -DmTimer::~DmTimer() -{ - DMLOG(DM_LOG_INFO, "DmTimer %s Destory in", mTimerName_.c_str()); - Release(); -} - -DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) -{ - DMLOG(DM_LOG_INFO, "DmTimer %s start timeout(%d)", mTimerName_.c_str(), timeOut); - if (mStatus_ != DmTimerStatus::DM_STATUS_INIT) { - return DmTimerStatus::DM_STATUS_BUSY; - } - - mTimeOutSec_ = timeOut; - mHandle_ = handle; - mHandleData_ = data; - - if (CreateTimeFd()) { - return DmTimerStatus::DM_STATUS_CREATE_ERROR; - } - - mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; - mThread_ = std::thread(&DmTimer::WiteforTimeout, this); - mThread_.detach(); - - return mStatus_; -} - -void DmTimer::Stop(int32_t code) -{ - DMLOG(DM_LOG_INFO, "DmTimer %s Stop code (%d)", mTimerName_.c_str(), code); - if (mTimeFd_[1]) { - char event = 'S'; - if (write(mTimeFd_[1], &event, 1) < 0) { - DMLOG(DM_LOG_ERROR, "DmTimer %s Stop timer failed, errno %d", mTimerName_.c_str(), errno); - return; - } - DMLOG(DM_LOG_INFO, "DmTimer %s Stop success", mTimerName_.c_str()); - } - - return; -} - -void DmTimer::WiteforTimeout() -{ - DMLOG(DM_LOG_INFO, "DmTimer %s start timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); - - int32_t nfds = epoll_wait(mEpFd_, mEvents_, MAXEVENTS, mTimeOutSec_ * MILL_SECONDS_PER_SECOND); - if (nfds < 0) { - DMLOG(DM_LOG_ERROR, "DmTimer %s epoll_wait returned n=%d, error: %d", mTimerName_.c_str(), nfds, errno); - } - - char event = 0; - if (nfds > 0) { - if (mEvents_[0].events & EPOLLIN) { - int num = read(mTimeFd_[0], &event, 1); - if (num > 0) { - DMLOG(DM_LOG_INFO, "DmTimer %s exit with event %d", mTimerName_.c_str(), event); - } else { - DMLOG(DM_LOG_ERROR, "DmTimer %s exit with errno %d", mTimerName_.c_str(), errno); - } - } - Release(); - return; - } - - mHandle_(mHandleData_); - Release(); - - DMLOG(DM_LOG_ERROR, "DmTimer %s end timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); - return; -} - -int32_t DmTimer::CreateTimeFd() -{ - DMLOG(DM_LOG_INFO, "DmTimer %s creatTimeFd", mTimerName_.c_str()); - int ret = 0; - - ret = pipe(mTimeFd_); - if (ret < 0) { - DMLOG(DM_LOG_ERROR, "DmTimer %s CreateTimeFd fail:(%d) errno(%d)", mTimerName_.c_str(), ret, errno); - return ret; - } - - mEv_.data.fd = mTimeFd_[0]; - mEv_.events = EPOLLIN | EPOLLET; - mEpFd_ = epoll_create(MAXEVENTS); - ret = epoll_ctl(mEpFd_, EPOLL_CTL_ADD, mTimeFd_[0], &mEv_); - if (ret != 0) { - Release(); - } - - return ret; -} - -void DmTimer::Release() -{ - DMLOG(DM_LOG_INFO, "DmTimer %s Release in", mTimerName_.c_str()); - if (mStatus_ == DmTimerStatus::DM_STATUS_INIT) { - DMLOG(DM_LOG_INFO, "DmTimer %s already Release", mTimerName_.c_str()); - return; - } - mStatus_ = DmTimerStatus::DM_STATUS_INIT; - close(mTimeFd_[0]); - close(mTimeFd_[1]); - if (mEpFd_ >= 0) { - close(mEpFd_); - } - mTimeFd_[0] = 0; - mTimeFd_[1] = 0; - mEpFd_ = 0; -} -} -} diff --git a/test/BUILD.gn b/test/BUILD.gn deleted file mode 100644 index d29faeb19..000000000 --- a/test/BUILD.gn +++ /dev/null @@ -1,18 +0,0 @@ -# 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. - -group("test") { - testonly = true - - deps = [ "unittest:unittest" ] -} diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn deleted file mode 100644 index 9c2c9dcce..000000000 --- a/test/unittest/BUILD.gn +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -module_out_path = "deviceManager_stander/inner_kits" - -group("unittest") { - testonly = true - - deps = [ ":device_manager_impl_test" ] -} - -## UnitTest device_manager_impl_test {{{ -ohos_unittest("device_manager_impl_test") { - module_out_path = module_out_path - - sources = [ "device_manager_impl_test.cpp" ] - - deps = [ ":device_manager_test_common" ] -} - -## UnitTest device_manager_impl_test }}} - -## Build device_manager_test_common.a {{{ -config("device_manager_test_common_public_config") { - include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/ipc/standard", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/ipc", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/notify", - "${utils_path}/include/log", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "${utils_path}/include/ipc/standard", - "${common_path}/include", - "//third_party/json/include", - ] - - cflags = [ - "-Wall", - "-Werror", - "-g3", - "-Dprivate=public", - "-Dprotected=public", - ] -} - -ohos_static_library("device_manager_test_common") { - testonly = true - - visibility = [ ":*" ] - - public_configs = [ ":device_manager_test_common_public_config" ] - - public_deps = [ - "${utils_path}:devicemanagerutils", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//third_party/googletest:gmock", - "//utils/native/base:utils", - "//utils/native/base:utils", - ] -} -## Build device_manager_test_common.a }}} diff --git a/test/unittest/device_manager_impl_test.cpp b/test/unittest/device_manager_impl_test.cpp deleted file mode 100644 index a6070729f..000000000 --- a/test/unittest/device_manager_impl_test.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/* - * 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_impl_test.h" -#include "device_manager_errno.h" -#include "dm_device_info.h" - -#include - -namespace OHOS { -namespace DistributedHardware { -void DeviceManagerImplTest::SetUp() -{ -} - -void DeviceManagerImplTest::TearDown() -{ -} - -void DeviceManagerImplTest::SetUpTestCase() -{ -} - -void DeviceManagerImplTest::TearDownTestCase() -{ -} - -namespace { -HWTEST_F(DeviceManagerImplTest, InitDeviceManager, testing::ext::TestSize.Level0) -{ - std::string packName = ""; - int32_t ret= DeviceManager::GetInstance().InitDeviceManager(packName, nullptr); - ASSERT_EQ(ret, DEVICEMANAGER_INVALID_VALUE); -} - -HWTEST_F(DeviceManagerImplTest, AuthenticateDevice1, testing::ext::TestSize.Level0) -{ - std::string packName = ""; - DmDeviceInfo dmDeviceInfo; - DmAppImageInfo dmAppImageInfo; - std::string extra= ""; - std::shared_ptr callback = nullptr; - int32_t ret= DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, - dmAppImageInfo, extra, callback); - ASSERT_EQ(ret, DEVICEMANAGER_INVALID_VALUE); -} - -HWTEST_F(DeviceManagerImplTest, AuthenticateDevice2, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.helloworld"; - DmDeviceInfo dmDeviceInfo; - DmAppImageInfo dmAppImageInfo; - std::string extra = ""; - std::shared_ptr callback = nullptr; - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DEVICEMANAGER_FAILED)); - int32_t ret= DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, - dmAppImageInfo, extra, callback); - ASSERT_EQ(ret, DEVICEMANAGER_IPC_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; -} - -HWTEST_F(DeviceManagerImplTest, AuthenticateDevice3, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.helloworld"; - DmDeviceInfo dmDeviceInfo; - DmAppImageInfo dmAppImageInfo; - std::string extra = ""; - std::shared_ptr callback = nullptr; - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DEVICEMANAGER_OK)); - int32_t ret= DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, - dmAppImageInfo, extra, callback); - ASSERT_EQ(ret, DEVICEMANAGER_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; -} - -HWTEST_F(DeviceManagerImplTest, CheckAuthentication1, testing::ext::TestSize.Level0) -{ - std::string packName = ""; - std::string authPara = ""; - std::shared_ptr callback = nullptr; - int32_t ret = DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); - ASSERT_EQ(ret, DEVICEMANAGER_INVALID_VALUE); -} - -HWTEST_F(DeviceManagerImplTest, CheckAuthentication2, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.helloworld"; - std::string authPara = ""; - std::shared_ptr callback = nullptr; - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DEVICEMANAGER_FAILED)); - int32_t ret= DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); - ASSERT_EQ(ret, DEVICEMANAGER_IPC_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; -} - -HWTEST_F(DeviceManagerImplTest, CheckAuthentication3, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.helloworld"; - std::string authPara = ""; - std::shared_ptr callback = nullptr; - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DEVICEMANAGER_OK)); - int32_t ret= DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); - ASSERT_EQ(ret, DEVICEMANAGER_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; -} - -HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery1, testing::ext::TestSize.Level0) -{ - std::string packName = ""; - DmSubscribeInfo subscribeInfo; - std::shared_ptr callback = nullptr; - int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, callback); - ASSERT_EQ(ret, DEVICEMANAGER_INVALID_VALUE); -} - -HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.helloworld"; - DmSubscribeInfo subscribeInfo; - test_callback_ = std::make_shared(); - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DEVICEMANAGER_OK)); - int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, test_callback_); - ASSERT_EQ(ret, DEVICEMANAGER_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; -} - -HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.helloworld"; - DmSubscribeInfo subscribeInfo; - test_callback_ = std::make_shared(); - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DEVICEMANAGER_FAILED)); - int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, test_callback_); - ASSERT_EQ(ret, DEVICEMANAGER_IPC_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; -} -} // namespace - -void DeviceDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) -{ - (void)subscribeId; -} - -void DeviceDiscoverCallback::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) -{ - (void)subscribeId; - (void)failedReason; -} - -void DeviceDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) -{ - (void)subscribeId; -} -} // namespace Vsync -} // namespace OHOS diff --git a/test/unittest/device_manager_impl_test.h b/test/unittest/device_manager_impl_test.h deleted file mode 100644 index 9efa3619b..000000000 --- a/test/unittest/device_manager_impl_test.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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_IMPL_TEST_H -#define OHOS_DEVICE_MANAGER_IMPL_TEST_H - -#include -#include - -#include "mock/mock_ipc_client_proxy.h" -#include "device_manager_impl.h" -#include "device_manager_callback.h" -#include "device_manager.h" - -namespace OHOS { -namespace DistributedHardware { -class DeviceManagerImplTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - virtual void SetUp() override; - virtual void TearDown() override; -private: - std::shared_ptr test_callback_ = nullptr; -}; - -class DeviceDiscoverCallback : public DiscoverCallback { -public: - DeviceDiscoverCallback() : DiscoverCallback() {} - virtual ~DeviceDiscoverCallback() override {} - virtual void OnDiscoverySuccess(uint16_t subscribeId) override; - virtual void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) override; - virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) override; -}; -} // namespace Vsync -} // namespace OHOS - -#endif // OHOS_DEVICE_MANAGER_IMPL_TEST_H diff --git a/test/unittest/mock/mock_ipc_client_proxy.h b/test/unittest/mock/mock_ipc_client_proxy.h deleted file mode 100644 index ece83e9fb..000000000 --- a/test/unittest/mock/mock_ipc_client_proxy.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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_MOCK_IPC_CLIENT_PROXY_H -#define OHOS_MOCK_IPC_CLIENT_PROXY_H - -#include -#include - -#include "ipc_client_proxy.h" - -namespace OHOS { -namespace DistributedHardware { -class MockIpcClientProxy : public IpcClientProxy, public RefBase { -public: - MOCK_METHOD3(SendRequest, int32_t(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp)); -}; -} // namespace DistributedHardware -} // namespace OHOS - -#endif // OHOS_MOCK_IPC_CLIENT_PROXY_H diff --git a/utils/BUILD.gn b/utils/BUILD.gn index b84acfffa..888ae7f79 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -26,8 +26,6 @@ if (defined(ohos_lite)) { "${common_path}/include/ipc", "${common_path}/include/ipc/model", "include", - "include/log", - "include/cipher", "include/ipc/lite", ] @@ -49,10 +47,10 @@ if (defined(ohos_lite)) { ] sources = [ - "src/anonymous_string.cpp", - "src/cipher/encrypt_utils.cpp", + "src/dm_anonymous.cpp", + "src/dm_log.cpp", + "src/dm_random.cpp", "src/ipc/lite/ipc_cmd_register.cpp", - "src/log/dm_log.cpp", ] defines = [ @@ -63,10 +61,7 @@ if (defined(ohos_lite)) { deps = [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", - "//foundation/communication/dsoftbus/sdk:softbus_client", "//foundation/communication/ipc_lite:liteipc_adapter", - "//foundation/distributedschedule/samgr_lite/samgr:samgr", "//third_party/bounds_checking_function:libsec_shared", "//third_party/mbedtls:mbedtls_shared", "//utils/native/lite:utils", @@ -75,25 +70,23 @@ if (defined(ohos_lite)) { } else { ohos_shared_library("devicemanagerutils") { include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", "${common_path}/include", "${common_path}/include/ipc", "${common_path}/include/ipc/model", "include", - "include/cipher", - "include/log", "include/ipc/standard", + "//utils/native/base/include", + "//utils/system/safwk/native/include", "//base/security/deviceauth/interfaces/innerkits", "//base/startup/syspara_lite/adapter/native/syspara/include", "//third_party/json/include", ] sources = [ - "src/anonymous_string.cpp", - "src/cipher/encrypt_utils.cpp", + "src/dm_anonymous.cpp", + "src/dm_log.cpp", + "src/dm_random.cpp", "src/ipc/standard/ipc_cmd_register.cpp", - "src/log/dm_log.cpp", ] deps = [ @@ -108,19 +101,12 @@ if (defined(ohos_lite)) { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", - "dsoftbus_standard:softbus_client", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - "startup_l2:syspara", ] subsystem_name = "distributedhardware" part_name = "device_manager_base" } -} +} \ No newline at end of file diff --git a/utils/include/anonymous_string.h b/utils/include/anonymous_string.h deleted file mode 100644 index 4144e517c..000000000 --- a/utils/include/anonymous_string.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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 ANONYMOUS_STRING_H -#define ANONYMOUS_STRING_H -#include - -namespace OHOS { -namespace DistributedHardware { -std::string GetAnonyString(const std::string &value); -std::string GetAnonyInt32(const int32_t value); -} -} -#endif \ No newline at end of file diff --git a/utils/include/cipher/encrypt_utils.h b/utils/include/cipher/encrypt_utils.h deleted file mode 100644 index db19b2364..000000000 --- a/utils/include/cipher/encrypt_utils.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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_ENCRYPT_UTILS_H -#define OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H - -#include -#include - -namespace OHOS { -namespace DistributedHardware { -class EncryptUtils { -public: - static int32_t MbedtlsBase64Encode(uint8_t *dst, size_t dlen, size_t *olen, - const uint8_t *src, size_t slen); - static int32_t MbedtlsBase64Decode(uint8_t *dst, size_t dlen, size_t *olen, - const uint8_t *src, size_t slen); - static int32_t GenRandInt(int32_t randMin, int32_t randMax); - static int64_t GenRandLongLong(int64_t randMin, int64_t randMax); - static int32_t GetRandomData(uint8_t *randStr, uint32_t len); - static int32_t MbedtlsEncrypt(const uint8_t *plainText, int32_t plainTextLen, uint8_t *cipherText, - int32_t cipherTextLen, int32_t *outLen); - static int32_t MbedtlsDecrypt(const uint8_t *cipherText, int32_t cipherTextLen, uint8_t *plainText, - int32_t plainTextLen, int32_t *outLen); - /** - * szOut最后一位为结束符,比如 szOutLen=4 可能返回 "abc" - * @param szOutLen 至少2 - * @param numberOnly 是否只生成数据 如果为true 则期望返回随机数字 如果为否,则期望返回随机字符 - */ - static bool MbedtlsGenRandomStr(char *szOut, int32_t szOutLen, bool numberOnly); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H \ No newline at end of file diff --git a/utils/include/ipc/lite/ipc_cmd_register.h b/utils/include/ipc/lite/ipc_cmd_register.h index 0144df0d6..f3d6ac3d7 100644 --- a/utils/include/ipc/lite/ipc_cmd_register.h +++ b/utils/include/ipc/lite/ipc_cmd_register.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,74 +13,74 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H +#ifndef OHOS_DM_IPC_CMD_PARSER_H +#define OHOS_DM_IPC_CMD_PARSER_H #include -#include #include - -#include "liteipc_adapter.h" -#include "single_instance.h" +#include #include "ipc_req.h" #include "ipc_rsp.h" +#include "liteipc_adapter.h" +#include "single_instance.h" namespace OHOS { namespace DistributedHardware { -#define ON_IPC_SET_REQUEST(cmdCode, paraA, paraB, paraC, paraD) \ - static int32_t IpcSetRequest##cmdCode(paraA, paraB, paraC, paraD); \ - struct IpcRegisterSetRequestFunc##cmdCode { \ - IpcRegisterSetRequestFunc##cmdCode() \ - { \ +#define ON_IPC_SET_REQUEST(cmdCode, paraA, paraB, paraC, paraD) \ + static int32_t IpcSetRequest##cmdCode(paraA, paraB, paraC, paraD); \ + struct IpcRegisterSetRequestFunc##cmdCode { \ + IpcRegisterSetRequestFunc##cmdCode() \ + { \ IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - IpcRegisterSetRequestFunc##cmdCode g_IpcRegisterSetRequestFunc##cmdCode; \ - static int32_t IpcSetRequest##cmdCode(paraA, paraB, paraC, paraD) \ + } \ + }; \ + IpcRegisterSetRequestFunc##cmdCode g_IpcRegisterSetRequestFunc##cmdCode; \ + static int32_t IpcSetRequest##cmdCode(paraA, paraB, paraC, paraD) -#define ON_IPC_READ_RESPONSE(cmdCode, paraA, paraB) \ - static int32_t IpcReadResponse##cmdCode(paraA, paraB); \ - struct IpcRegisterReadResponseFunc##cmdCode { \ - IpcRegisterReadResponseFunc##cmdCode() \ - { \ +#define ON_IPC_READ_RESPONSE(cmdCode, paraA, paraB) \ + static int32_t IpcReadResponse##cmdCode(paraA, paraB); \ + struct IpcRegisterReadResponseFunc##cmdCode { \ + IpcRegisterReadResponseFunc##cmdCode() \ + { \ IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - IpcRegisterReadResponseFunc##cmdCode g_IpcRegisterReadResponseFunc##cmdCode; \ - static int32_t IpcReadResponse##cmdCode(paraA, paraB) \ + } \ + }; \ + IpcRegisterReadResponseFunc##cmdCode g_IpcRegisterReadResponseFunc##cmdCode; \ + static int32_t IpcReadResponse##cmdCode(paraA, paraB) -#define ON_IPC_CMD(cmdCode, paraA) \ - static void IpcCmdProcess##cmdCode(paraA); \ - struct IpcRegisterCmdProcessFunc##cmdCode { \ - IpcRegisterCmdProcessFunc##cmdCode() \ - { \ +#define ON_IPC_CMD(cmdCode, paraA) \ + static void IpcCmdProcess##cmdCode(paraA); \ + struct IpcRegisterCmdProcessFunc##cmdCode { \ + IpcRegisterCmdProcessFunc##cmdCode() \ + { \ IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ - static void IpcCmdProcess##cmdCode(paraA) \ + } \ + }; \ + IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ + static void IpcCmdProcess##cmdCode(paraA) -#define ON_IPC_SERVER_CMD(cmdCode, paraA, paraB) \ - static void IpcServerCmdProcess##cmdCode(paraA, paraB); \ - class IpcRegisterServerCmdProcessFunc##cmdCode { \ - public: \ - IpcRegisterServerCmdProcessFunc##cmdCode() \ - { \ +#define ON_IPC_SERVER_CMD(cmdCode, paraA, paraB) \ + static void IpcServerCmdProcess##cmdCode(paraA, paraB); \ + class IpcRegisterServerCmdProcessFunc##cmdCode { \ + public: \ + IpcRegisterServerCmdProcessFunc##cmdCode() \ + { \ IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##cmdCode); \ - } \ - }; \ - IpcRegisterServerCmdProcessFunc##cmdCode g_IpcRegisterServerCmdProcessFunc##cmdCode; \ + } \ + }; \ + IpcRegisterServerCmdProcessFunc##cmdCode g_IpcRegisterServerCmdProcessFunc##cmdCode; \ static void IpcServerCmdProcess##cmdCode(paraA, paraB) -using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t bufferLen); +using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t bufferLen); using ReadResponseFunc = int32_t (*)(IpcIo &reply, std::shared_ptr pBaseRsp); using OnIpcCmdFunc = void (*)(IpcIo &reply); using OnIpcServerCmdFunc = void (*)(IpcIo &req, IpcIo &reply); class IpcCmdRegister { -DECLARE_SINGLE_INSTANCE(IpcCmdRegister); + DECLARE_SINGLE_INSTANCE(IpcCmdRegister); + public: void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) { @@ -98,11 +98,12 @@ public: { onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); }; - int32_t SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen); + int32_t SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen); int32_t ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ptr pBaseRsp); int32_t OnIpcCmd(int32_t cmdCode, IpcIo &reply); int32_t OnIpcServerCmd(int32_t cmdCode, IpcIo &req, IpcIo &reply); + private: std::unordered_map setIpcRequestFuncMap_; std::unordered_map readResponseFuncMap_; @@ -111,4 +112,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file +#endif // OHOS_DM_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/utils/include/ipc/standard/ipc_cmd_register.h b/utils/include/ipc/standard/ipc_cmd_register.h index c2c5d585d..167f4ec50 100644 --- a/utils/include/ipc/standard/ipc_cmd_register.h +++ b/utils/include/ipc/standard/ipc_cmd_register.h @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,53 +13,52 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H +#ifndef OHOS_DM_IPC_CMD_PARSER_H +#define OHOS_DM_IPC_CMD_PARSER_H #include -#include #include +#include -#include "iremote_broker.h" -#include "single_instance.h" - -#include "ipc_types.h" #include "ipc_req.h" #include "ipc_rsp.h" +#include "ipc_types.h" +#include "iremote_broker.h" +#include "single_instance.h" namespace OHOS { namespace DistributedHardware { -#define ON_IPC_SET_REQUEST(cmdCode, paraA, paraB) \ - static int32_t IpcSetRequest##cmdCode(paraA, paraB); \ - struct IpcRegisterSetRequestFunc##cmdCode { \ - IpcRegisterSetRequestFunc##cmdCode() \ - { \ +#define ON_IPC_SET_REQUEST(cmdCode, paraA, paraB) \ + static int32_t IpcSetRequest##cmdCode(paraA, paraB); \ + struct IpcRegisterSetRequestFunc##cmdCode { \ + IpcRegisterSetRequestFunc##cmdCode() \ + { \ IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - IpcRegisterSetRequestFunc##cmdCode g_IpcRegisterSetRequestFunc##cmdCode; \ - static int32_t IpcSetRequest##cmdCode(paraA, paraB) \ + } \ + }; \ + IpcRegisterSetRequestFunc##cmdCode g_IpcRegisterSetRequestFunc##cmdCode; \ + static int32_t IpcSetRequest##cmdCode(paraA, paraB) -#define ON_IPC_READ_RESPONSE(cmdCode, paraA, paraB) \ - static int32_t IpcReadResponse##cmdCode(paraA, paraB); \ - struct IpcRegisterReadResponseFunc##cmdCode { \ - IpcRegisterReadResponseFunc##cmdCode() \ - { \ +#define ON_IPC_READ_RESPONSE(cmdCode, paraA, paraB) \ + static int32_t IpcReadResponse##cmdCode(paraA, paraB); \ + struct IpcRegisterReadResponseFunc##cmdCode { \ + IpcRegisterReadResponseFunc##cmdCode() \ + { \ IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - IpcRegisterReadResponseFunc##cmdCode g_IpcRegisterReadResponseFunc##cmdCode; \ - static int32_t IpcReadResponse##cmdCode(paraA, paraB) \ + } \ + }; \ + IpcRegisterReadResponseFunc##cmdCode g_IpcRegisterReadResponseFunc##cmdCode; \ + static int32_t IpcReadResponse##cmdCode(paraA, paraB) -#define ON_IPC_CMD(cmdCode, paraA, paraB) \ - static int32_t IpcCmdProcess##cmdCode(paraA, paraB); \ - struct IpcRegisterCmdProcessFunc##cmdCode { \ - IpcRegisterCmdProcessFunc##cmdCode() \ - { \ +#define ON_IPC_CMD(cmdCode, paraA, paraB) \ + static int32_t IpcCmdProcess##cmdCode(paraA, paraB); \ + struct IpcRegisterCmdProcessFunc##cmdCode { \ + IpcRegisterCmdProcessFunc##cmdCode() \ + { \ IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ + } \ + }; \ + IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ static int32_t IpcCmdProcess##cmdCode(paraA, paraB) using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); @@ -67,7 +66,8 @@ using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseReq, MessageParcel &data); int32_t ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp); int32_t OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply); + private: std::unordered_map setIpcRequestFuncMap_; std::unordered_map readResponseFuncMap_; @@ -91,4 +92,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file +#endif // OHOS_DM_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/utils/include/log/dm_log.h b/utils/include/log/dm_log.h deleted file mode 100644 index 1db27040a..000000000 --- a/utils/include/log/dm_log.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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_LOG_H -#define OHOS_DM_LOG_H - -namespace OHOS { -namespace DistributedHardware { -typedef enum { - DM_LOG_DEBUG, - DM_LOG_INFO, - DM_LOG_WARN, - DM_LOG_ERROR, -} DMLogLevel; - -void DMLog(DMLogLevel logLevel, const char *fmt, ...); -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_LOG_H diff --git a/utils/src/anonymous_string.cpp b/utils/src/anonymous_string.cpp deleted file mode 100644 index f5834ee37..000000000 --- a/utils/src/anonymous_string.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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 "anonymous_string.h" - -#include "securec.h" - -namespace OHOS { -namespace DistributedHardware { -std::string GetAnonyString(const std::string &value) -{ - const int32_t INT32_SHORT_ID_LENGTH = 20; - const int32_t INT32_PLAINTEXT_LENGTH = 4; - const int32_t INT32_MIN_ID_LENGTH = 3; - std::string res; - std::string tmpStr("******"); - int32_t strLen = value.length(); - if (strLen < INT32_MIN_ID_LENGTH) { - return tmpStr; - } - - if (strLen <= INT32_SHORT_ID_LENGTH) { - res += value[0]; - res += tmpStr; - res += value[strLen - 1]; - } else { - res.append(value, 0, INT32_PLAINTEXT_LENGTH); - res += tmpStr; - res.append(value, strLen - INT32_PLAINTEXT_LENGTH, INT32_PLAINTEXT_LENGTH); - } - - return res; -} - -std::string GetAnonyInt32(const int32_t value) -{ - const int32_t INT32_STRING_LENGTH = 40; - char tempBuffer[INT32_STRING_LENGTH] = ""; - int32_t secRet = sprintf_s(tempBuffer, INT32_STRING_LENGTH, "%d", value); - if (secRet <= 0) { - std::string nullString(""); - return nullString; - } - int32_t length = strlen(tempBuffer); - for (int32_t i = 1; i < length - 1; i++) { - tempBuffer[i] = '*'; - } - if (length == 0x01) { - tempBuffer[0] = '*'; - } - - std::string tempSting(tempBuffer); - return tempSting; -} -} -} \ No newline at end of file diff --git a/utils/src/cipher/encrypt_utils.cpp b/utils/src/cipher/encrypt_utils.cpp deleted file mode 100644 index 67a39b9c4..000000000 --- a/utils/src/cipher/encrypt_utils.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - * 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 "encrypt_utils.h" - -#include "mbedtls/base64.h" -#include "mbedtls/gcm.h" -#include "mbedtls/md.h" - -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/entropy.h" - -#include -#include -#include -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "securec.h" - -namespace OHOS { -namespace DistributedHardware { -int32_t EncryptUtils::MbedtlsBase64Encode(uint8_t *dst, size_t dlen, size_t *olen, - const uint8_t *src, size_t slen) -{ - return mbedtls_base64_encode(dst, dlen, olen, src, slen); -} - -int32_t EncryptUtils::MbedtlsBase64Decode(uint8_t *dst, size_t dlen, size_t *olen, - const uint8_t *src, size_t slen) -{ - return mbedtls_base64_decode(dst, dlen, olen, src, slen); -} - -int32_t EncryptUtils::GenRandInt(int32_t randMin, int32_t randMax) -{ - std::random_device randDevice; - std::mt19937 genRand(randDevice()); - std::uniform_int_distribution disRand(randMin, randMax); - return disRand(genRand); -} - -int64_t EncryptUtils::GenRandLongLong(int64_t randMin, int64_t randMax) -{ - std::random_device randDevice; - std::mt19937 genRand(randDevice()); - std::uniform_int_distribution disRand(randMin, randMax); - return disRand(genRand); -} - -int32_t EncryptUtils::GetRandomData(uint8_t *randStr, uint32_t len) -{ - mbedtls_entropy_context *entropy = nullptr; - mbedtls_ctr_drbg_context *ctrDrbg = nullptr; - int32_t ret = DEVICEMANAGER_FAILED; - do { - if (randStr == nullptr || len == 0) { - break; - } - entropy = (mbedtls_entropy_context *)malloc(sizeof(mbedtls_entropy_context)); - if (entropy == nullptr) { - break; - } - ctrDrbg = (mbedtls_ctr_drbg_context *)malloc(sizeof(mbedtls_ctr_drbg_context)); - if (ctrDrbg == nullptr) { - break; - } - mbedtls_ctr_drbg_init(ctrDrbg); - mbedtls_entropy_init(entropy); - ret = mbedtls_ctr_drbg_seed(ctrDrbg, mbedtls_entropy_func, entropy, nullptr, 0); - if (ret != 0) { - break; - } - ret = mbedtls_ctr_drbg_random(ctrDrbg, randStr, len); - if (ret != 0) { - break; - } - ret = DEVICEMANAGER_OK; - } while (0); - if (entropy != nullptr) { - free(entropy); - } - if (ctrDrbg != nullptr) { - free(ctrDrbg); - } - return ret; -} - -int32_t EncryptUtils::MbedtlsEncrypt(const uint8_t *plainText, int32_t plainTextLen, uint8_t *cipherText, - int32_t cipherTextLen, int32_t *outLen) -{ - // Security algorithms do not support open source. Customize if required - if (memcpy_s(cipherText, cipherTextLen, plainText, plainTextLen) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_COPY_FAILED; - } - *outLen = plainTextLen; - return DEVICEMANAGER_OK; -} - -int32_t EncryptUtils::MbedtlsDecrypt(const uint8_t *cipherText, int32_t cipherTextLen, uint8_t *plainText, - int32_t plainTextLen, int32_t *outLen) -{ - // Security algorithms do not support open source. Customize if required - (void)outLen; - if (memcpy_s(plainText, plainTextLen, cipherText, cipherTextLen) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_COPY_FAILED; - } - return DEVICEMANAGER_OK; -} - -bool EncryptUtils::MbedtlsGenRandomStr(char *szOut, int32_t szOutLen, bool numberOnly) -{ - const int32_t MIN_OUT_LENGTH = 2; - if (szOut == nullptr || szOutLen <= MIN_OUT_LENGTH) { - return false; - } - szOut[--szOutLen] = 0; - GetRandomData((uint8_t*)szOut, szOutLen); - const int32_t NUMBER_COUNT = 10; - const int32_t ALPHA_COUNT = 26; - const int32_t ALPHA_BYTE_COUNT = 2; - int32_t M = numberOnly ? NUMBER_COUNT : (NUMBER_COUNT + ALPHA_BYTE_COUNT * ALPHA_COUNT); - for (int32_t i = 0; i < szOutLen; i++) { - // 0~9,A~Z,a~z - uint32_t idx = ((uint32_t)szOut[i] % M); - char base; - if (idx < NUMBER_COUNT) { - base = '0'; - } else if (idx >= NUMBER_COUNT && idx < (NUMBER_COUNT + ALPHA_COUNT)) { - base = 'A'; - idx -= NUMBER_COUNT; - } else { - base = 'a'; - idx -= (NUMBER_COUNT + ALPHA_COUNT); - } - szOut[i] = base + idx; - } - return true; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/utils/src/ipc/lite/ipc_cmd_register.cpp b/utils/src/ipc/lite/ipc_cmd_register.cpp index 4fbab5a16..2a3e76d2b 100644 --- a/utils/src/ipc/lite/ipc_cmd_register.cpp +++ b/utils/src/ipc/lite/ipc_cmd_register.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,20 +15,20 @@ #include "ipc_cmd_register.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); -int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) { auto setRequestMapIter = setIpcRequestFuncMap_.find(cmdCode); if (setRequestMapIter == setIpcRequestFuncMap_.end()) { - DMLOG(DM_LOG_ERROR, "cmdCode:%d not register SetRequestFunc", cmdCode); - return DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + LOGE("cmdCode:%d not register SetRequestFunc", cmdCode); + return DM_IPC_NOT_REGISTER_FUNC; } return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); } @@ -37,8 +37,8 @@ int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ { auto readResponseMapIter = readResponseFuncMap_.find(cmdCode); if (readResponseMapIter == readResponseFuncMap_.end()) { - DMLOG(DM_LOG_ERROR, "cmdCode:%d not register ReadResponseFunc", cmdCode); - return DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + LOGE("cmdCode:%d not register ReadResponseFunc", cmdCode); + return DM_IPC_NOT_REGISTER_FUNC; } return (readResponseMapIter->second)(reply, pBaseRsp); } @@ -47,22 +47,22 @@ int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, IpcIo &reply) { auto onIpcCmdMapIter = onIpcCmdFuncMap_.find(cmdCode); if (onIpcCmdMapIter == onIpcCmdFuncMap_.end()) { - DMLOG(DM_LOG_ERROR, "cmdCode:%d not register OnIpcCmdFunc", cmdCode); - return DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + LOGE("cmdCode:%d not register OnIpcCmdFunc", cmdCode); + return DM_IPC_NOT_REGISTER_FUNC; } (onIpcCmdMapIter->second)(reply); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcCmdRegister::OnIpcServerCmd(int32_t cmdCode, IpcIo &req, IpcIo &reply) { auto onIpcServerCmdMapIter = onIpcServerCmdFuncMap_.find(cmdCode); if (onIpcServerCmdMapIter == onIpcServerCmdFuncMap_.end()) { - DMLOG(DM_LOG_ERROR, "cmdCode:%d not register OnIpcCmdFunc", cmdCode); - return DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + LOGE("cmdCode:%d not register OnIpcCmdFunc", cmdCode); + return DM_IPC_NOT_REGISTER_FUNC; } (onIpcServerCmdMapIter->second)(req, reply); - return DEVICEMANAGER_OK; + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/ipc/standard/ipc_cmd_register.cpp b/utils/src/ipc/standard/ipc_cmd_register.cpp index e958dfd04..2d3f3fd2c 100644 --- a/utils/src/ipc/standard/ipc_cmd_register.cpp +++ b/utils/src/ipc/standard/ipc_cmd_register.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,8 +15,8 @@ #include "ipc_cmd_register.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { @@ -26,8 +26,8 @@ int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBas { auto setRequestMapIter = setIpcRequestFuncMap_.find(cmdCode); if (setRequestMapIter == setIpcRequestFuncMap_.end()) { - DMLOG(DM_LOG_ERROR, "cmdCode:%d not register SetRequestFunc", cmdCode); - return DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + LOGE("cmdCode:%d not register SetRequestFunc", cmdCode); + return DM_IPC_NOT_REGISTER_FUNC; } return (setRequestMapIter->second)(pBaseReq, data); } @@ -36,8 +36,8 @@ int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std: { auto readResponseMapIter = readResponseFuncMap_.find(cmdCode); if (readResponseMapIter == readResponseFuncMap_.end()) { - DMLOG(DM_LOG_ERROR, "cmdCode:%d not register ReadResponseFunc", cmdCode); - return DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + LOGE("cmdCode:%d not register ReadResponseFunc", cmdCode); + return DM_IPC_NOT_REGISTER_FUNC; } return (readResponseMapIter->second)(reply, pBaseRsp); } @@ -46,8 +46,8 @@ int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessagePa { auto onIpcCmdMapIter = onIpcCmdFuncMap_.find(cmdCode); if (onIpcCmdMapIter == onIpcCmdFuncMap_.end()) { - DMLOG(DM_LOG_ERROR, "cmdCode:%d not register OnIpcCmdFunc", cmdCode); - return DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + LOGE("cmdCode:%d not register OnIpcCmdFunc", cmdCode); + return DM_IPC_NOT_REGISTER_FUNC; } return (onIpcCmdMapIter->second)(data, reply); } diff --git a/utils/src/log/dm_log.cpp b/utils/src/log/dm_log.cpp deleted file mode 100644 index 538594b15..000000000 --- a/utils/src/log/dm_log.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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_log.h" - -#include "securec.h" - -#include "constants.h" - -#ifdef HI_LOG_ENABLE -#include "hilog/log.h" -#else -#include - -#endif - -namespace OHOS { -namespace DistributedHardware { -static void DMLogOut(DMLogLevel logLevel, const char *logBuf) -{ -#ifdef HI_LOG_ENABLE - LogLevel hiLogLevel = LOG_INFO; - switch (logLevel) { - case DM_LOG_DEBUG: - hiLogLevel = LOG_DEBUG; - break; - case DM_LOG_INFO: - hiLogLevel = LOG_INFO; - break; - case DM_LOG_WARN: - hiLogLevel = LOG_WARN; - break; - case DM_LOG_ERROR: - hiLogLevel = LOG_ERROR; - break; - default: - break; - } - (void)HiLogPrint(LOG_CORE, hiLogLevel, LOG_DOMAIN, "", "%{public}s", logBuf); -#else - switch (logLevel) { - case DM_LOG_DEBUG: - printf("[D]%s\n", logBuf); - break; - case DM_LOG_INFO: - printf("[I]%s\n", logBuf); - break; - case DM_LOG_WARN: - printf("[W]%s\n", logBuf); - break; - case DM_LOG_ERROR: - printf("[E]%s\n", logBuf); - break; - default: - break; - } -#endif -} - -void DMLog(DMLogLevel logLevel, const char *fmt, ...) -{ - char logBuf[LOG_MAX_LEN] = {0}; - va_list arg; - int32_t ret = 0; - - (void)memset_s(&arg, sizeof(va_list), 0, sizeof(va_list)); - va_start(arg, fmt); - ret = vsprintf_s(logBuf, sizeof(logBuf), fmt, arg); - va_end(arg); - if (ret < 0) { - DMLogOut(logLevel, "DM log length error."); - return; - } - DMLogOut(logLevel, logBuf); -} -} // namespace DistributedHardware -} // namespace OHOS -- Gitee From 2f1a721c2dac581b96d643ffa7d31cd75672c0ee Mon Sep 17 00:00:00 2001 From: renguang1116 Date: Wed, 12 Jan 2022 21:57:49 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E6=8F=90=E4=BA=A4DM=E6=A8=A1=E5=9D=97TDD?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=20Signed-off-by:=20renguang1116=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/BUILD.gn | 18 + test/unittest/BUILD.gn | 327 +++++++++ test/unittest/UTTest_auth_request_state.cpp | 665 ++++++++++++++++++ test/unittest/UTTest_auth_request_state.h | 39 + test/unittest/UTTest_auth_response_state.cpp | 480 +++++++++++++ test/unittest/UTTest_auth_response_state.h | 36 + .../UTTest_device_manager_service.cpp | 346 +++++++++ test/unittest/UTTest_device_manager_service.h | 47 ++ ...UTTest_device_manager_service_listener.cpp | 112 +++ .../UTTest_device_manager_service_listener.h | 44 ++ test/unittest/UTTest_device_message.cpp | 514 ++++++++++++++ test/unittest/UTTest_device_message.h | 40 ++ test/unittest/UTTest_dm_auth_manager.cpp | 569 +++++++++++++++ test/unittest/UTTest_dm_auth_manager.h | 47 ++ .../UTTest_dm_device_info_manager.cpp | 62 ++ test/unittest/UTTest_dm_device_info_manager.h | 45 ++ .../UTTest_dm_device_state_manager.cpp | 200 ++++++ .../unittest/UTTest_dm_device_state_manager.h | 44 ++ test/unittest/UTTest_dm_discovery_manager.cpp | 252 +++++++ test/unittest/UTTest_dm_discovery_manager.h | 43 ++ test/unittest/UTTest_hichain_connector.cpp | 490 +++++++++++++ test/unittest/UTTest_hichain_connector.h | 51 ++ test/unittest/UTTest_softbus_connector.cpp | 447 ++++++++++++ test/unittest/UTTest_softbus_connector.h | 55 ++ test/unittest/UTTest_softbus_session.cpp | 209 ++++++ test/unittest/UTTest_softbus_session.h | 49 ++ test/unittest/auth_request_state.cpp | 192 +++++ test/unittest/device_manager_impl_test.cpp | 192 +++++ test/unittest/device_manager_impl_test.h | 55 ++ test/unittest/mock/ipc_server_listener.cpp | 31 + test/unittest/mock/ipc_server_listener.h | 39 + test/unittest/mock/mock_ipc_client_proxy.h | 33 + 32 files changed, 5773 insertions(+) create mode 100644 test/BUILD.gn create mode 100644 test/unittest/BUILD.gn create mode 100644 test/unittest/UTTest_auth_request_state.cpp create mode 100644 test/unittest/UTTest_auth_request_state.h create mode 100644 test/unittest/UTTest_auth_response_state.cpp create mode 100644 test/unittest/UTTest_auth_response_state.h create mode 100644 test/unittest/UTTest_device_manager_service.cpp create mode 100644 test/unittest/UTTest_device_manager_service.h create mode 100644 test/unittest/UTTest_device_manager_service_listener.cpp create mode 100644 test/unittest/UTTest_device_manager_service_listener.h create mode 100644 test/unittest/UTTest_device_message.cpp create mode 100644 test/unittest/UTTest_device_message.h create mode 100644 test/unittest/UTTest_dm_auth_manager.cpp create mode 100644 test/unittest/UTTest_dm_auth_manager.h create mode 100644 test/unittest/UTTest_dm_device_info_manager.cpp create mode 100644 test/unittest/UTTest_dm_device_info_manager.h create mode 100644 test/unittest/UTTest_dm_device_state_manager.cpp create mode 100644 test/unittest/UTTest_dm_device_state_manager.h create mode 100644 test/unittest/UTTest_dm_discovery_manager.cpp create mode 100644 test/unittest/UTTest_dm_discovery_manager.h create mode 100644 test/unittest/UTTest_hichain_connector.cpp create mode 100644 test/unittest/UTTest_hichain_connector.h create mode 100644 test/unittest/UTTest_softbus_connector.cpp create mode 100644 test/unittest/UTTest_softbus_connector.h create mode 100644 test/unittest/UTTest_softbus_session.cpp create mode 100644 test/unittest/UTTest_softbus_session.h create mode 100644 test/unittest/auth_request_state.cpp create mode 100644 test/unittest/device_manager_impl_test.cpp create mode 100644 test/unittest/device_manager_impl_test.h create mode 100644 test/unittest/mock/ipc_server_listener.cpp create mode 100644 test/unittest/mock/ipc_server_listener.h create mode 100644 test/unittest/mock/mock_ipc_client_proxy.h diff --git a/test/BUILD.gn b/test/BUILD.gn new file mode 100644 index 000000000..ece194320 --- /dev/null +++ b/test/BUILD.gn @@ -0,0 +1,18 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("test") { + testonly = true + + deps = [ "unittest:unittest" ] +} \ No newline at end of file diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn new file mode 100644 index 000000000..d1f6bda8a --- /dev/null +++ b/test/unittest/BUILD.gn @@ -0,0 +1,327 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/distributedhardware/devicemanager/devicemanager.gni") +module_out_path = "deviceManager_stander/inner_kits" + +group("unittest") { + testonly = true + + deps = [ + ":UTTest_device_manager_service", + ":UTTest_device_manager_service_listener", + ":UTTest_dm_device_info_manager", + ":UTTest_dm_device_state_manager", + ":UTTest_dm_discovery_manager", + ":UTTest_hichain_connector", + ":UTTest_softbus_connector", + ":UTTest_softbus_session", + ":device_manager_impl_test", + ] +} + +## UnitTest device_manager_impl_test {{{ +ohos_unittest("device_manager_impl_test") { + module_out_path = module_out_path + + sources = [ "device_manager_impl_test.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest device_manager_impl_test }}} + +## UnitTest UTTest_device_manager_service {{{ +ohos_unittest("UTTest_device_manager_service") { + module_out_path = module_out_path + + sources = [ "UTTest_device_manager_service.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_device_manager_service }}} + +## UnitTest UTTest_hichain_connector {{{ +ohos_unittest("UTTest_hichain_connector") { + module_out_path = module_out_path + + sources = [ "UTTest_hichain_connector.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_hichain_connector }}} + +## UnitTest UTTest_dm_device_info_manager {{{ +ohos_unittest("UTTest_dm_device_info_manager") { + module_out_path = module_out_path + + sources = [ "UTTest_dm_device_info_manager.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_dm_device_info_manager }}} + +## UnitTest UTTest_softbus_connector {{{ +ohos_unittest("UTTest_softbus_connector") { + module_out_path = module_out_path + + sources = [ "UTTest_softbus_connector.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_softbus_connector }}} + +## UnitTest UTTest_softbus_session {{{ +ohos_unittest("UTTest_softbus_session") { + module_out_path = module_out_path + + sources = [ "UTTest_softbus_session.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_softbus_session }}} + +## UnitTest UTTest_dm_device_state_manager {{{ +ohos_unittest("UTTest_dm_device_state_manager") { + module_out_path = module_out_path + + sources = [ + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/config/config_manager.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/parameter.cpp", + "UTTest_dm_device_state_manager.cpp", + ] + + deps = [ ":device_manager_test" ] +} + +## UnitTest UTTest_dm_device_state_manager }}} + +## UnitTest UTTest_device_manager_service_listener {{{ +ohos_unittest("UTTest_device_manager_service_listener") { + module_out_path = module_out_path + + sources = [ + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", + "UTTest_device_manager_service_listener.cpp", + ] + + deps = [ ":device_manager_test" ] +} + +## UnitTest UTTest_device_manager_service_listener }}} + +## UnitTest UTTest_dm_discovery_manager {{{ +ohos_unittest("UTTest_dm_discovery_manager") { + module_out_path = module_out_path + + sources = [ + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/parameter.cpp", + "UTTest_dm_discovery_manager.cpp", + ] + + deps = [ ":device_manager_test" ] +} + +## UnitTest UTTest_dm_discovery_manager }}} +## Build device_manager_test_common.a {{{ +config("device_manager_test_common_public_config") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/ipc/standard", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/ipc", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/notify", + "//third_party/json/include", + "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${utils_path}/include", + "${utils_path}/include/ipc/standard", + "${services_path}/include", + "${services_path}/include/dependency/timer", + "${services_path}/include/discovery", + "${services_path}/include/dependency/softbus", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dependency/softbus", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/softbus_lite/interfaces/kits/transport", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//foundation/communication/dsoftbus/interfaces/kits/discovery", + "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/authentication", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/adapter", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ipc/standard", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/discovery", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dependency/hichain", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/deviceinfo/", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/devicestate", + "//foundation/distributedhardware/devicemanager/test/unittest/mock", + "//base/security/deviceauth/interfaces/innerkits", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ability", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/config", + ] + + cflags = [ + "-Wall", + "-Werror", + "-g3", + "-Dprivate=public", + "-Dprotected=public", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"device_manager_UTtest\"", + "LOG_DOMAIN=0xD004190", + ] +} + +ohos_static_library("device_manager_test_common") { + testonly = true + + visibility = [ ":*" ] + + public_configs = [ ":device_manager_test_common_public_config" ] + + public_deps = [ + "${utils_path}:devicemanagerutils", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice:devicemanagerservice", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock", + "//third_party/googletest:gtest", + "//utils/native/base:utils", + "//utils/native/base:utils", + ] +} + +## Build device_manager_test_common.a }}} + +## Build device_manager_test_common.a {{{ +config("device_manager_test_common_public") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/ipc", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/notify", + "//third_party/json/include", + "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${utils_path}/include", + "${utils_path}/include/ipc/standard", + "${services_path}/include", + "${services_path}/include/dependency/timer", + "${services_path}/include/discovery", + "${services_path}/include/dependency/softbus", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//foundation/communication/dsoftbus/interfaces/kits/discovery", + "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dependency/softbus", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/authentication", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/adapter", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/discovery", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dependency/hichain", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/deviceinfo/", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/devicestate", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/", + "//base/security/deviceauth/interfaces/innerkits", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ability", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/config", + ] + + cflags = [ + "-Wall", + "-Werror", + "-g3", + "-Dprivate=public", + "-Dprotected=public", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"device_manager_UTtest\"", + "LOG_DOMAIN=0xD004190", + ] +} + +ohos_static_library("device_manager_test") { + testonly = true + + visibility = [ ":*" ] + + public_configs = [ ":device_manager_test_common_public" ] + + public_deps = [ + "${utils_path}:devicemanagerutils", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock", + "//third_party/googletest:gtest", + "//utils/native/base:utils", + ] + + deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", + "${utils_path}:devicemanagerutils", + "//base/security/deviceauth/services:deviceauth_sdk", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + ] + + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} +## Build device_manager_test.a }}} diff --git a/test/unittest/UTTest_auth_request_state.cpp b/test/unittest/UTTest_auth_request_state.cpp new file mode 100644 index 000000000..eded6b942 --- /dev/null +++ b/test/unittest/UTTest_auth_request_state.cpp @@ -0,0 +1,665 @@ +/* + * 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 "UTTest_auth_request_state.h" + +#include "dm_auth_manager.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +void AuthRequestStateTest::SetUp() +{ +} +void AuthRequestStateTest::TearDown() +{ +} +void AuthRequestStateTest::SetUpTestCase() +{ +} +void AuthRequestStateTest::TearDownTestCase() +{ +} + +namespace { + +std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; +std::string NEGOTIATE_TIMEOUT_TASK = "negotiateTimeoutTask"; +std::string CONFIRM_TIMEOUT_TASK = "confirmTimeoutTask"; +std::string INPUT_TIMEOUT_TASK = "inputTimeoutTask"; +std::string ADD_TIMEOUT_TASK = "addTimeoutTask"; + +/** + * @tc.name: AuthRequestInitState::SetAuthManager_001 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestInitState::SetAuthManager with authManager != null + * 3 check ret is authResponseState->authManager_.use_count() + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, SetAuthManager_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + authRequestState->SetAuthManager(authManager); + int32_t ret = authRequestState->authManager_.use_count(); + authRequestState->authManager_.reset(); + ASSERT_EQ(ret, 1); +} + +/** + * @tc.name: AuthRequestInitState::SetAuthManager_002 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestInitState::SetAuthManager with authManager = null + * 3 check ret is authResponseState->authManager_.use_count() + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, SetAuthManager_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->authManager_.use_count(); + authRequestState->authManager_.reset(); + ASSERT_EQ(ret, 0); +} + +/** + * @tc.name: AuthRequestNegotiateState::TransitionTo_001 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestInitState::TransitionTo with authManager = null + * 4 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, TransitionTo_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + authManager = nullptr; + authRequestState->authManager_ = authManager; + int32_t ret = authRequestState->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestInitState::TransitionTo_002 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestInitState::TransitionTo with authManager != null + * 4 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, TransitionTo_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr context = std::make_shared(); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNegotiateState()); + authManager->authRequestContext_ = std::make_shared(); + authManager->authMessageProcessor_ = std::make_shared(authManager); + context->sessionId = 123456; + authRequestState->SetAuthContext(context); + authRequestState->SetAuthManager(authManager); + int32_t ret = authRequestState->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); + ASSERT_EQ(ret, DM_OK); + sleep(20); +} + +/** + * @tc.name: AuthRequestInitState::GetStateType_001 + * @tc.desc: 1 call AuthRequestInitState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_INIT); + sleep(15); +} + +/** + * @tc.name: AuthRequestInitState::Enter_001 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestInitState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + authManager = nullptr; + authRequestState->SetAuthManager(authManager); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestInitState::Enter_002 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestInitState::Enter with authManager != null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestInitState()); + authRequestState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + context->deviceId = "123456"; + authRequestState->SetAuthContext(context); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthRequestNegotiateState::GetStateType_002 + * @tc.desc: 1 call AuthRequestNegotiateState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_NEGOTIATE + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_NEGOTIATE); + sleep(15); +} + +/** + * @tc.name: AuthRequestNegotiateState::Enter_001 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestNegotiateState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestNegotiateState::Enter_002 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestNegotiateState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateState()); + std::shared_ptr hiChainConnector = std::make_shared(); + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNegotiateState()); + authManager->authRequestContext_->deviceId = "111"; + authRequestState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + context->deviceId = "123456"; + context->sessionId = 22222; + authRequestState->SetAuthContext(context); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthRequestNegotiateDoneState::GetStateType_003 + * @tc.desc: 1 call AuthRequestNegotiateDoneState::GetStateType + * 2 check ret is AuthState::AUTH_REQUEST_NEGOTIATE_DONE + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateDoneState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_NEGOTIATE_DONE); + sleep(15); +} + +/** + * @tc.name: AuthRequestNegotiateDoneState::Enter_005 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestNegotiateDoneState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_005, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateDoneState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestNegotiateDoneState::Enter_006 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestNegotiateDoneState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_006, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateDoneState()); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr negotiateStartTimer = std::make_shared(NEGOTIATE_TIMEOUT_TASK); + authManager->timerMap_[NEGOTIATE_TIMEOUT_TASK] = negotiateStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authMessageProcessor_->SetRequestContext(authManager->authRequestContext_); + authRequestState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + context->sessionId = 333333; + authRequestState->SetAuthContext(context); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthRequestReplyState::GetStateType_004 + * @tc.desc: 1 call AuthRequestReplyState::GetStateType + * 2 check ret is AuthState::AUTH_REQUEST_REPLY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestReplyState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_REPLY); + sleep(15); +} + +/** + * @tc.name: AuthRequestReplyState::Enter_007 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestReplyState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_007, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestReplyState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestReplyState::Enter_008 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestReplyState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_008, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestReplyState()); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr inputStartTimer = std::make_shared(CONFIRM_TIMEOUT_TASK); + authManager->timerMap_[CONFIRM_TIMEOUT_TASK] = inputStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestReplyState()); + authManager->authResponseContext_->sessionId = 1; + authManager->authMessageProcessor_->SetResponseContext(authManager->authResponseContext_); + authManager->authMessageProcessor_->SetRequestContext(authManager->authRequestContext_); + authManager->SetAuthRequestState(authRequestState); + authRequestState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + context->sessionId = 333333; + authRequestState->SetAuthContext(context); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthRequestInputState::GetStateType_005 + * @tc.desc: 1 call AuthRequestInputState::GetStateType + * 2 check ret is AuthState::AUTH_REQUEST_INPUT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_005, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInputState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_INPUT); + sleep(15); +} + +/** + * @tc.name: AuthRequestInputState::Enter_009 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestInputState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_009, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInputState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestInputState::Enter_010 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestInputState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_010, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInputState()); + authRequestState->SetAuthManager(authManager); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthRequestJoinState::GetStateType_006 + * @tc.desc: 1 call AuthRequestJoinState::GetStateType + * 2 check ret is AuthState::AUTH_REQUEST_JOIN + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_006, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestJoinState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_JOIN); + sleep(15); +} + +/** + * @tc.name: AuthRequestJoinState::Enter_011 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestJoinState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_011, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestJoinState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestJoinState::Enter_012 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestJoinState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_012, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestJoinState()); + authManager->authRequestContext_ = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr joinStartTimer = std::make_shared(ADD_TIMEOUT_TASK); + authManager->timerMap_[ADD_TIMEOUT_TASK] = joinStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObject; + authManager->authResponseContext_->groupId = "111"; + authManager->authResponseContext_->groupName = "222"; + authManager->authResponseContext_->code = 123; + authManager->authResponseContext_->requestId = 234; + authManager->authResponseContext_->deviceId = "234"; + jsonObject[TAG_GROUP_ID] = authManager->authResponseContext_->groupId; + jsonObject[TAG_GROUP_NAME] = authManager->authResponseContext_->groupName; + jsonObject[PIN_CODE_KEY] = authManager->authResponseContext_->code; + jsonObject[TAG_REQUEST_ID] = authManager->authResponseContext_->requestId; + jsonObject[TAG_DEVICE_ID] = authManager->authResponseContext_->deviceId; + authRequestState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + context->deviceId = "44444"; + context->sessionId = 55555; + authRequestState->SetAuthContext(context); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthRequestNetworkState::GetStateType_007 + * @tc.desc: 1 call AuthRequestNetworkState::GetStateType + * 2 check ret is AuthState::AUTH_REQUEST_NETWORK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_007, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNetworkState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_NETWORK); + sleep(15); +} + +/** + * @tc.name: AuthRequestNetworkState::Enter_013 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestNetworkState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_013, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNetworkState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestNetworkState::Enter_014 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestNetworkState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_014, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNetworkState()); + std::shared_ptr authenticateStartTimer = std::make_shared(AUTHENTICATE_TIMEOUT_TASK); + authManager->timerMap_[AUTHENTICATE_TIMEOUT_TASK] = authenticateStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNetworkState()); + authManager->SetAuthRequestState(authRequestState); + authRequestState->SetAuthManager(authManager); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthRequestFinishState::GetStateType_008 + * @tc.desc: 1 call AuthRequestFinishState::GetStateType + * 2 check ret is AuthState::AUTH_REQUEST_FINISH + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, GetStateType_008, testing::ext::TestSize.Level0) +{ + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestFinishState()); + int32_t ret = authRequestState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_FINISH); + sleep(15); +} + +/** + * @tc.name: AuthRequestFinishState::Enter_015 + * @tc.desc: 1 set authManager to null + * 2 call AuthRequestFinishState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_015, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestFinishState()); + authRequestState->SetAuthManager(nullptr); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthRequestFinishState::Enter_016 + * @tc.desc: 1 set authManager not null + * 2 call AuthRequestNetworkState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthRequestStateTest, Enter_016, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestFinishState()); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr inputStartTimer = std::make_shared(CONFIRM_TIMEOUT_TASK); + authManager->timerMap_[CONFIRM_TIMEOUT_TASK] = inputStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseFinishState()); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestFinishState()); + authManager->authResponseContext_->sessionId = 1; + authManager->authMessageProcessor_->SetResponseContext(authManager->authResponseContext_); + authManager->authMessageProcessor_->SetRequestContext(authManager->authRequestContext_); + authManager->SetAuthRequestState(authRequestState); + authRequestState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + context->sessionId = 333333; + authRequestState->SetAuthContext(context); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_auth_request_state.h b/test/unittest/UTTest_auth_request_state.h new file mode 100644 index 000000000..118963122 --- /dev/null +++ b/test/unittest/UTTest_auth_request_state.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_AUTH_REQUEST_STATE_TEST_H +#define OHOS_DM_AUTH_REQUEST_STATE_TEST_H + +#include + +#include +#include +#include + +#include "auth_request_state.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +class AuthRequestStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/UTTest_auth_response_state.cpp b/test/unittest/UTTest_auth_response_state.cpp new file mode 100644 index 000000000..48e886fe9 --- /dev/null +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -0,0 +1,480 @@ +/* + * 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 "UTTest_auth_response_state.h" + +#include "auth_response_state.h" +#include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +void AuthResponseStateTest::SetUp() +{ +} +void AuthResponseStateTest::TearDown() +{ +} +void AuthResponseStateTest::SetUpTestCase() +{ +} +void AuthResponseStateTest::TearDownTestCase() +{ +} + +namespace { + +/** + * @tc.name: AuthResponseInitState::SetAuthManager_001 + * @tc.desc: 1 set authManager not null + * 2 call AuthResponseInitState::SetAuthManager with authManager != null + * 3 check ret is authResponseState->authManager_.use_count() + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, SetAuthManager_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); + authResponseState->SetAuthManager(authManager); + int32_t ret = authResponseState->authManager_.use_count(); + ASSERT_EQ(ret, 1); + sleep(15); +} + +/** + * @tc.name: AuthResponseInitState::SetAuthManager_002 + * @tc.desc: 1 set authManager to null + * 2 call AuthResponseInitState::SetAuthManager with authManager = null + * 3 check ret is authResponseState->authManager_.use_count() + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, SetAuthManager_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); + authResponseState->SetAuthManager(nullptr); + int32_t ret = authResponseState->authManager_.use_count(); + ASSERT_EQ(ret, 0); + sleep(15); +} + +/** + * @tc.name: AuthResponseInitState::TransitionTo_001 + * @tc.desc: 1 set authManager to null + * 2 call AuthResponseInitState::TransitionTo with authManager = null + * 4 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, TransitionTo_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); + authManager = nullptr; + authResponseState->authManager_ = authManager; + int32_t ret = authResponseState->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthResponseInitState::TransitionTo_002 + * @tc.desc: 1 set authManager not null + * 2 call AuthResponseInitState::TransitionTo with authManager != null + * 4 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, TransitionTo_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr context = std::make_shared(); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNegotiateState()); + authManager->authRequestContext_ = std::make_shared(); + authManager->authMessageProcessor_ = std::make_shared(authManager); + context->sessionId = 123456; + authRequestState->SetAuthContext(context); + authRequestState->SetAuthManager(authManager); + int32_t ret = authRequestState->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); + ASSERT_EQ(ret, DM_OK); + sleep(20); +} + +/** + * @tc.name: AuthResponseInitState::GetStateType_001 + * @tc.desc: 1 call AuthResponseInitState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, GetStateType_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); + int32_t ret = authResponseState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_INIT); + sleep(15); +} + +/** + * @tc.name: AuthResponseInitState::Enter_001 + * @tc.desc: 1 call AuthResponseInitState::GetStateType + * 2 check ret is AuthResponseInitState::Enter + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthResponseNegotiateState::GetStateType_002 + * @tc.desc: 1 call AuthResponseNegotiateState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_NEGOTIATE + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, GetStateType_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseNegotiateState()); + int32_t ret = authResponseState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_NEGOTIATE); + sleep(15); +} + +/** + * @tc.name: AuthResponseNegotiateState::Enter_002 + * @tc.desc: 1 set authManager to null + * 2 call AuthResponseNegotiateState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseNegotiateState()); + authManager = nullptr; + authResponseState->SetAuthManager(authManager); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthResponseNegotiateState::Enter_003 + * @tc.desc: 1 set authManager not null + * 2 call AuthResponseNegotiateState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseNegotiateState()); + std::shared_ptr hiChainConnector = std::make_shared(); + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseNegotiateState()); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNegotiateState()); + authManager->authResponseContext_->deviceId = "111"; + authManager->authResponseContext_->localDeviceId = "222"; + authResponseState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + context->deviceId = "123456"; + context->sessionId = 22222; + authResponseState->SetAuthContext(context); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: AuthResponseConfirmState::GetStateType_003 + * @tc.desc: 1 call AuthResponseConfirmState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_CONFIRM + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, GetStateType_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseConfirmState()); + int32_t ret = authResponseState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_CONFIRM); + sleep(15); +} + +/** + * @tc.name: AuthResponseConfirmState::Enter_004 + * @tc.desc: 1 set authManager to null + * 2 call AuthResponseConfirmState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseConfirmState()); + authResponseState->SetAuthManager(nullptr); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthResponseConfirmState::Enter_005 + * @tc.desc: 1 set authManager not null + * 2 call AuthResponseConfirmState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_005, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseConfirmState()); + authResponseState->SetAuthManager(authManager); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthResponseGroupState::GetStateType_004 + * @tc.desc: 1 call AuthResponseGroupState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_GROUP + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, GetStateType_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseGroupState()); + int32_t ret = authResponseState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_GROUP); + sleep(15); +} + +/** + * @tc.name: AuthResponseGroupState::Enter_006 + * @tc.desc: 1 set authManager to null + * 2 call AuthResponseGroupState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_006, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseGroupState()); + authResponseState->SetAuthManager(nullptr); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthResponseGroupState::Enter_007 + * @tc.desc: 1 set authManager not null + * 2 call AuthResponseGroupState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_007, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseGroupState()); + std::shared_ptr hiChainConnector = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authResponseContext_ = std::make_shared(); + authResponseState->SetAuthManager(authManager); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthResponseShowState::GetStateType_005 + * @tc.desc: 1 call AuthResponseShowState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_SHOW + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, GetStateType_005, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseShowState()); + int32_t ret = authResponseState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_SHOW); + sleep(15); +} + +/** + * @tc.name: AuthResponseShowState::Enter_008 + * @tc.desc: 1 set authManager to null + * 2 call AuthResponseShowState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_008, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseShowState()); + authResponseState->SetAuthManager(nullptr); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthResponseShowState::Enter_009 + * @tc.desc: 1 set authManager not null + * 2 call AuthResponseShowState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_009, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseShowState()); + authResponseState->SetAuthManager(authManager); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthResponseFinishState::GetStateType_006 + * @tc.desc: 1 call AuthResponseShowState::GetStateType + * 2 check ret is AuthState::AUTH_RESPONSE_SHOW + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, GetStateType_006, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseFinishState()); + int32_t ret = authResponseState->GetStateType(); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_FINISH); + sleep(15); +} + +/** + * @tc.name: AuthResponseFinishState::Enter_010 + * @tc.desc: 1 set authManager to null + * 2 call AuthResponseFinishState::Enter with authManager = null + * 3 check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_010, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseFinishState()); + authResponseState->SetAuthManager(nullptr); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthResponseFinishState::Enter_011 + * @tc.desc: 1 set authManager not null + * 2 call AuthResponseFinishState::Enter with authManager != null + * 3 check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthResponseStateTest, Enter_011, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseFinishState()); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestFinishState()); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseFinishState()); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->listener_ = std::make_shared(); + authManager->authResponseContext_->sessionId = 1; + authManager->authRequestContext_->deviceId = "2"; + authManager->authRequestContext_->hostPkgName = "3"; + authManager->authRequestContext_->token = "4"; + authManager->authResponseContext_->reply = 5; + authManager->authRequestContext_->reason = 6; + authManager->SetAuthResponseState(authResponseState); + authResponseState->SetAuthManager(authManager); + std::shared_ptr context = std::make_shared(); + authResponseState->SetAuthContext(context); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); + sleep(15); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_auth_response_state.h b/test/unittest/UTTest_auth_response_state.h new file mode 100644 index 000000000..270e5caff --- /dev/null +++ b/test/unittest/UTTest_auth_response_state.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AUTH_RESPONSE_STATE_TEST_H +#define OHOS_AUTH_RESPONSE_STATE_TEST_H + +#include + +#include + +#include "auth_response_state.h" + +namespace OHOS { +namespace DistributedHardware { +class AuthResponseStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp new file mode 100644 index 000000000..585cea342 --- /dev/null +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -0,0 +1,346 @@ +/* + * 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 "UTTest_device_manager_service.h" + +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); + +void DeviceManagerServiceTest::SetUp() +{ +} + +void DeviceManagerServiceTest::TearDown() +{ +} + +void DeviceManagerServiceTest::SetUpTestCase() +{ +} + +void DeviceManagerServiceTest::TearDownTestCase() +{ +} +namespace { + +std::string INPUT_TIMEOUT_TASK = "inputTimeoutTask"; + +/** + * @tc.name: StartDeviceDiscovery_001 + * @tc.desc: Set StartDeviceDiscovery's flag bit intFlag_ to False and return DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + std::string pkgName = "com.ohos.test"; + DmSubscribeInfo subscribeInfo; + std::string extra = "test"; + int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +/** + * @tc.name: StartDeviceDiscovery_002 + * @tc.desc: Empty pkgName of StartDeviceDiscovery and return DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + DmSubscribeInfo subscribeInfo; + std::string extra = "test"; + DeviceManagerService::GetInstance().Init(); + int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: StartDeviceDiscovery_003 + * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return + * DM_DISCOVERY_REPEATED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + DmSubscribeInfo subscribeInfo; + std::string extra = "test"; + int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + pkgName = "1com.ohos.test1"; + ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + EXPECT_EQ(ret, DM_DISCOVERY_FAILED); +} + +/** + * @tc.name: StopDeviceDiscovery_001 + * @tc.desc: Set StopDeviceDiscovery's flag bit intFlag_ to false and return DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 1; + int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +/** + * @tc.name:StopDeviceDiscovery_002 + * @tc.desc: StopDeviceDiscovery is initialized, pkgName is null, and its return value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + uint16_t subscribeId = 1; + DeviceManagerService::GetInstance().Init(); + int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: GetLocalDeviceInfo_001 + * @tc.desc: Set the flag bit of GetLocalDeviceInfo to intFlag_ to false; The return value is DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + DmDeviceInfo info; + int ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +/** + * @tc.name:GetLocalDeviceInfo_002 + * @tc.desc: Initialize the GetLocalDeviceInfo function with the return value DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeviceManagerService::GetInstance().Init(); + int ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: Init_001 + * @tc.desc: The OnDeviceFound function does the worong case and return DM_INT_MULTIPLE + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, Init_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = true; + int ret = DeviceManagerService::GetInstance().Init(); + EXPECT_EQ(ret, DM_INT_MULTIPLE); +} + +/** + * @tc.name: Init_002 + * @tc.desc: The OnDeviceFound function does the correct case and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, Init_002, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + std::shared_ptr softbusConnector_ = nullptr; + int ret = DeviceManagerService::GetInstance().Init(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetTrustedDeviceList_001 + * @tc.desc: Set the intFlag of GetTrustedDeviceList to false. The return value is DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ + +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + std::vector deviceList; + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +/** + * @tc.name: GetTrustedDeviceList_002 + * @tc.desc:Set the intFlag of GetTrustedDeviceList to true and pkgName = null ; The return value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_002, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = true; + std::string pkgName; + std::string extra = "jdddd"; + std::vector deviceList; + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: AuthenticateDevice_001 + * @tc.desc: 将GAuthenticateDevice的intFlag设置为false,设置pkgName = "com.ohos.test";其返回值为DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + int32_t authType = 0; + std::string deviceId = " 2345"; + int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +/** + * @tc.name: AuthenticateDevice_002 + * @tc.desc: Set intFlag for GAuthenticateDevice to True and pkgName to null; The return value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_002, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = true; + std::string pkgName; + std::string extra = "jdddd"; + int32_t authType = 0; + std::string deviceId = " 2345"; + int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: AuthenticateDevice_003 + * @tc.desc: Set intFlag for GAuthenticateDevice to true and pkgName to com.ohos.test; The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_003, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = true; + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + int32_t authType = 0; + std::string deviceId = "123456"; + int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnAuthenticateDevice_001 + * @tc.desc: 将UnAuthenticateDevice的intFlag设置为false,设置pkgName = "com.ohos.test";其返回值为DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + std::string pkgName = "com.ohos.test"; + std::string deviceId = "12345"; + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +/** + * @tc.name: UnAuthenticateDevice_002 + * @tc.desc: Set intFlag for UnAuthenticateDevice to True and pkgName to null; The return value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_002, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = true; + std::string pkgName; + std::string deviceId = "12345"; + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: UnAuthenticateDevice_003 + * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return + * value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_003, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = true; + std::string pkgName = "com.ohos.test"; + std::string deviceId; + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: VerifyAuthentication_001 + * @tc.desc: Set intFlag for VerifyAuthentication to false and set authParam = "jdjjjj",The return value is + * DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, VerifyAuthentication_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = false; + std::string authParam = "jdjjjj"; + int ret = DeviceManagerService::GetInstance().VerifyAuthentication(authParam); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +/** + * @tc.name: VerifyAuthentication_002 + * @tc.desc:Set intFlag for VerifyAuthentication to true and set authParam = "jdjjjj",The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, VerifyAuthentication_002, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().intFlag_ = true; + std::string authParam = "jdjjjj"; + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener_ = std::make_shared(); + DeviceManagerService::GetInstance().authMgr_ = std::make_shared(softbusConnector, listener_); + std::shared_ptr inputStartTimer = std::make_shared(INPUT_TIMEOUT_TASK); + DeviceManagerService::GetInstance().authMgr_->timerMap_[INPUT_TIMEOUT_TASK] = inputStartTimer; + int ret = DeviceManagerService::GetInstance().VerifyAuthentication(authParam); + EXPECT_EQ(ret, DM_FAILED); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h new file mode 100644 index 000000000..30693e87d --- /dev/null +++ b/test/unittest/UTTest_device_manager_service.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_UTTEST_DM_SERVICE_H +#define OHOS_UTTEST_DM_SERVICE_H + +#include +#include + +#include +#include + +#include "device_manager_service.h" +#include "device_manager_service_listener.h" +#include "dm_auth_manager.h" +#include "dm_device_info_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "single_instance.h" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { + +class DeviceManagerServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#undef private +#undef protected +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp new file mode 100644 index 000000000..3d63e1f0c --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_listener.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 "UTTest_device_manager_service_listener.h" + +#include + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_discover_result_req.h" +#include "ipc_notify_verify_auth_result_req.h" + +namespace OHOS { +namespace DistributedHardware { +void DeviceManagerServiceListenerTest::SetUp() +{ +} +void DeviceManagerServiceListenerTest::TearDown() +{ +} +void DeviceManagerServiceListenerTest::SetUpTestCase() +{ +} +void DeviceManagerServiceListenerTest::TearDownTestCase() +{ +} +namespace { + +/** + * @tc.name: OnDeviceStateChange_001 + * @tc.desc: OnDeviceStateChange, construct a dummy listener, pass in pkgName, use the constructed listener to get + * deviceTypeId + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + DmDeviceState state = DEVICE_STATE_ONLINE; + DmDeviceInfo info = { + .deviceId = "asdad", + .deviceName = "asda", + .deviceTypeId = 1, + }; + listener_->OnDeviceStateChange(pkgName, state, info); + std::shared_ptr pReq = + std::static_pointer_cast(listener_->ipcServerListener_.req_); + int32_t dmState = pReq->GetDeviceState(); + EXPECT_EQ(1, dmState); +} + +/** + * @tc.name: OnAuthResult_001 + * @tc.desc:OnAuthResult, construct a dummy listener, pass in pkgName, use the constructed listener to get pkgName + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + std::string deviceId = "dkdkd"; + std::string token = "kdkddk"; + int32_t status = 3; + std::string reason = "kddk"; + listener_->OnAuthResult(pkgName, deviceId, token, status, reason); + std::shared_ptr pReq = + std::static_pointer_cast(listener_->ipcServerListener_.req_); + std ::string ret = pReq->GetPkgName(); + EXPECT_EQ(ret, pkgName); +} + +/** + * @tc.name: OnVerifyAuthResult_001 + * @tc.desc: OnVerifyAuthResult,construct a dummy listener, pass in pkgName, use the constructed listener to get + * deviceId + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, OnVerifyAuthResult_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + std::string deviceId = "dkdkd"; + int32_t resultCode = 1; + std::string flag = "true"; + listener_->OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); + std::shared_ptr pReq = + std::static_pointer_cast(listener_->ipcServerListener_.req_); + std ::string ret = pReq->GetDeviceId(); + EXPECT_EQ(ret, deviceId); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service_listener.h b/test/unittest/UTTest_device_manager_service_listener.h new file mode 100644 index 000000000..2c07604ca --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_listener.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_UTTEST_DM_SERVICE_LISTENER_H +#define OHOS_UTTEST_DM_SERVICE_LISTENER_H + +#define private public +#define protected public + +#include +#include + +#include + +#include "device_manager_service_listener.h" +#include "dm_device_info.h" +#include "ipc_server_listener.h" + +namespace OHOS { +namespace DistributedHardware { + +class DeviceManagerServiceListenerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#undef private +#undef protected +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_device_message.cpp b/test/unittest/UTTest_device_message.cpp new file mode 100644 index 000000000..ba7308964 --- /dev/null +++ b/test/unittest/UTTest_device_message.cpp @@ -0,0 +1,514 @@ +/* + * 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_log.h" +#include "dm_constants.h" +#include "UTTest_device_message.h" +#include "auth_message_processor.h" +#include "softbus_connector.h" +#include "softbus_session.h" +#include "dm_auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { +void AuthMessageProcessorTest::SetUp() +{ +} +void AuthMessageProcessorTest::TearDown() +{ +} +void AuthMessageProcessorTest::SetUpTestCase() +{ +} +void AuthMessageProcessorTest::TearDownTestCase() +{ +} + +namespace{ + +/** + * @tc.name: AuthMessageProcessor::CreateNegotiateMessage_001 + * @tc.desc: 1 set cryptoAdapter_ to null + * 2 call AuthMessageProcessor::CreateNegotiateMessage_001 with cryptoAdapter_ = nullptr + * 3 check ret is authMessageProcessor->CreateNegotiateMessage(jsonObj); + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + int32_t msgType = MSG_TYPE_NEGOTIATE; + nlohmann::json jsonObj; + jsonObj[TAG_VER] = DM_ITF_VER; + jsonObj[TAG_TYPE] = msgType; + authMessageProcessor->cryptoAdapter_ = nullptr; + authMessageProcessor->CreateNegotiateMessage(jsonObj); + std::string str1 = jsonObj.dump(); + nlohmann::json jsonObject; + jsonObject[TAG_VER] = DM_ITF_VER; + jsonObject[TAG_TYPE] = msgType; + jsonObject[TAG_CRYPTO_SUPPORT] = false; + std::string str2 = jsonObject.dump(); + ASSERT_EQ(str1, str2); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::CreateSyncGroupMessage_001 + * @tc.desc: Compare JSON before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, CreateSyncGroupMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + authMessageProcessor->authRequestContext_= std::make_shared(); + nlohmann::json jsona; + nlohmann::json jsonObj; + authMessageProcessor->authRequestContext_->deviceId = "132416546"; + std::vector syncGroupList ; + syncGroupList.push_back("1111"); + authMessageProcessor->authRequestContext_->syncGroupList = syncGroupList; + jsona[TAG_DEVICE_ID] = authMessageProcessor->authRequestContext_->deviceId; + jsona[TAG_GROUPIDS] = authMessageProcessor->authRequestContext_->syncGroupList; + authMessageProcessor->CreateSyncGroupMessage(jsonObj); + std::string str1 = jsona.dump(); + std::string str2 = jsonObj.dump(); + ASSERT_EQ(str1, str2); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::CreateResponseAuthMessage_001 + * @tc.desc: Compare JSON before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsona; + nlohmann::json jsonObj; + authMessageProcessor->authResponseContext_->reply = 0; + authMessageProcessor->authResponseContext_->deviceId = "132416546"; + nlohmann::json jsonb; + jsonb[TAG_GROUP_ID] = "123456"; + authMessageProcessor->authResponseContext_->groupId = jsonb.dump(); + authMessageProcessor->authResponseContext_->code = 1; + authMessageProcessor->authResponseContext_->networkId = "11112222"; + authMessageProcessor->authResponseContext_->requestId = 222222; + authMessageProcessor->authResponseContext_->groupName = "333333"; + jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; + jsona[TAG_DEVICE_ID] = authMessageProcessor->authResponseContext_->deviceId; + jsona[PIN_CODE_KEY] = authMessageProcessor->authResponseContext_->code; + jsona[TAG_NET_ID] = authMessageProcessor->authResponseContext_->networkId; + jsona[TAG_REQUEST_ID] = authMessageProcessor->authResponseContext_->requestId; + jsona[TAG_GROUP_ID] = "123456"; + jsona[TAG_GROUP_NAME] = authMessageProcessor->authResponseContext_->groupName; + authMessageProcessor->CreateResponseAuthMessage(jsonObj); + std::string str1 = jsona.dump(); + std::string str2 = jsonObj.dump(); + ASSERT_EQ(str1, str2); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::CreateResponseFinishMessage_001 + * @tc.desc: Compare JSON before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, CreateResponseFinishMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsona; + nlohmann::json jsonObj; + authMessageProcessor->authResponseContext_->reply= 1; + jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; + authMessageProcessor->CreateResponseFinishMessage(jsonObj); + std::string str1 = jsona.dump(); + std::string str2 = jsonObj.dump(); + ASSERT_EQ(str1, str2); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseResponseFinishMessage_001 + * @tc.desc: Compare JSON before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseResponseFinishMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext= std::make_shared(); + authMessageProcessor->authResponseContext_= std::make_shared(); + nlohmann::json jsonObj; + authMessageProcessor->authResponseContext_->reply = 1; + jsonObj[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseResponseFinishMessage(jsonObj); + ASSERT_EQ(authMessageProcessor->authResponseContext_,authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseAuthResponseMessage_001 + * @tc.desc: Compare JSON before and after assi gnment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseAuthResponseMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + nlohmann::json jsona; + authResponseContext->reply = 0; + authResponseContext->deviceId = "11111"; + authResponseContext->code = 1; + authResponseContext->networkId = "12345"; + authResponseContext->requestId = 2; + authResponseContext->groupId = "23456"; + authResponseContext->groupName = "34567"; + jsona[TAG_REPLY] = authResponseContext->reply; + jsona[TAG_DEVICE_ID] = authResponseContext->deviceId; + jsona[PIN_CODE_KEY] = authResponseContext->code; + jsona[TAG_NET_ID] = authResponseContext->networkId; + jsona[TAG_REQUEST_ID] = authResponseContext->requestId; + jsona[TAG_GROUP_ID] = authResponseContext->groupId; + jsona[TAG_GROUP_NAME] = authResponseContext->groupName; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseAuthResponseMessage(jsona); + ASSERT_EQ(authMessageProcessor->authResponseContext_, authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseAuthRequestMessage_001 + * @tc.desc: Compare JSON before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseAuthRequestMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->SetResponseContext(authResponseContext); + nlohmann::json json; + nlohmann::json jsonThumbnail; + authResponseContext->deviceId = "123"; + authResponseContext->reply = 0; + authResponseContext->authType = 222; + authResponseContext->networkId = "234"; + authResponseContext->groupId = "345"; + authResponseContext->groupName = "456"; + authResponseContext->requestId = 2333; + jsonThumbnail[TAG_DEVICE_ID] = authResponseContext->deviceId; + jsonThumbnail[TAG_REPLY] = authResponseContext->reply; + jsonThumbnail[TAG_AUTH_TYPE] = authResponseContext->authType; + jsonThumbnail[TAG_NET_ID] = authResponseContext->networkId; + jsonThumbnail[TAG_GROUP_ID] = authResponseContext->groupId ; + jsonThumbnail[TAG_GROUP_NAME] = authResponseContext->groupName; + jsonThumbnail[TAG_REQUEST_ID] = authResponseContext->requestId; + authMessageProcessor->authSplitJsonList_.push_back(jsonThumbnail); + int32_t ret = authMessageProcessor->ParseAuthRequestMessage(); + ASSERT_EQ(ret,DM_FAILED); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseAuthRequestMessage_002 + * @tc.desc: Compare JSON before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseAuthRequestMessage_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->SetResponseContext(authResponseContext); + nlohmann::json json; + nlohmann::json jsonThumbnail; + authResponseContext->deviceId = "123"; + authResponseContext->reply = 1; + authResponseContext->authType = 222; + authResponseContext->networkId = "234"; + authResponseContext->groupId = "345"; + authResponseContext->groupName = "456"; + authResponseContext->requestId = 2333; + jsonThumbnail[TAG_DEVICE_ID] = authResponseContext->deviceId; + jsonThumbnail[TAG_REPLY] = authResponseContext->reply; + jsonThumbnail[TAG_AUTH_TYPE] = authResponseContext->authType; + jsonThumbnail[TAG_NET_ID] = authResponseContext->networkId; + jsonThumbnail[TAG_GROUP_ID] = authResponseContext->groupId ; + jsonThumbnail[TAG_GROUP_NAME] = authResponseContext->groupName; + jsonThumbnail[TAG_REQUEST_ID] = authResponseContext->requestId; + authMessageProcessor->authSplitJsonList_.push_back(jsonThumbnail); + int32_t ret = authMessageProcessor->ParseAuthRequestMessage(); + ASSERT_EQ(ret,DM_OK); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseNegotiateMessage_001 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObj; + jsonObj[TAG_CRYPTO_SUPPORT]="CRYPTOSUPPORT"; + jsonObj[TAG_CRYPTO_SUPPORT] = authMessageProcessor->authResponseContext_->cryptoSupport; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseNegotiateMessage(jsonObj); + ASSERT_EQ( authMessageProcessor->authResponseContext_, authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseNegotiateMessage_002 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObj; + jsonObj[TAG_CRYPTO_NAME]="CRYPTONAME"; + jsonObj[TAG_CRYPTO_NAME] = authResponseContext->cryptoSupport; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseNegotiateMessage(jsonObj); + ASSERT_EQ( authMessageProcessor->authResponseContext_, authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseNegotiateMessage_003 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObj; + jsonObj[TAG_CRYPTO_VERSION]="CRYPTOVERSION"; + jsonObj[TAG_CRYPTO_VERSION] = authResponseContext->cryptoSupport; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseNegotiateMessage(jsonObj); + ASSERT_EQ( authMessageProcessor->authResponseContext_, authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseNegotiateMessage_004 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObj; + jsonObj[TAG_DEVICE_ID]="DEVICEID"; + jsonObj[TAG_DEVICE_ID] = authResponseContext->deviceId; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseNegotiateMessage(jsonObj); + ASSERT_EQ( authMessageProcessor->authResponseContext_, authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::ParseNegotiateMessage_005 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_005, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor= std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObj; + jsonObj[TAG_LOCAL_DEVICE_ID]="LOCALDEVICEID"; + jsonObj[TAG_LOCAL_DEVICE_ID] = authResponseContext->localDeviceId; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseNegotiateMessage(jsonObj); + ASSERT_EQ( authMessageProcessor->authResponseContext_, authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::SetRequestContext_001 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, SetRequestContext_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor = std::make_shared(data); + std::shared_ptr authRequestContext = std::make_shared(); + authMessageProcessor->SetRequestContext(authRequestContext); + ASSERT_EQ(authMessageProcessor->authRequestContext_,authRequestContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::SetRequestContext_002 + * @tc.desc: Judge whether authrequestcontext is empty + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, SetRequestContext_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor = std::make_shared(data); + std::shared_ptr authRequestContext = std::make_shared(); + authMessageProcessor->SetRequestContext(nullptr); + ASSERT_EQ(authMessageProcessor->authRequestContext_,nullptr); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::SetResponseContext_001 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, SetResponseContext_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor = std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->SetResponseContext(authResponseContext); + ASSERT_EQ(authMessageProcessor->authResponseContext_,authResponseContext); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::SetResponseContext_002 + * @tc.desc: Judge whether authrequestcontext is empty + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, SetResponseContext_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor = std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->SetResponseContext(nullptr); + ASSERT_EQ(authMessageProcessor->authResponseContext_,nullptr); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::GetResponseContext_001 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, GetResponseContext_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor = std::make_shared(data); + authMessageProcessor->authResponseContext_ = std::make_shared(); + std::shared_ptr authResponseContext = authMessageProcessor->GetResponseContext(); + ASSERT_EQ(authResponseContext, authMessageProcessor->authResponseContext_); + sleep(15); +} + +/** + * @tc.name: AuthMessageProcessor::GetResponseContext_002 + * @tc.desc: Judge whether authrequestcontext is empty + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, GetResponseContext_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr data = std::make_shared(softbusConnector, listener); + std::shared_ptr authMessageProcessor = std::make_shared(data); + authMessageProcessor->authResponseContext_ = std::make_shared(); + std::shared_ptr authResponseContext = authMessageProcessor->GetResponseContext(); + ASSERT_NE(authResponseContext,nullptr); + sleep(15); +} +} +} +} diff --git a/test/unittest/UTTest_device_message.h b/test/unittest/UTTest_device_message.h new file mode 100644 index 000000000..3d818e9a8 --- /dev/null +++ b/test/unittest/UTTest_device_message.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_MESSAGE_TEST_H +#define OHOS_DEVICE_MESSAGE_TEST_H +#define private public +#define protected public + +#include +#include +#include +#include "nlohmann/json.hpp" +#include "auth_message_processor.h" + +namespace OHOS { +namespace DistributedHardware { +class AuthMessageProcessorTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} +} +#endif // OHOS_DM_IMPL_TEST_H +#undef private +#undef protected diff --git a/test/unittest/UTTest_dm_auth_manager.cpp b/test/unittest/UTTest_dm_auth_manager.cpp new file mode 100644 index 000000000..a911efe3a --- /dev/null +++ b/test/unittest/UTTest_dm_auth_manager.cpp @@ -0,0 +1,569 @@ +/* + * 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_auth_manager.h" + +#include "nlohmann/json.hpp" + +#include "dm_log.h" +#include "dm_constants.h" +#include "auth_message_processor.h" +#include "UTTest_dm_auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { +void DmAuthManagerTest::SetUp() +{ +} +void DmAuthManagerTest::TearDown() +{ +} +void DmAuthManagerTest::SetUpTestCase() +{ +} +void DmAuthManagerTest::TearDownTestCase() +{ +} + +namespace{ + + std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; + std::string NEGOTIATE_TIMEOUT_TASK = "negotiateTimeoutTask"; + std::string CONFIRM_TIMEOUT_TASK = "confirmTimeoutTask"; + std::string INPUT_TIMEOUT_TASK = "inputTimeoutTask"; + std::string ADD_TIMEOUT_TASK = "addTimeoutTask"; + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_001 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_AUTH_BUSINESS_BUSY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); + std::shared_ptr context = std::make_shared(); + std::string pkgName = "111"; + int32_t authType = 1; + std::string deviceId = "222"; + std::string extra = "333"; + authRequestState->SetAuthContext(context); + authManager->SetAuthRequestState(authRequestState); + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret,DM_AUTH_BUSINESS_BUSY); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_002 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_AUTH_BUSINESS_BUSY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseInitState()); + std::shared_ptr context = std::make_shared(); + const std::string pkgName = "111"; + int32_t authType = 1; + const std::string deviceId = "222"; + const std::string extra = "333"; + authResponseState->SetAuthContext(context); + authManager->SetAuthResponseState(authResponseState); + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret,DM_AUTH_BUSINESS_BUSY); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_003 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + std::string pkgName = "111"; + int32_t authType = 1; + std::string deviceId = "222"; + std::string extra = ""; + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_004 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + nlohmann::json json; + const std::string pkgName = "111"; + int32_t authType = 4; + const std::string deviceId = "222"; + const std::string extra = "targetPkgName"; + authRequestContext->targetPkgName = "targetPkgName"; + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret, DM_INPUT_PARA_EMPTY); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_005 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_005, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + nlohmann::json json; + const std::string pkgName = "111"; + int32_t authType = 1; + const std::string deviceId = "222"; + const std::string extra = "targetPkgName"; + authRequestContext->targetPkgName = "targetPkgName"; + json[TARGET_PKG_NAME_KEY] = authRequestContext->targetPkgName; + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_006 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_006, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + nlohmann::json json; + const std::string pkgName = "111"; + int32_t authType = 1; + const std::string deviceId = "222"; + const std::string extra = "appName"; + authRequestContext->targetPkgName = "appName"; + json[APP_NAME_KEY] = authRequestContext->targetPkgName; + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_007 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_007, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + nlohmann::json json; + const std::string pkgName = "111"; + int32_t authType = 1; + const std::string deviceId = "222"; + const std::string extra = "appDescription"; + authRequestContext->targetPkgName = "appDescription"; + json[APP_DESCRIPTION_KEY] = authRequestContext->targetPkgName; + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_008 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_008, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + nlohmann::json json; + const std::string pkgName = "111"; + int32_t authType = 1; + const std::string deviceId = "222"; + const std::string extra = "appThumbnail"; + authRequestContext->targetPkgName = "appThumbnail"; + json[APP_THUMBNAIL] = authRequestContext->targetPkgName; + int32_t ret =authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DmAuthManager::AuthenticateDevice_009 + * @tc.desc: Call authenticatedevice to check whether the return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_009, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + nlohmann::json json; + const std::string pkgName = "111"; + int32_t authType = 1; + const std::string deviceId = "222"; + const std::string extra = "appIcon"; + authRequestContext->targetPkgName = "appIcon"; + json[APP_ICON_KEY] = authRequestContext->targetPkgName; + int32_t ret = authManager->AuthenticateDevice(pkgName,authType,deviceId,extra); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DmAuthManager::UnAuthenticateDevice_001 + * @tc.desc: Call unauthenticateddevice to check whether the return value is DM_ FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + std::string pkgName = ""; + std::string deviceId = "222"; + int32_t ret =authManager->UnAuthenticateDevice(pkgName,deviceId); + ASSERT_EQ(ret,DM_FAILED); +} + +/** + * @tc.name: DmAuthManager::VerifyAuthentication_001 + * @tc.desc: Call verifyauthentication to check whether the return value is DM_ FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, VerifyAuthentication_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNetworkState()); + std::shared_ptr negotiateStartTimer = std::make_shared(INPUT_TIMEOUT_TASK); + authManager->timerMap_[INPUT_TIMEOUT_TASK] = negotiateStartTimer; + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNetworkState()); + authManager->authResponseContext_=nullptr; + authManager->SetAuthRequestState(authRequestState); + int32_t ret =authManager->HandleAuthenticateTimeout(); + ASSERT_EQ(ret,DM_FAILED); +} + + + + +/** + * @tc.name: DmAuthManager::HandleAuthenticateTimeout_001 + * @tc.desc: authResponseContext_= nullptr; Call handleauthenticatemeout to check whether the return value is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNetworkState()); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNetworkState()); + authManager->authResponseContext_=nullptr; + authManager->SetAuthRequestState(authRequestState); + int32_t ret =authManager->HandleAuthenticateTimeout(); + ASSERT_EQ(ret,DM_FAILED); +} + +/** + * @tc.name: DmAuthManager::HandleAuthenticateTimeout_002 + * @tc.desc: authResponseContext_= nullptr; Call handleauthenticatemeout to check whether the return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestFinishState()); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestFinishState()); + authManager->SetAuthRequestState(authRequestState); + int32_t ret =authManager->HandleAuthenticateTimeout(); + ASSERT_EQ(ret,DM_OK); +} + +/** + * @tc.name: DmAuthManager::EstablishAuthChannel_001 + * @tc.desc: Call establishauthchannel to check whether the return value is DM_ FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, EstablishAuthChannel_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr sessionSession = std::shared_ptr(); + std::shared_ptr authRequestContext = std::make_shared(); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestFinishState()); + std::string deviceId1; + int32_t ret =authManager->EstablishAuthChannel(deviceId1); + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: DmAuthManager::SendAuthRequest_001 + * @tc.desc: Cryptosupport = true call sendauthrequest to check whether the return value is DM_ FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, SendAuthRequest_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNegotiateState()); + std::shared_ptr negotiateStartTimer = std::make_shared(NEGOTIATE_TIMEOUT_TASK); + authManager->timerMap_[NEGOTIATE_TIMEOUT_TASK] = negotiateStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared();; + authManager->authRequestState_ = std::shared_ptr(new AuthRequestFinishState()); + authManager->authResponseContext_->cryptoSupport = true; + authManager->SetAuthRequestState(authRequestState); + int32_t sessionId=1; + int32_t ret =authManager->SendAuthRequest(sessionId); + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: DmAuthManager::StartAuthProcess_001 + * @tc.desc: Whether the return value of calling startauthprocess is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, StartAuthProcess_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseConfirmState()); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseConfirmState()); + authManager->SetAuthResponseState(authResponseState); + int32_t action = 0; + int32_t ret =authManager->StartAuthProcess(action); + ASSERT_EQ(ret,DM_FAILED); +} + +/** + * @tc.name: DmAuthManager::StartAuthProcess_002 + * @tc.desc: Whether the return value of calling startauthprocess is DM_ OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, StartAuthProcess_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseConfirmState()); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseConfirmState()); + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->SetAuthResponseState(authResponseState); + authManager->authResponseContext_->sessionId=111; + int32_t action = 1; + int32_t ret =authManager->StartAuthProcess(action); + ASSERT_EQ(ret,DM_OK); +} + +/** + * @tc.name: DmAuthManager::CreateGroup_001 + * @tc.desc: Whether the return value of calling creategroup is DM_ OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, CreateGroup_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseConfirmState()); + std::shared_ptr hiChainConnector = std::make_shared(); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseConfirmState()); + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->SetAuthResponseState(authResponseState); + authManager->authResponseContext_->requestId=111; + authManager->authResponseContext_->groupName="111"; + int32_t action = 1; + int32_t ret =authManager->StartAuthProcess(action); + ASSERT_EQ(ret,DM_OK); +} + +/** + * @tc.name: DmAuthManager::AddMember_001 + * @tc.desc: Whether the return value of calling addmember is DM_ OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, AddMember_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseInitState()); + authManager->authRequestContext_ = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr joinStartTimer = std::make_shared(ADD_TIMEOUT_TASK); + authManager->timerMap_[ADD_TIMEOUT_TASK] = joinStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObject; + authManager->authResponseContext_->groupId="111"; + authManager->authResponseContext_->groupName="222"; + authManager->authResponseContext_->code=123; + authManager->authResponseContext_->requestId=234; + authManager->authResponseContext_->deviceId="234"; + jsonObject[TAG_GROUP_ID] = authManager->authResponseContext_->groupId; + jsonObject[TAG_GROUP_NAME] = authManager->authResponseContext_->groupName; + jsonObject[PIN_CODE_KEY] = authManager->authResponseContext_->code; + jsonObject[TAG_REQUEST_ID] = authManager->authResponseContext_->requestId; + jsonObject[TAG_DEVICE_ID] = authManager->authResponseContext_->deviceId; + std::string deviceId = "44444"; + authManager->SetAuthResponseState(authResponseState); + int32_t ret =authManager->AddMember(deviceId); + ASSERT_EQ(ret,DM_OK); + sleep(15); +} + +/** + * @tc.name: DmAuthManager::JoinNetwork_001 + * @tc.desc: Whether the return value of calling joinnetwork is DM_ OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, JoinNetwork_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestFinishState()); + std::shared_ptr authenticateStartTimer = std::make_shared(AUTHENTICATE_TIMEOUT_TASK); + authManager->timerMap_[AUTHENTICATE_TIMEOUT_TASK] = authenticateStartTimer; + authManager->authMessageProcessor_ = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestFinishState()); + authManager->SetAuthRequestState(authRequestState); + int32_t ret =authManager->JoinNetwork(); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DmAuthManager::GetIsCryptoSupport_001 + * @tc.desc: authResponseState_ Equal to nullptr + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, GetIsCryptoSupport_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseFinishState()); + bool isCryptoSupport = false; + int32_t ret =authManager->GetIsCryptoSupport(isCryptoSupport); + ASSERT_EQ(ret,DM_OK); +} + +/** + * @tc.name: DmAuthManager::SetAuthResponseState_001 + * @tc.desc: Is the authresponsestate assignment successful + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, SetAuthResponseState_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseFinishState()); + authManager->authResponseState_ = std::shared_ptr(new AuthResponseFinishState()); + authManager->SetAuthResponseState(authResponseState); + int32_t ret =authManager->SetAuthResponseState(authResponseState); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DmAuthManager::GetPinCode_001 + * @tc.desc: Return authresponsecontext - > code + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAuthManagerTest, GetPinCode_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener); + authManager->authResponseContext_ = std::make_shared();; + int32_t ret =authManager->GetPinCode(); + ASSERT_EQ(ret,authManager->authResponseContext_->code); +} +} +} +} diff --git a/test/unittest/UTTest_dm_auth_manager.h b/test/unittest/UTTest_dm_auth_manager.h new file mode 100644 index 000000000..12aec0294 --- /dev/null +++ b/test/unittest/UTTest_dm_auth_manager.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_AUTH_MANAGER_TEST_H +#define OHOS_DM_AUTH_MANAGER_TEST_H + +#include +#include +#include + +#include "authentication.h" +#include "softbus_session.h" +#include "device_manager_service_listener.h" +#include "dm_adapter_manager.h" +#include "dm_constants.h" +#include "softbus_connector.h" +#include "hichain_connector.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "auth_message_processor.h" +#include "dm_timer.h" +#include "dm_auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} +} +#endif diff --git a/test/unittest/UTTest_dm_device_info_manager.cpp b/test/unittest/UTTest_dm_device_info_manager.cpp new file mode 100644 index 000000000..992f5a011 --- /dev/null +++ b/test/unittest/UTTest_dm_device_info_manager.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_device_info_manager.h" + +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +void DeviceManagerImplTest::SetUp() +{ +} + +void DeviceManagerImplTest::TearDown() +{ +} + +void DeviceManagerImplTest::SetUpTestCase() +{ +} + +void DeviceManagerImplTest::TearDownTestCase() +{ +} + +namespace { + +std::shared_ptr softbusConnector = std::make_shared(); +std::shared_ptr listener_ = std::make_shared(); +std::shared_ptr dmDeviceStateManager = + std::shared_ptr(new DmDeviceInfoManager(softbusConnector)); + +/** + * @tc.name: DmDeviceInfoManager_001 + * @tc.desc: Returns a new pointer to the constructor DmDeviceInfoManager new + * to construct an environment where the device has been discovered, and stop discovering + * the device. Its return value is DM_INPUT_PARA_EMPTY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerImplTest, DmDeviceInfoManager_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr p = + std::shared_ptr(new DmDeviceInfoManager(softbusConnector)); + ASSERT_NE(p, nullptr); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_device_info_manager.h b/test/unittest/UTTest_dm_device_info_manager.h new file mode 100644 index 000000000..565d7a8f7 --- /dev/null +++ b/test/unittest/UTTest_dm_device_info_manager.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_UTTEST_DM_DEVICEINFO_MANAGER_H +#define OHOS_UTTEST_DM_DEVICEINFO_MANAGER_H + +#include +#include + +#include +#include + +#include "device_manager_service_listener.h" +#include "dm_adapter_manager.h" +#include "dm_device_info.h" +#include "dm_device_info_manager.h" +#include "softbus_connector.h" +#include "softbus_session_callback.h" + +namespace OHOS { +namespace DistributedHardware { + +class DeviceManagerImplTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#undef private +#undef protected +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_dm_device_state_manager.cpp b/test/unittest/UTTest_dm_device_state_manager.cpp new file mode 100644 index 000000000..8ea55d520 --- /dev/null +++ b/test/unittest/UTTest_dm_device_state_manager.cpp @@ -0,0 +1,200 @@ +/* + * 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 "UTTest_dm_device_state_manager.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_adapter_manager.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_verify_auth_result_req.h" +#include "dm_device_state_manager.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_discover_result_req.h" + +namespace OHOS { +namespace DistributedHardware { + +void DmDeviceStateManagerTest::SetUp() +{ +} + +void DmDeviceStateManagerTest::TearDown() +{ +} + +void DmDeviceStateManagerTest::SetUpTestCase() +{ +} + +void DmDeviceStateManagerTest::TearDownTestCase() +{ +} +namespace { + +std::shared_ptr softbusConnector = std::make_shared(); +std::shared_ptr listener_ = std::make_shared(); +std::shared_ptr dmDeviceStateManager = std::shared_ptr(new DmDeviceStateManager(softbusConnector, listener_)); + +/** + * @tc.name: DmDeviceStateManager_001 + * @tc.desc: set DmDeviceStateManager to tne new pointer,and it's not nullptr + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, DmDeviceStateManager_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr p = std::shared_ptr(new DmDeviceStateManager(softbusConnector, listener_)); + ASSERT_NE(p, nullptr); + +} + +/** + * @tc.name: DmDeviceStateManager_002 + * @tc.desc: set DmDeviceStateManager to tne new pointer,it's not nullptr and delete it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, DmDeviceStateManager_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr p = std::shared_ptr(new DmDeviceStateManager(softbusConnector, listener_)); + p.reset(); + EXPECT_EQ(p, nullptr); +} + +/** + * @tc.name: OnDeviceOnline_001 + * @tc.desc: set info.deviceId to some para,and return it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, OnDeviceOnline_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "123"; + DmDeviceInfo info ; + strncpy (info.deviceId, "123", sizeof(info.deviceId)); + dmDeviceStateManager->OnDeviceOnline(pkgName, info); + std::shared_ptr pReq = std::static_pointer_cast (listener_->ipcServerListener_.req_); + DmDeviceInfo ret = pReq->GetDeviceInfo(); + int result = strcmp(info.deviceId,ret.deviceId); + EXPECT_EQ (result ,0); +} + +/** + * @tc.name: OnDeviceOffline_001 + * @tc.desc: set info.deviceId to some para,and return it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, OnDeviceOffline_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + DmDeviceInfo info; + strncpy (info.deviceId, "123", sizeof(info.deviceId)); + dmDeviceStateManager->OnDeviceOffline(pkgName, info); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + DmDeviceInfo ret = pReq->GetDeviceInfo(); + int result = strcmp(info.deviceId,ret.deviceId); + EXPECT_EQ (result ,0); +} + +/** + * @tc.name: OnDeviceChanged_001 + * @tc.desc: set info.deviceId to some para,and return it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, OnDeviceChanged_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + DmDeviceInfo info ; + strncpy (info.deviceId, "123", sizeof(info.deviceId)); + dmDeviceStateManager->OnDeviceChanged(pkgName, info); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + DmDeviceInfo ret = pReq->GetDeviceInfo(); + int result = strcmp(info.deviceId,ret.deviceId); + EXPECT_EQ (result ,0); +} + +/** + * @tc.name: OnDeviceReady_001 + * @tc.desc: set info.deviceId to some para,and return it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, OnProfileReady_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string deviceId; + DmDeviceInfo info ; + strncpy (info.deviceId, "123", sizeof(info.deviceId)); + dmDeviceStateManager->OnProfileReady(pkgName, deviceId); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + DmDeviceInfo ret = pReq->GetDeviceInfo(); + int result = strcmp(info.deviceId,ret.deviceId); + ASSERT_GE(result,0); +} + +/** + * @tc.name: OnDeviceReady_001 + * @tc.desc: set info.deviceId to 123,and call OnDeviceReady ,change info.deviceId to 4 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, OnDeviceReady_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + DmDeviceInfo info ; + strncpy (info.deviceId, "123", sizeof(info.deviceId)); + dmDeviceStateManager->OnDeviceReady(pkgName,info); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + DmDeviceInfo ret = pReq->GetDeviceInfo(); + int result = strcmp(info.deviceId,ret.deviceId); + ASSERT_GE(result,0); +} + +/** + * @tc.name: OnDeviceChanged_001 + * @tc.desc: set info.deviceId to 123,and call OnDeviceChanged ,change info.deviceId to 4 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, OnDeviceChanged_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + DmDeviceInfo info ; + strncpy (info.deviceId, "123", sizeof(info.deviceId)); + dmDeviceStateManager->OnDeviceChanged(pkgName, info); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + DmDeviceInfo ret = pReq->GetDeviceInfo(); + int result = strcmp(info.deviceId,ret.deviceId); + ASSERT_GE(result,0); +} + +/** + * @tc.name: RegisterSoftbusStateCallback_001 + * @tc.desc: call RegisterSoftbusStateCallback and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDeviceStateManagerTest, RegisterSoftbusStateCallback_001, testing::ext::TestSize.Level0) +{ + int ret = dmDeviceStateManager->RegisterSoftbusStateCallback(); + EXPECT_EQ (ret,DM_OK); +} +} +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_dm_device_state_manager.h b/test/unittest/UTTest_dm_device_state_manager.h new file mode 100644 index 000000000..68f88a297 --- /dev/null +++ b/test/unittest/UTTest_dm_device_state_manager.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_UTTEST_DM_DEVICE_STATE_MANAGER_H +#define OHOS_UTTEST_DM_DEVICE_STATE_MANAGER_H + +#include +#include + +#include "softbus_connector.h" +#include "dm_adapter_manager.h" +#include "device_manager_service_listener.h" +#include "softbus_session_callback.h" +#include "dm_discovery_manager.h" + +namespace OHOS +{ +namespace DistributedHardware +{ + +class DmDeviceStateManagerTest : public testing::Test +{ +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} +} +#undef private +#undef protected +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_dm_discovery_manager.cpp b/test/unittest/UTTest_dm_discovery_manager.cpp new file mode 100644 index 000000000..c8e89ae0a --- /dev/null +++ b/test/unittest/UTTest_dm_discovery_manager.cpp @@ -0,0 +1,252 @@ +/* + * 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 +#include + +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "ipc_server_listener.h" +#include "device_manager_service_listener.h" +#include "UTTest_dm_discovery_manager.h" +#include "discovery_service.h" + +namespace OHOS { +namespace DistributedHardware { + +void DmDiscoveryManagerTest::SetUp() { +} + +void DmDiscoveryManagerTest::TearDown() { +} + +void DmDiscoveryManagerTest::SetUpTestCase() { +} + +void DmDiscoveryManagerTest::TearDownTestCase() { +} + +namespace +{ +std::shared_ptr softbusConnector_ = std::make_shared(); +std::shared_ptr listener_ = std::make_shared(); +std::shared_ptr discoveryMgr_ = std::make_shared(softbusConnector_, listener_); + +/** + * @tc.name: DmDiscoveryManager_001 + * @tc.desc: Test whether the DmDiscoveryManager function can generate a new pointer + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, DmDiscoveryManager_001, testing::ext::TestSize.Level0) { + std::shared_ptr Test = std::make_shared(softbusConnector_, listener_); + ASSERT_NE(Test, nullptr); +} + +/** + * @tc.name: DmDiscoveryManager_002 + * @tc.desc: Test whether the DmDiscoveryManager function can delete a new pointer + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, DmDiscoveryManager_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr Test = std::make_shared(softbusConnector_, listener_); + Test.reset(); + EXPECT_EQ(Test, nullptr); +} + +/** + * @tc.name:StartDeviceDiscovery_001 + * @tc.desc: keeping pkgame unchanged, call StartDeviceDiscovery twice so that its discoveryQueue is not empty and return DM_DISCOVERY_REPEATED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + DmSubscribeInfo subscribeInfo; + const std::string extra; + discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + EXPECT_EQ (ret, DM_DISCOVERY_REPEATED); +} + +/** + * @tc.name:StartDeviceDiscovery_002 + * @tc.desc: pkgame changed, call StartDeviceDiscovery twice so that its discoveryQueue is not empty and return DM_DISCOVERY_REPEATED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + std::string extra; + DmSubscribeInfo subscribeInfo; + discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + pkgName = "com.ohos.helloworld.new"; + int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + ASSERT_EQ(ret, DM_DISCOVERY_FAILED); +} + +/** + * @tc.name:StopDeviceDiscovery_001 + * @tc.desc: Assign the correct value + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +//doing +HWTEST_F(DmDiscoveryManagerTest, StopDeviceDiscovery_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + const std::string extra; + DmSubscribeInfo subscribeInfo; + uint16_t subscribeId = 1; + discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + int ret = discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); + ASSERT_NE(ret, DM_OK); +} + +/** + * @tc.name: OnDeviceFound_001 + * @tc.desc: The OnDeviceFound function does the correct case and assigns pkgName + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, OnDeviceFound_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + uint16_t aaa = 11; + DmDiscoveryContext context{pkgName, "121110", aaa}; + discoveryMgr_->discoveryContextMap_[pkgName] = context; + sleep(1); + DmDeviceInfo info; + info.deviceId[0] = '\0'; + info.deviceName[0] = '\0'; + discoveryMgr_->OnDeviceFound(pkgName, info); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + int ret1 = discoveryMgr_->discoveryContextMap_.count(pkgName); + EXPECT_EQ (ret1, 1); + std ::string ret = pReq->GetPkgName(); + EXPECT_EQ (ret,pkgName); +} + +/** + * @tc.name: OnDeviceFound_002 + * @tc.desc: set pkgName not null and discoveryContextMap_ null and return + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + DmDeviceInfo info; + discoveryMgr_->OnDeviceFound(pkgName, info); + int ret1 = discoveryMgr_->discoveryContextMap_.count(pkgName); + EXPECT_EQ (ret1, 1); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + std ::string ret = pReq->GetPkgName(); + EXPECT_EQ (ret, pkgName); +} + +/** + * @tc.name: OnDiscoveryFailed_001 + * @tc.desc: The OnDeviceFound function takes the wrong case and emptying pkgName + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, OnDiscoveryFailed_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + int32_t subscribeId = 1; + int32_t failedReason = 3; + discoveryMgr_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + std ::string ret = pReq->GetPkgName(); + EXPECT_EQ (ret, pkgName); +} + +/** + * @tc.name: OnDiscoveryFailed_002 + * @tc.desc: The OnDeviceFound function takes the wrong case and emptying pkgName + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, OnDiscoveryFailed_002, testing::ext::TestSize.Level0) { + std::string pkgName; + int32_t subscribeId = 1; + int32_t failedReason = 3; + discoveryMgr_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); + int ret1 = discoveryMgr_->discoveryContextMap_.count(pkgName); + EXPECT_EQ (ret1, 0); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + std ::string ret = pReq->GetPkgName(); + EXPECT_EQ (ret, pkgName); +} + +/** + * @tc.name: OnDiscoverySuccess_001 + * @tc.desc: The OnDeviceFound function takes the wrong case and return pkgName + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, OnDiscoverySuccess_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + int32_t subscribeId = 1; + discoveryMgr_->OnDiscoverySuccess(pkgName, subscribeId); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + std ::string ret = pReq->GetPkgName(); + EXPECT_EQ (ret, pkgName); +} + +/** + * @tc.name: OnDiscoverySuccess_002 + * @tc.desc: set pkgName null and return discoveryContextMap_ null and return pkgName(null) + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, OnDiscoverySuccess_002, testing::ext::TestSize.Level0) +{ + std::string pkgName ; + int32_t subscribeId = 1; + discoveryMgr_->OnDiscoverySuccess(pkgName, subscribeId); + int ret1 = discoveryMgr_->discoveryContextMap_.count(pkgName); + EXPECT_EQ (ret1, 1); + std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + std ::string ret = pReq->GetPkgName(); + EXPECT_EQ (ret, pkgName); +} + +/** + * @tc.name: HandleDiscoveryTimeout_001 + * @tc.desc: set pkgName not null and return 1(true) + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmDiscoveryManagerTest, HandleDiscoveryTimeout_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + discoveryMgr_->HandleDiscoveryTimeout() ; + int ret = discoveryMgr_->discoveryContextMap_.count(pkgName); + EXPECT_EQ (ret, 1); +} +} +} +} + + diff --git a/test/unittest/UTTest_dm_discovery_manager.h b/test/unittest/UTTest_dm_discovery_manager.h new file mode 100644 index 000000000..44a25e2b0 --- /dev/null +++ b/test/unittest/UTTest_dm_discovery_manager.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_UTTEST_DM_DISCOVERY_MANAGER_H +#define OHOS_UTTEST_DM_DISCOVERY_MANAGER_H +#include +#include +#include + +#include "softbus_connector.h" +#include "device_manager_service_listener.h" +#include "dm_discovery_manager.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_discover_result_req.h" + +#define private public +namespace OHOS +{ +namespace DistributedHardware +{ +class DmDiscoveryManagerTest : public testing::Test +{ +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} +} +#endif // OHOS_UTTEST_DM_DISCOVERY_MANAGER_H \ No newline at end of file diff --git a/test/unittest/UTTest_hichain_connector.cpp b/test/unittest/UTTest_hichain_connector.cpp new file mode 100644 index 000000000..db28b4607 --- /dev/null +++ b/test/unittest/UTTest_hichain_connector.cpp @@ -0,0 +1,490 @@ +/* + * 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 +#include +#include + +#include "parameter.h" +#include "dm_anonymous.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_random.h" +#include "UTTest_hichain_connector.h" +#include "hichain_connector.h" + +namespace OHOS +{ +namespace DistributedHardware +{ +void HichainConnectorTest::SetUp() +{ +} +void HichainConnectorTest::TearDown() +{ +} +void HichainConnectorTest::SetUpTestCase() +{ +} +void HichainConnectorTest::TearDownTestCase() +{ +} +namespace { +/** + * @tc.name: CreateGroup_001 + * @tc.desc: Set the deviceGroupManager_ pointer to CreateGroup to NULlptr and return DM_INVALID_VALUE + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, CreateGroup_001, testing::ext::TestSize.Level0) +{ + int64_t requestId = 123456; + std::string groupName = "dfggg"; + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector-> deviceGroupManager_ = nullptr; + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_INVALID_VALUE); +} + +/** + * @tc.name: CreateGroup_002 + * @tc.desc: Set CreateGroup to the correct process and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, CreateGroup_002, testing::ext::TestSize.Level0) +{ + int64_t requestId = 123456; + std::string groupName = "uuiioo"; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetGroupInfo_001 + * @tc.desc: set groupName not null and return false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetGroupInfo_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr hichainConnector = std::make_shared(); + std::string groupName = "dcdkdkd1"; + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); + std::string queryParams = jsonObj.dump(); + std::vector groupList; + int ret = hichainConnector->GetGroupInfo(queryParams, groupList); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: GetGroupInfo_003 + * @tc.desc: set groupName nou null groupListot null and return 0 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetGroupInfo_003, testing::ext::TestSize.Level0) +{ + std::string groupName = "lcdkddkd1 "; + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); + std::string queryParams = jsonObj.dump(); + GroupInfo aa; + aa.groupName = "afa"; + std::vector groupList; + groupList.push_back(aa); + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GetGroupInfo(queryParams, groupList); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: IsGroupInfoInvalid_001 + * @tc.desc: GroupType is GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP, group.groupVisibility is not GROUP_VISIBILITY_PUBLIC. + Group.return true + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ + +HWTEST_F(HichainConnectorTest, IsGroupInfoInvalid_001, testing::ext::TestSize.Level0) +{ + GroupInfo group; + group.groupName = "dkdkkdkdk"; + group.groupId = 1; + group.groupOwner = "ohos.distributedhardware.devicemanager"; + group.groupType = 7; + group.groupVisibility = 1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: IsGroupInfoInvalid_002 + * @tc.desc: GroupType is GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP, group.groupVisibility is GROUP_VISIBILITY_PUBLIC, + Grou. groupOwner is not equal to DM_PKG_NAME. The value is true + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, IsGroupInfoInvalid_002, testing::ext::TestSize.Level0) +{ + GroupInfo group; + group.groupName = "test"; + group.groupId = 1; + group.groupOwner = "ohos.disware"; + group.groupType = 1; + group.groupVisibility = -1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: DelMemberFromGroup_001 + * @tc.desc:set groupId, deviceId null and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, DelMemberFromGroup_001, testing::ext::TestSize.Level0) +{ + std::string groupId ; + std::string deviceId; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DelMemberFromGroup_002 + * @tc.desc: The groupId "34451"; The deviceId = "123"; Can be deleted correctly + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, DelMemberFromGroup_002, testing::ext::TestSize.Level0) +{ + std::string groupId = "34451"; + std::string deviceId = "123"; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GenRequestId_001 + * @tc.desc:Call the GenRequestId function + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GenRequestId_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GenRequestId(); + ASSERT_NE(ret, 0); +} + +/** + * @tc.name: from_json_001 + * @tc.desc: Pass in arguments to the from_JSON function and convert it to the correct value + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, from_json_001, testing::ext::TestSize.Level0) +{ + GroupInfo groupInfo; + groupInfo.groupName = "aaaa"; + groupInfo.groupId = "345678"; + groupInfo.groupOwner = "lllll"; + groupInfo.groupType = 5; + groupInfo.groupVisibility = 5; + nlohmann::json jsonObject; + jsonObject[FIELD_GROUP_NAME] = groupInfo.groupName; + jsonObject[FIELD_GROUP_ID] = groupInfo.groupId ; + jsonObject[ FIELD_GROUP_OWNER] = groupInfo.groupOwner; + jsonObject[ FIELD_GROUP_TYPE] = groupInfo.groupType; + jsonObject[FIELD_GROUP_VISIBILITY] = groupInfo.groupVisibility; + from_json(jsonObject, groupInfo); + EXPECT_EQ(groupInfo.groupName, "aaaa"); + EXPECT_EQ(groupInfo.groupId, "345678"); + EXPECT_EQ(groupInfo.groupOwner, "lllll"); + EXPECT_EQ(groupInfo.groupType, 5); + EXPECT_EQ(groupInfo.groupVisibility, 5); +} + +/** + * @tc.name: HiChainConnector_001 + * @tc.desc: Returns a new pointer to the HiChainConnector constructor new + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, HiChainConnector_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr m_HiChainConnector = std::make_shared(); + ASSERT_NE(m_HiChainConnector, nullptr); +} + +/** + * @tc.name: HiChainConnector_002 + * @tc.desc: Give the HiChainConnector constructor new a new pointer and delete it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, HiChainConnector_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr m_HiChainConnector = std::make_shared(); + m_HiChainConnector.reset(); + EXPECT_EQ(m_HiChainConnector, nullptr); +} + +/** + * @tc.name:RegisterHiChainCallback_001 + * @tc.desc: Call the RegisterHiChainCallback function with a return value of DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, RegisterHiChainCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.softbus.test"; + std::shared_ptr listener_ = std::make_shared(); + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr discoveryMgr_ = std::make_shared(softbusConnector, listener_); + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->RegisterHiChainCallback(pkgName, std::shared_ptr(discoveryMgr_)); + int ret1 = HiChainConnector:: hiChainConnectorCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 1); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: IsGroupCreated_001 + * @tc.desc: Call the RegisterHiChainCallback function with a return value of DM_OK + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, IsGroupCreated_001, testing::ext::TestSize.Level0) +{ + std::string groupName = "dcdkdkd1"; + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); + std::string queryParams = jsonObj.dump(); + std::vector groupList ; + GroupInfo groupInfo; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupCreated( groupName, groupInfo); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: AddMember_001 + * @tc.desc: set deviceGroupManager_ = nullptr; + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, AddMember_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->deviceGroupManager_ = nullptr; + std::string deviceId ; + std::string connectInfo; + int ret = hichainConnector->AddMember(deviceId, connectInfo); + EXPECT_EQ(ret, -1); +} + +/** + * @tc.name: AddMember_002 + * @tc.desc: set deviceId and connectInfo = null; + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, AddMember_002, testing::ext::TestSize.Level0) +{ + std::string deviceId; + std::string connectInfo; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->AddMember(deviceId, connectInfo); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: AddMember_002 + * @tc.desc: set deviceId and connectInfo = null; + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, AddMember3, testing::ext::TestSize.Level0) +{ + std::string deviceId = "123456"; + std::string connectInfo = "dkdkk"; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->AddMember(deviceId, connectInfo); + ASSERT_GE(ret, 1); +} + +/** + * @tc.name: onRequest_001 + * @tc.desc:set operationCode != GroupOperationCode::MEMBER_JOIN(3); return nullptr ; + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, onRequest_001, testing::ext::TestSize.Level0) +{ + int64_t requestId = 2; + int32_t operationCode = 2; + char *reqParams; + std::shared_ptr hichainConnector = std::make_shared(); + char *ret = hichainConnector->onRequest(requestId, operationCode, reqParams); + EXPECT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetConnectPara_001 + * @tc.desc: set para not null and go to the second master + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetConnectPara_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "softbus"; + std::shared_ptr listener_ = std::make_shared(); + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr discoveryMgr_ = std::make_shared(softbusConnector, listener_); + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(pkgName, std::shared_ptr(discoveryMgr_)); + std::string deviceId = "23445"; + std::string reqDeviceId = "234566"; + std::string p; + std::string ret = hichainConnector->GetConnectPara(deviceId, reqDeviceId); + EXPECT_EQ(ret, p); +} + +/** + * @tc.name: GetConnectPara_002 + * @tc.desc:Empty deviceId so that jsonObject.is_discarded is null and the value of connectAddr is returned + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetConnectPara_002, testing::ext::TestSize.Level0) +{ + std::string deviceId; + std::string reqDeviceId = "234566"; + std::string pkgName = "softbus"; + std::shared_ptr listener_ = std::make_shared(); + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr discoveryMgr_ = std::make_shared(softbusConnector, listener_); + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(pkgName, std::shared_ptr(discoveryMgr_)); + std::string ret = hichainConnector->GetConnectPara(deviceId, reqDeviceId); + EXPECT_EQ(ret,""); +} + +/** + * @tc.name: DeleteGroup_001 + * @tc.desc: set groupId = "34567",and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, DeleteGroup_001, testing::ext::TestSize.Level0) +{ + std::string groupId = "34567"; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->DeleteGroup(groupId); + EXPECT_EQ(ret,DM_OK); +} + +/** + * @tc.name: GetRelatedGroups_001 + * @tc.desc: set DeviceId 123 groupList null and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetRelatedGroups_001, testing::ext::TestSize.Level0) +{ + std::string DeviceId = "123"; + std::vector groupList; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GetRelatedGroups(DeviceId, groupList); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: GetRelatedGroups_003 + * @tc.desc: set DeviceId = 12345,groupList null and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetRelatedGroups_003, testing::ext::TestSize.Level0) +{ + std::string DeviceId = "12345"; + std::vector groupList; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GetRelatedGroups(DeviceId, groupList); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: SyncGroups_001 + * @tc.desc: set deviceId = "34567",and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, SyncGroups_001, testing::ext::TestSize.Level0) +{ + std::string deviceId = "34567"; + std::vector remoteGroupIdList; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->SyncGroups(deviceId, remoteGroupIdList); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetSyncGroupList_001 + * @tc.desc: set groupList null,and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetSyncGroupList_001, testing::ext::TestSize.Level0) +{ + std::vector groupList; + std::vector syncGroupList; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GetSyncGroupList(groupList, syncGroupList); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: GetSyncGroupList_002 + * @tc.desc: set groupList not null,and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetSyncGroupList_002, testing::ext::TestSize.Level0) +{ + std::vector groupList; + GroupInfo groupList1; + groupList1.groupName = "hichainconnector"; + groupList1.groupId = "123456"; + groupList1.groupOwner ="doftbus"; + groupList1.groupType = 1; + groupList1.groupVisibility = 2; + groupList.push_back(groupList1); + std::vector syncGroupList; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GetSyncGroupList(groupList, syncGroupList); + EXPECT_EQ(ret, DM_OK); +} +} +} +} + diff --git a/test/unittest/UTTest_hichain_connector.h b/test/unittest/UTTest_hichain_connector.h new file mode 100644 index 000000000..29b1ac99d --- /dev/null +++ b/test/unittest/UTTest_hichain_connector.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_UTTEST_HICHAIN_CONNECTOR_H +#define OHOS_UTTEST_HICHAIN_CONNECTOR_H + +#include +#include +#include +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +#include "device_auth.h" +#include "single_instance.h" +#include "hichain_connector_callback.h" +#include "device_manager_service_listener.h" +#include "dm_auth_manager.h" +#include "dm_device_state_manager.h" +#include "hichain_connector.h" + +namespace OHOS +{ +namespace DistributedHardware +{ +class HichainConnectorTest : public testing::Test +{ +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} +} +#undef private +#undef protected +#endif // OHOS_HICHAIN_CONNECTOR_H diff --git a/test/unittest/UTTest_softbus_connector.cpp b/test/unittest/UTTest_softbus_connector.cpp new file mode 100644 index 000000000..df6a4f61a --- /dev/null +++ b/test/unittest/UTTest_softbus_connector.cpp @@ -0,0 +1,447 @@ +/* + * 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 "UTTest_softbus_connector.h" + +#include +#include + +#include +#include + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "parameter.h" +#include "softbus_connector.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +void SoftbusConnectorTest::SetUp() +{ +} +void SoftbusConnectorTest::TearDown() +{ +} +void SoftbusConnectorTest::SetUpTestCase() +{ +} +void SoftbusConnectorTest::TearDownTestCase() +{ +} + +namespace { +static std::shared_ptr softbusConnector = std::make_shared(); +/** + * @tc.name: Init_001 + * @tc.desc: go tothe corrort case and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, Init_001, testing::ext::TestSize.Level0) +{ + int ret = softbusConnector->Init(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: RegisterSoftbusDiscoveryCallback_001 + * @tc.desc: set pkgName = "com.ohos.helloworld";call RegisterSoftbusDiscoveryCallback function to corrort ,return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, RegisterSoftbusDiscoveryCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + std::shared_ptr listener_ = std::make_shared(); + std::shared_ptr discoveryMgr_ = + std::make_shared(softbusConnector, listener_); + int ret = softbusConnector->RegisterSoftbusDiscoveryCallback( + pkgName, std::shared_ptr(discoveryMgr_)); + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 1); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnRegisterSoftbusDiscoveryCallback_001 + * @tc.desc: set pkgName = "com.ohos.helloworld";call UnRegisterSoftbusDiscoveryCallback function to corrort ,return + * DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusDiscoveryCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 0); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnRegisterSoftbusStateCallback_001 + * @tc.desc: set pkgName = "com.ohos.helloworld";call UnRegisterSoftbusStateCallback function to corrort ,return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusStateCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + int ret = softbusConnector->UnRegisterSoftbusStateCallback(pkgName); + int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 0); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetTrustedDeviceList_001 + * @tc.desc: create GetAllNodeDeviceInfo not equal 0, and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetTrustedDeviceList_001, testing::ext::TestSize.Level0) +{ + std::vector deviceInfoList; + int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetLocalDeviceInfo_001 + * @tc.desc: set pkgName to com.softbus.test,define deviceInfo,and return DM_OK. + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.softbus.test"; + DmDeviceInfo deviceInfo; + int ret = softbusConnector->GetLocalDeviceInfo(deviceInfo); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: StartDiscovery_001 + * @tc.desc: get StartDiscovery to wroing master and return DM_DISCOVERY_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0) +{ + DmSubscribeInfo dmSubscribeInfo; + int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); + EXPECT_EQ(ret, DM_DISCOVERY_FAILED); +} + +/** + * @tc.name: IsDeviceOnLine_001 + * @tc.desc: set deviceId = "12333";,and return false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_001, testing::ext::TestSize.Level0) +{ + std::string deviceId = "12333"; + bool ret = softbusConnector->IsDeviceOnLine(deviceId); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: IsDeviceOnLine_002 + * @tc.desc: + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "145677"; + NodeBasicInfo Info; + strncpy(Info.networkId, "145677", sizeof(Info.networkId)); + bool ret = softbusConnector->IsDeviceOnLine(deviceId); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: SoftbusConnector_001 + * @tc.desc: set SoftbusConnector to new a pointer ,and the pointer nou equal nullptr + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, SoftbusConnector_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr m_SoftbusConnector = std::make_shared(); + ASSERT_NE(m_SoftbusConnector, nullptr); +} + +/** + * @tc.name: SoftbusConnector_002 + * @tc.desc: set SoftbusConnector to new a pointer ,and the pointer nou equal nullptr,and delete it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, SoftbusConnector_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr m_SoftbusConnector = std::make_shared(); + m_SoftbusConnector.reset(); + EXPECT_EQ(m_SoftbusConnector, nullptr); +} + +/** + * @tc.name: GetConnectionIpAddress_001 + * @tc.desc: set deviceId null,adb return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_001, testing::ext::TestSize.Level0) +{ + std::string deviceId; + std::string ipAddress = "123456"; + int ret = softbusConnector->GetConnectionIpAddress(deviceId, ipAddress); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: GetConnectionIpAddress_002 + * @tc.desc: set some corrort para,and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "213456"; + std::string ipAddress = "123456"; + int ret = softbusConnector->GetConnectionIpAddress(deviceId, ipAddress); + EXPECT_EQ(ret, DM_FAILED); +} +/** + * @tc.name: GetConnectionIpAddress_003 + * @tc.desc: set deviceInfo.addrNum = -1;go to second master and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_003, testing::ext::TestSize.Level0) +{ + DeviceInfo deviceInfo; + deviceInfo.addrNum = -1; + std::string ipAddress; + std::string deviceId = "3338848"; + int ret = softbusConnector->GetConnectionIpAddress(deviceId, ipAddress); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: GetConnectAddrByType_001 + * @tc.desc: set deviceInfo'pointer null, go to first master,and return nullptr + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetConnectAddrByType_001, testing::ext::TestSize.Level0) +{ + ConnectionAddrType type; + type = CONNECTION_ADDR_MAX; + ConnectionAddr *p = nullptr; + ConnectionAddr *ret = softbusConnector->GetConnectAddrByType(nullptr, type); + EXPECT_EQ(p, ret); +} + +/** + * @tc.name: GetConnectAddrByType_002 + * @tc.desc:set deviceInfo to some corrort para,and return nullptr + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetConnectAddrByType_002, testing::ext::TestSize.Level0) +{ + DeviceInfo deviceInfo; + deviceInfo.addrNum = 1; + ConnectionAddrType type; + type = CONNECTION_ADDR_BR; + ConnectionAddr *p = nullptr; + ConnectionAddr *ret = softbusConnector->GetConnectAddrByType(&deviceInfo, type); + EXPECT_EQ(ret, p); +} + +/** + * @tc.name: GetConnectAddr_001 + * @tc.desc: set deviceId to null,and return nullptr + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetConnectAddr_001, testing::ext::TestSize.Level0) +{ + std::string deviceId; + std::string connectAddr; + ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + EXPECT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetConnectAddr_002 + * @tc.desc:set deviceId nit null set deviceInfo.addrNum = -1; and return nullptr + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, GetConnectAddr_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "123345"; + std::string connectAddr; + DeviceInfo deviceInfo; + deviceInfo.addrNum = -1; + ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + EXPECT_EQ(ret, nullptr); +} + +/** + * @tc.name: CovertNodeBasicInfoToDmDevice_001 + * @tc.desc: go to the corrort case and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, CovertNodeBasicInfoToDmDevice_001, testing::ext::TestSize.Level0) +{ + NodeBasicInfo nodeBasicInfo; + DmDeviceInfo dmDeviceInfo; + int ret = softbusConnector->CovertNodeBasicInfoToDmDevice(nodeBasicInfo, dmDeviceInfo); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnPublishSuccess_001 + * @tc.desc: go to the corrort case and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnPublishSuccess_001, testing::ext::TestSize.Level0) +{ + int32_t publishId = 0; + int ret = softbusConnector->OnPublishSuccess(publishId); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnPublishSuccess_001 + * @tc.desc: go to the corrort case and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnPublishFail1, testing::ext::TestSize.Level0) +{ + int32_t publishId = 0; + PublishFailReason reason; + reason = PUBLISH_FAIL_REASON_NOT_SUPPORT_MEDIUM; + int ret = softbusConnector->OnPublishFail(publishId, reason); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnSoftBusDeviceOnline_001 + * @tc.desc: set info to some corrort parp. and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnSoftBusDeviceOnline_001, testing::ext::TestSize.Level0) +{ + NodeBasicInfo info; + int ret = softbusConnector->OnSoftBusDeviceOnline(&info); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnSoftbusDeviceOffline_001 + * @tc.desc: set info to some corrort parp. and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceOffline_001, testing::ext::TestSize.Level0) +{ + NodeBasicInfo info; + int ret = softbusConnector->OnSoftbusDeviceOffline(&info); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnSoftbusDeviceInfoChanged_001 + * @tc.desc: go to the corrort case and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceInfoChanged_001, testing::ext::TestSize.Level0) +{ + NodeBasicInfo info; + NodeBasicInfoType type; + type = TYPE_NETWORK_ID; + int ret = softbusConnector->OnSoftbusDeviceInfoChanged(type, &info); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnSoftbusDeviceFound_001 + * @tc.desc: set device some corrort para and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceFound_001, testing::ext::TestSize.Level0) +{ + DeviceInfo device; + int ret = softbusConnector->OnSoftbusDeviceFound(&device); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnSoftbusDiscoveryFailed_001 + * @tc.desc: set some corrort para and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnSoftbusDiscoveryFailed_001, testing::ext::TestSize.Level0) +{ + int32_t subscribeId = 0; + DiscoveryFailReason failReason; + failReason = DISCOVERY_FAIL_REASON_NOT_SUPPORT_MEDIUM; + int ret = softbusConnector->OnSoftbusDiscoveryFailed(subscribeId, failReason); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnSoftbusDiscoverySuccess_001 + * @tc.desc: set some corrort para and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnSoftbusDiscoverySuccess_001, testing::ext::TestSize.Level0) +{ + int32_t subscribeId = 0; + int ret = softbusConnector->OnSoftbusDiscoverySuccess(subscribeId); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnParameterChgCallback_001 + * @tc.desc: set some corrort para and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusConnectorTest, OnParameterChgCallback_001, testing::ext::TestSize.Level0) +{ + char *key; + char *value; + void *context = nullptr; + int ret = softbusConnector->OnParameterChgCallback(key, value, context); + EXPECT_EQ(ret, DM_OK); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_softbus_connector.h b/test/unittest/UTTest_softbus_connector.h new file mode 100644 index 000000000..03857486c --- /dev/null +++ b/test/unittest/UTTest_softbus_connector.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_UTTest_DM_SOFTBUS_CONNECTOR_H +#define OHOS_UTTest_DM_SOFTBUS_CONNECTOR_H + +#define private public // hack complier +#define protected public + +#include +#include + +#include +#include +#include +#include +#include + +#include "device_manager_service_listener.h" +#include "discovery_service.h" +#include "dm_device_info.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "dm_subscribe_info.h" +#include "softbus_bus_center.h" +#include "softbus_connector.h" +#include "softbus_discovery_callback.h" +#include "softbus_session.h" +#include "softbus_state_callback.h" +namespace OHOS { +namespace DistributedHardware { + +class SoftbusConnectorTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#undef private +#undef protected +#endif diff --git a/test/unittest/UTTest_softbus_session.cpp b/test/unittest/UTTest_softbus_session.cpp new file mode 100644 index 000000000..0be9cf6d1 --- /dev/null +++ b/test/unittest/UTTest_softbus_session.cpp @@ -0,0 +1,209 @@ +/* + * 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 "UTTest_softbus_session.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +void SoftbusSessionTest::SetUp() +{ +} +void SoftbusSessionTest::TearDown() +{ +} +void SoftbusSessionTest::SetUpTestCase() +{ +} +void SoftbusSessionTest::TearDownTestCase() +{ +} + +namespace { + +std::shared_ptr softbusSession = std::make_shared(); + +/** + * @tc.name: OpenAuthSession_001 + * @tc.desc: set deviceId =null, return sessionId(1) + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, OpenAuthSession_001, testing::ext::TestSize.Level0) +{ + std::string deviceId = ""; + int ret = softbusSession->OpenAuthSession(deviceId); + EXPECT_EQ(ret, -1); +} + +/** + * @tc.name: OpenAuthSession_002 + * @tc.desc: set deviceId = "123456";and return sessionId + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, OpenAuthSession_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "123456"; + int ret = softbusSession->OpenAuthSession(deviceId); + EXPECT_EQ(ret, -1); +} + +/** + * @tc.name: SendData_001 + * @tc.desc: set message null and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, SendData_001, testing::ext::TestSize.Level0) +{ + std::string message = ""; + int32_t sessionId = -1; + int ret = softbusSession->SendData(sessionId, message); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: SendData_002 + * @tc.desc: set sessionId = 0 ,go to the SendBytes'smaster and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) +{ + int32_t msgType = 2; + nlohmann::json jsonObj; + jsonObj[TAG_VER] = DM_ITF_VER; + jsonObj[TAG_TYPE] = msgType; + std::string message = jsonObj.dump(); + int32_t sessionId = 0; + int ret = softbusSession->SendData(sessionId, message); + EXPECT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: OnSessionOpened_001 + * @tc.desc: set result = 0,sessionId = -1;and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level0) +{ + int result = 0; + int32_t sessionId = -1; + int ret = softbusSession->OnSessionOpened(sessionId, result); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SoftbusSession_001 + * @tc.desc: set SoftbusSession to make a new pointer ,and it not nullptr + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, SoftbusSession_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr m_SoftbusSession = std::make_shared(); + ASSERT_NE(m_SoftbusSession, nullptr); +} + +/** + * @tc.name: SoftbusSession_002 + * @tc.desc: set SoftbusSession to make a new pointer , it not nullptr and delete it + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, SoftbusSession_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr m_SoftbusSession = std::make_shared(); + m_SoftbusSession.reset(); + EXPECT_EQ(m_SoftbusSession, nullptr); +} + +/** + * @tc.name: OnSessionClosed_001 + * @tc.desc: set some corrort para,and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, OnSessionClosed_001, testing::ext::TestSize.Level0) +{ + int32_t sessionId = 3; + int ret = softbusSession->OnSessionClosed(sessionId); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: OnBytesReceived_002 + * @tc.desc: set sessionId = 3 and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, OnBytesReceived_002, testing::ext::TestSize.Level0) +{ + int32_t sessionId = 3; + void *data; + uint32_t dataLen = 1; + int ret = softbusSession->OnBytesReceived(sessionId, data, dataLen); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: CloseAuthSession_001 + * @tc.desc: set sessionId = 3, and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, CloseAuthSession_001, testing::ext::TestSize.Level0) +{ + int32_t sessionId = 3; + int ret = softbusSession->CloseAuthSession(sessionId); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetPeerDeviceId_001 + * @tc.desc: set sessionId = 3 and return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, GetPeerDeviceId_001, testing::ext::TestSize.Level0) +{ + int32_t sessionId = 3; + std::string peerDevId; + int ret = softbusSession->GetPeerDeviceId(sessionId, peerDevId); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnRegisterSessionCallback_001 + * @tc.desc: set info to null and return DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusSessionTest, UnRegisterSessionCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "softbus"; + int ret = softbusSession->UnRegisterSessionCallback(pkgName); + EXPECT_EQ(ret, DM_OK); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_softbus_session.h b/test/unittest/UTTest_softbus_session.h new file mode 100644 index 000000000..41998d6f6 --- /dev/null +++ b/test/unittest/UTTest_softbus_session.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_UTTest_DM_SOFTBUS_SESSION_H +#define OHOS_UTTest_DM_SOFTBUS_SESSION_H + +#include +#include + +#include +#include +#include +#include +#include + +#include "device_manager_service_listener.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "inner_session.h" +#include "session.h" +#include "softbus_session.h" +#include "softbus_session_callback.h" + +namespace OHOS { +namespace DistributedHardware { + +class SoftbusSessionTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#undef private +#undef protected +#endif \ No newline at end of file diff --git a/test/unittest/auth_request_state.cpp b/test/unittest/auth_request_state.cpp new file mode 100644 index 000000000..bab92c0b1 --- /dev/null +++ b/test/unittest/auth_request_state.cpp @@ -0,0 +1,192 @@ +/* + * 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 "auth_request_state.h" + +#include "dm_auth_manager.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t AuthRequestState::Leave() +{ + return DM_OK; +} + +int32_t AuthRequestState::SetAuthManager(std::shared_ptr authManager) +{ + authManager_ = std::move(authManager); + return DM_OK; +} + +int32_t AuthRequestState::SetAuthContext(std::shared_ptr context) +{ + context_ = std::move(context); + return DM_OK; +} + +std::shared_ptr AuthRequestState::GetAuthContext() +{ + return context_; +} + +int32_t AuthRequestState::TransitionTo(std::shared_ptr state) +{ + LOGE("AuthRequestState::TransitionTo"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + state->SetAuthManager(stateAuthManager); + stateAuthManager->SetAuthRequestState(state); + state->SetAuthContext(context_); + this->Leave(); + state->Enter(); + return DM_OK; +} + +int32_t AuthRequestInitState::GetStateType() +{ + return AuthState::AUTH_REQUEST_INIT; +} + +int32_t AuthRequestInitState::Enter() +{ + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->EstablishAuthChannel(context_->deviceId); + return DM_OK; +} + +int32_t AuthRequestNegotiateState::GetStateType() +{ + return AuthState::AUTH_REQUEST_NEGOTIATE; +} + +int32_t AuthRequestNegotiateState::Enter() +{ + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->StartNegotiate(context_->sessionId); + return DM_OK; +} + +int32_t AuthRequestNegotiateDoneState::GetStateType() +{ + return AuthState::AUTH_REQUEST_NEGOTIATE_DONE; +} + +int32_t AuthRequestNegotiateDoneState::Enter() +{ + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->SendAuthRequest(context_->sessionId); + return DM_OK; +} + +int32_t AuthRequestReplyState::GetStateType() +{ + return AuthState::AUTH_REQUEST_REPLY; +} + +int32_t AuthRequestReplyState::Enter() +{ + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->StartRespAuthProcess(); + return DM_OK; +} + +int32_t AuthRequestInputState::GetStateType() +{ + return AuthState::AUTH_REQUEST_INPUT; +} + +int32_t AuthRequestInputState::Enter() +{ + LOGE("DmAuthManager::AuthRequestInputState"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->ShowStartAuthDialog(); + return DM_OK; +} + +int32_t AuthRequestJoinState::GetStateType() +{ + return AuthState::AUTH_REQUEST_JOIN; +} + +int32_t AuthRequestJoinState::Enter() +{ + LOGE("DmAuthManager::AuthRequestJoinState"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->AddMember(context_->deviceId); + return DM_OK; +} + +int32_t AuthRequestNetworkState::GetStateType() +{ + return AuthState::AUTH_REQUEST_NETWORK; +} + +int32_t AuthRequestNetworkState::Enter() +{ + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->JoinNetwork(); + return DM_OK; +} + +int32_t AuthRequestFinishState::GetStateType() +{ + return AuthState::AUTH_REQUEST_FINISH; +} + +int32_t AuthRequestFinishState::Enter() +{ + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->AuthenticateFinish(); + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/device_manager_impl_test.cpp b/test/unittest/device_manager_impl_test.cpp new file mode 100644 index 000000000..e44c6bb6c --- /dev/null +++ b/test/unittest/device_manager_impl_test.cpp @@ -0,0 +1,192 @@ +/* + * 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_impl_test.h" + +#include + +#include "dm_constants.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +void DeviceManagerImplTest::SetUp() +{ +} + +void DeviceManagerImplTest::TearDown() +{ +} + +void DeviceManagerImplTest::SetUpTestCase() +{ +} + +void DeviceManagerImplTest::TearDownTestCase() +{ +} + +namespace { +HWTEST_F(DeviceManagerImplTest, InitDeviceManager, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, nullptr); + ASSERT_EQ(ret, DM_INVALID_VALUE); +} + +HWTEST_F(DeviceManagerImplTest, AuthenticateDevice1, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + DmDeviceInfo dmDeviceInfo; + DmAppImageInfo dmAppImageInfo; + std::string extra = ""; + std::shared_ptr callback = nullptr; + int32_t ret = + DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, dmAppImageInfo, extra, callback); + ASSERT_EQ(ret, DM_INVALID_VALUE); +} + +HWTEST_F(DeviceManagerImplTest, AuthenticateDevice2, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.helloworld"; + DmDeviceInfo dmDeviceInfo; + DmAppImageInfo dmAppImageInfo; + std::string extra = ""; + std::shared_ptr callback = nullptr; + std::shared_ptr mockInstance = std::make_shared(); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_FAILED)); + int32_t ret = + DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, dmAppImageInfo, extra, callback); + ASSERT_EQ(ret, DM_IPC_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; +} + +HWTEST_F(DeviceManagerImplTest, AuthenticateDevice3, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.helloworld"; + DmDeviceInfo dmDeviceInfo; + DmAppImageInfo dmAppImageInfo; + std::string extra = ""; + std::shared_ptr callback = nullptr; + std::shared_ptr mockInstance = std::make_shared(); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_OK)); + int32_t ret = + DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, dmAppImageInfo, extra, callback); + ASSERT_EQ(ret, DM_OK); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; +} + +HWTEST_F(DeviceManagerImplTest, CheckAuthentication1, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::string authPara = ""; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); + ASSERT_EQ(ret, DM_INVALID_VALUE); +} + +HWTEST_F(DeviceManagerImplTest, CheckAuthentication2, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.helloworld"; + std::string authPara = ""; + std::shared_ptr callback = nullptr; + std::shared_ptr mockInstance = std::make_shared(); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_FAILED)); + int32_t ret = DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); + ASSERT_EQ(ret, DM_IPC_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; +} + +HWTEST_F(DeviceManagerImplTest, CheckAuthentication3, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.helloworld"; + std::string authPara = ""; + std::shared_ptr callback = nullptr; + std::shared_ptr mockInstance = std::make_shared(); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_OK)); + int32_t ret = DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); + ASSERT_EQ(ret, DM_OK); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; +} + +HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery1, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + DmSubscribeInfo subscribeInfo; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, callback); + ASSERT_EQ(ret, DM_INVALID_VALUE); +} + +HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.helloworld"; + DmSubscribeInfo subscribeInfo; + test_callback_ = std::make_shared(); + std::shared_ptr mockInstance = std::make_shared(); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_OK)); + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, test_callback_); + ASSERT_EQ(ret, DM_OK); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; +} + +HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.helloworld"; + DmSubscribeInfo subscribeInfo; + test_callback_ = std::make_shared(); + std::shared_ptr mockInstance = std::make_shared(); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_FAILED)); + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, test_callback_); + ASSERT_EQ(ret, DM_IPC_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; +} +} // namespace + +void DeviceDiscoveryCallback::OnDiscoverySuccess(uint16_t subscribeId) +{ + (void)subscribeId; +} + +void DeviceDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) +{ + (void)subscribeId; + (void)failedReason; +} + +void DeviceDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +{ + (void)subscribeId; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/device_manager_impl_test.h b/test/unittest/device_manager_impl_test.h new file mode 100644 index 000000000..ffcb70e32 --- /dev/null +++ b/test/unittest/device_manager_impl_test.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IMPL_TEST_H +#define OHOS_DM_IMPL_TEST_H + +#include +#include + +#include "device_manager.h" +#include "device_manager_callback.h" +#include "device_manager_impl.h" +#include "mock/mock_ipc_client_proxy.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerImplTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; + +private: + std::shared_ptr test_callback_ = nullptr; +}; + +class DeviceDiscoveryCallback : public DiscoveryCallback { +public: + DeviceDiscoveryCallback() : DiscoveryCallback() + { + } + virtual ~DeviceDiscoveryCallback() override + { + } + virtual void OnDiscoverySuccess(uint16_t subscribeId) override; + virtual void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; + virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_IMPL_TEST_H diff --git a/test/unittest/mock/ipc_server_listener.cpp b/test/unittest/mock/ipc_server_listener.cpp new file mode 100644 index 000000000..4feadd497 --- /dev/null +++ b/test/unittest/mock/ipc_server_listener.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "ipc_server_listener.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + req_ = req; + return 0; +} + +int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + req_ = req; + return 0; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/ipc_server_listener.h b/test/unittest/mock/ipc_server_listener.h new file mode 100644 index 000000000..e0f072ac8 --- /dev/null +++ b/test/unittest/mock/ipc_server_listener.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_SERVER_LISTENER_H +#define OHOS_DM_IPC_SERVER_LISTENER_H + +#include +#include + +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerListener { +public: + IpcServerListener() = default; + virtual ~IpcServerListener() = default; + +public: + int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + std::shared_ptr req_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SERVER_LISTENER_H \ No newline at end of file diff --git a/test/unittest/mock/mock_ipc_client_proxy.h b/test/unittest/mock/mock_ipc_client_proxy.h new file mode 100644 index 000000000..ece83e9fb --- /dev/null +++ b/test/unittest/mock/mock_ipc_client_proxy.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_MOCK_IPC_CLIENT_PROXY_H +#define OHOS_MOCK_IPC_CLIENT_PROXY_H + +#include +#include + +#include "ipc_client_proxy.h" + +namespace OHOS { +namespace DistributedHardware { +class MockIpcClientProxy : public IpcClientProxy, public RefBase { +public: + MOCK_METHOD3(SendRequest, int32_t(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp)); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_MOCK_IPC_CLIENT_PROXY_H -- Gitee From 9a4d07ff7ec78407c5b88f3be7847dcb891cc454 Mon Sep 17 00:00:00 2001 From: puhui Date: Wed, 12 Jan 2022 22:00:55 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E6=8F=90=E4=BA=A4DM=E6=A1=86=E6=9E=B6?= =?UTF-8?q?=E4=B8=8E=E6=9C=8D=E5=8A=A1=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- BUILD.gn | 2 +- ...hos.distributedHardware.deviceManager.d.ts | 476 +++++++++++ display/build.gradle | 57 ++ display/entry/build.gradle | 42 + display/entry/src/main/config.json | 61 ++ display/entry/src/main/js/default/app.js | 23 + .../entry/src/main/js/default/i18n/en-US.json | 4 + .../entry/src/main/js/default/i18n/zh-CN.json | 4 + .../src/main/js/default/pages/index/index.css | 169 ++++ .../src/main/js/default/pages/index/index.hml | 98 +++ .../src/main/js/default/pages/index/index.js | 331 ++++++++ .../main/resources/base/element/string.json | 12 + .../src/main/resources/base/media/icon.png | Bin 0 -> 6790 bytes display/settings.gradle | 1 + services/devicemanagerservice/BUILD.gn | 202 +++++ .../include/ability/dm_ability_manager.h | 57 ++ .../include/adapter/crypto_adapter.h | 39 + .../include/adapter/decision_adapter.h | 40 + .../include/adapter/dm_adapter_manager.h | 39 + .../include/adapter/profile_adapter.h | 38 + .../authentication/auth_message_processor.h | 64 ++ .../authentication/auth_request_state.h | 95 +++ .../authentication/auth_response_state.h | 82 ++ .../include/authentication/auth_ui.h | 38 + .../include/authentication/authentication.h | 34 + .../include/authentication/dm_auth_manager.h | 182 +++++ .../include/config/config_manager.h | 81 ++ .../include/config/json_config.h | 79 ++ .../commonevent/event_manager_adapt.h | 81 ++ .../dependency/hichain/hichain_connector.h | 81 ++ .../hichain/hichain_connector_callback.h | 30 + .../dependency/softbus/softbus_connector.h | 93 +++ .../softbus/softbus_discovery_callback.h | 29 + .../dependency/softbus/softbus_session.h | 52 ++ .../softbus/softbus_session_callback.h | 31 + .../softbus/softbus_state_callback.h | 30 + .../include/dependency/timer/dm_timer.h | 71 ++ .../include/device_manager_service.h | 65 ++ .../include/device_manager_service_listener.h | 46 ++ .../deviceinfo/dm_device_info_manager.h | 41 + .../devicestate/dm_device_state_manager.h | 48 ++ .../include/discovery/dm_discovery_manager.h | 56 ++ .../include/ipc/lite/ipc_server_listener.h | 42 + .../include/ipc/lite/ipc_server_listenermgr.h | 52 ++ .../include/ipc/lite/ipc_server_stub.h | 26 + .../ipc/standard/ipc_server_client_proxy.h | 35 + .../ipc/standard/ipc_server_listener.h | 37 + .../include/ipc/standard/ipc_server_stub.h | 73 ++ .../src/ability/lite/dm_ability_manager.cpp | 50 ++ .../ability/standard/dm_ability_manager.cpp | 75 ++ .../src/adapter/lite/dm_adapter_manager.cpp | 56 ++ .../adapter/standard/dm_adapter_manager.cpp | 50 ++ .../authentication/auth_message_processor.cpp | 291 +++++++ .../src/authentication/auth_request_state.cpp | 205 +++++ .../authentication/auth_response_state.cpp | 159 ++++ .../src/authentication/auth_ui.cpp | 49 ++ .../src/authentication/dm_auth_manager.cpp | 754 ++++++++++++++++++ .../src/config/config_manager.cpp | 299 +++++++ .../commonevent/event_manager_adapt.cpp | 151 ++++ .../dependency/hichain/hichain_connector.cpp | 424 ++++++++++ .../dependency/softbus/softbus_connector.cpp | 561 +++++++++++++ .../dependency/softbus/softbus_session.cpp | 163 ++++ .../src/dependency/timer/dm_timer.cpp | 153 ++++ .../src/device_manager_service.cpp | 229 ++++++ .../src/device_manager_service_listener.cpp | 120 +++ .../src/deviceinfo/dm_device_info_manager.cpp | 62 ++ .../devicestate/dm_device_state_manager.cpp | 122 +++ .../src/discovery/dm_discovery_manager.cpp | 119 +++ .../src/ipc/lite/ipc_cmd_parser.cpp | 256 ++++++ .../src/ipc/lite/ipc_server_listener.cpp | 92 +++ .../src/ipc/lite/ipc_server_listenermgr.cpp | 65 ++ .../src/ipc/lite/ipc_server_main.cpp | 51 ++ .../src/ipc/lite/ipc_server_stub.cpp | 223 ++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 435 ++++++++++ .../ipc/standard/ipc_server_client_proxy.cpp | 46 ++ .../src/ipc/standard/ipc_server_listener.cpp | 48 ++ .../src/ipc/standard/ipc_server_stub.cpp | 187 +++++ 77 files changed, 8863 insertions(+), 1 deletion(-) create mode 100644 display/@ohos.distributedHardware.deviceManager.d.ts create mode 100644 display/build.gradle create mode 100644 display/entry/build.gradle create mode 100644 display/entry/src/main/config.json create mode 100644 display/entry/src/main/js/default/app.js create mode 100644 display/entry/src/main/js/default/i18n/en-US.json create mode 100644 display/entry/src/main/js/default/i18n/zh-CN.json create mode 100644 display/entry/src/main/js/default/pages/index/index.css create mode 100644 display/entry/src/main/js/default/pages/index/index.hml create mode 100644 display/entry/src/main/js/default/pages/index/index.js create mode 100644 display/entry/src/main/resources/base/element/string.json create mode 100644 display/entry/src/main/resources/base/media/icon.png create mode 100644 display/settings.gradle create mode 100644 services/devicemanagerservice/BUILD.gn create mode 100644 services/devicemanagerservice/include/ability/dm_ability_manager.h create mode 100644 services/devicemanagerservice/include/adapter/crypto_adapter.h create mode 100644 services/devicemanagerservice/include/adapter/decision_adapter.h create mode 100644 services/devicemanagerservice/include/adapter/dm_adapter_manager.h create mode 100644 services/devicemanagerservice/include/adapter/profile_adapter.h create mode 100644 services/devicemanagerservice/include/authentication/auth_message_processor.h create mode 100644 services/devicemanagerservice/include/authentication/auth_request_state.h create mode 100644 services/devicemanagerservice/include/authentication/auth_response_state.h create mode 100644 services/devicemanagerservice/include/authentication/auth_ui.h create mode 100644 services/devicemanagerservice/include/authentication/authentication.h create mode 100644 services/devicemanagerservice/include/authentication/dm_auth_manager.h create mode 100644 services/devicemanagerservice/include/config/config_manager.h create mode 100644 services/devicemanagerservice/include/config/json_config.h create mode 100644 services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h create mode 100644 services/devicemanagerservice/include/dependency/hichain/hichain_connector.h create mode 100644 services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_connector.h create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_session.h create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h create mode 100644 services/devicemanagerservice/include/dependency/timer/dm_timer.h create mode 100644 services/devicemanagerservice/include/device_manager_service.h create mode 100644 services/devicemanagerservice/include/device_manager_service_listener.h create mode 100644 services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h create mode 100644 services/devicemanagerservice/include/devicestate/dm_device_state_manager.h create mode 100644 services/devicemanagerservice/include/discovery/dm_discovery_manager.h create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h create mode 100644 services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp create mode 100644 services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp create mode 100644 services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp create mode 100644 services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp create mode 100644 services/devicemanagerservice/src/authentication/auth_message_processor.cpp create mode 100644 services/devicemanagerservice/src/authentication/auth_request_state.cpp create mode 100644 services/devicemanagerservice/src/authentication/auth_response_state.cpp create mode 100644 services/devicemanagerservice/src/authentication/auth_ui.cpp create mode 100644 services/devicemanagerservice/src/authentication/dm_auth_manager.cpp create mode 100644 services/devicemanagerservice/src/config/config_manager.cpp create mode 100644 services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp create mode 100644 services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp create mode 100644 services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp create mode 100644 services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp create mode 100644 services/devicemanagerservice/src/dependency/timer/dm_timer.cpp create mode 100644 services/devicemanagerservice/src/device_manager_service.cpp create mode 100644 services/devicemanagerservice/src/device_manager_service_listener.cpp create mode 100644 services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp create mode 100644 services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp create mode 100644 services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp diff --git a/BUILD.gn b/BUILD.gn index 3fc86faf2..cb9b6a6fa 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -24,4 +24,4 @@ if (defined(ohos_lite)) { ] } } -} \ No newline at end of file +} diff --git a/display/@ohos.distributedHardware.deviceManager.d.ts b/display/@ohos.distributedHardware.deviceManager.d.ts new file mode 100644 index 000000000..604936a6e --- /dev/null +++ b/display/@ohos.distributedHardware.deviceManager.d.ts @@ -0,0 +1,476 @@ +/* + * 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. + */ + +import { AsyncCallback, Callback } from './basic'; + +declare namespace deviceManager { + /** + * DeviceInfo + */ + interface DeviceInfo { + /** + * DeviceId ID. + */ + deviceId: string; + + /** + * Device name of the device. + */ + deviceName: string; + + /** + * Device type of the device. + */ + deviceType: DeviceType; + } + + /** + * Device Type definitions + */ + enum DeviceType { + /** + * Indicates an unknown device type. + */ + UNKNOWN_TYPE = 0, + + /** + * Indicates a speaker. + */ + SPEAKER = 0x0A, + + /** + * Indicates a smartphone. + */ + PHONE = 0x0E, + + /** + * Indicates a tablet. + */ + TABLET = 0x11, + + /** + * Indicates a smart watch. + */ + WEARABLE = 0x6D, + + /** + * Indicates a car. + */ + CAR = 0x83, + + /** + * Indicates a smart TV. + */ + TV = 0x9C + } + + /** + * Device state change event definition + */ + enum DeviceStateChangeAction { + /** + * device online action + */ + ONLINE = 0, + + /** + * device ready action, the device information synchronization was completed. + */ + READY = 1, + + /** + * device offline action + */ + OFFLINE = 2, + + /** + * device change action + */ + CHANGE = 3 + } + + /** + * Service subscribe info for device discover + * + * @systemapi this method can be used only by system applications. + */ + interface SubscribeInfo { + /** + * Service subscribe ID, the value is in scope [0, 65535], should be unique for each discover process + */ + subscribeId: number; + + /** + * Discovery mode for service subscription. + */ + mode: DiscoverMode; + + /** + * Service subscription medium. + */ + medium: ExchangeMedium; + + /** + * Service subscription frequency. + */ + freq: ExchangeFreq; + + /** + * only find the device with the same account. + */ + isSameAccount: boolean; + + /** + * find the sleeping devices. + */ + isWakeRemote: boolean; + + /** + * Subscribe capability. + */ + capability: SubscribeCap; + } + + /** + * device discover mode + * + * @systemapi this method can be used only by system applications. + */ + enum DiscoverMode { + /** + * Passive + */ + DISCOVER_MODE_PASSIVE = 0x55, + + /** + * Proactive + */ + DISCOVER_MODE_ACTIVE = 0xAA + } + + /** + * device discover medium + * + * @systemapi this method can be used only by system applications. + */ + enum ExchangeMedium { + /** + * Automatic medium selection + */ + AUTO = 0, + + /** + * Bluetooth + */ + BLE = 1, + + /** + * Wi-Fi + */ + COAP = 2, + + /** + * USB + */ + USB = 3 + } + + /** + * device discover freq + * + * @systemapi this method can be used only by system applications. + */ + enum ExchangeFreq { + /** + * Low + */ + LOW = 0, + + /** + * Medium + */ + MID = 1, + + /** + * High + */ + HIGH = 2, + + /** + * Super-high + */ + SUPER_HIGH = 3 + } + + /** + * device discover capability + * + * @systemapi this method can be used only by system applications. + */ + enum SubscribeCap { + /** + * ddmpCapability + */ + SUBSCRIBE_CAPABILITY_DDMP = 0 + } + + /** + * Device Authentication param + * + * @systemapi this method can be used only by system applications + */ + interface AuthParam { + /** + * Authentication type, 1 for pin code. + */ + authType: number; + + /** + * App application Icon. + */ + appIcon?: Uint8Array; + + /** + * App application thumbnail. + */ + appThumbnail?: Uint8Array; + + /** + * Authentication extra infos. + */ + extraInfo: {[key:string] : any}; + + } + + /** + * Device auth info. + * + * @systemapi this method can be used only by system applications + */ + interface AuthInfo { + /** + * Authentication type, 1 for pin code. + */ + authType: number; + + /** + * the token used for this authentication. + */ + token: number; + + /** + * Authentication extra infos. + */ + extraInfo: {[key:string] : any}; + } + + /** + * User Operation Action from devicemanager Fa. + * + * @systemapi this method can be used only by system applications. + */ + enum UserOperationAction { + /** + * allow authentication + */ + ACTION_ALLOW_AUTH = 0, + + /** + * cancel authentication + */ + ACTION_CANCEL_AUTH = 1, + + /** + * user operation timeout for authentication confirm + */ + ACTION_AUTH_CONFIRM_TIMEOUT = 2, + + /** + * cancel pincode display + */ + ACTION_CANCEL_PINCODE_DISPLAY = 3, + + /** + * cancel pincode input + */ + ACTION_CANCEL_PINCODE_INPUT = 4, + } + + /** + * Creates a {@code DeviceManager} instance. + * + *

To manage devices, you must first call this method to obtain a {@code DeviceManager} instance and then + * use this instance to call other device management methods. + * + * @param bundleName Indicates the bundle name of the application. + * @param callback Indicates the callback to be invoked upon {@code DeviceManager} instance creation. + */ + function createDeviceManager(bundleName: string, callback: AsyncCallback): void; + + /** + * Provides methods for managing devices. + */ + interface DeviceManager { + /** + * Releases the {@code DeviceManager} instance after the methods for device management are no longer used. + */ + release(): void; + + /** + * Obtains a list of trusted devices. + * + * @param options Indicates the extra parameters to be passed to this method for device filtering or sorting. + * This parameter can be null. For details about available values, see {@link #TARGET_PACKAGE_NAME} and + * {@link #SORT_TYPE}. + * @return Returns a list of trusted devices. + */ + getTrustedDeviceListSync(): Array; + + /** + * Start to discover device. + * + * @param bundleName Indicates the bundle name of the application. + * @param subscribeInfo subscribe info to discovery device + * @systemapi this method can be used only by system applications. + */ + startDeviceDiscovery(subscribeInfo: SubscribeInfo): void; + + /** + * Stop to discover device. + * + * @param bundleName Indicates the bundle name of the application. + * @param subscribeId Service subscribe ID + * @systemapi this method can be used only by system applications. + */ + stopDeviceDiscovery(subscribeId: number): void; + + /** + * Authenticate the specified device. + * + * @param deviceInfo deviceInfo of device to authenticate + * @param authparam authparam of device to authenticate + * @param callback Indicates the callback to be invoked upon authenticateDevice + * @systemapi this method can be used only by system applications. + */ + authenticateDevice(deviceInfo: DeviceInfo, authparam: AuthParam, callback: AsyncCallback<{deviceId: string, pinTone ?: number}>): void; + + /** + * verify auth info, such as pin code. + * + * @param authInfo device auth info o verify + * @param callback Indicates the callback to be invoked upon verifyAuthInfo + * @systemapi this method can be used only by system applications. + */ + verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void; + + /** + * Get authenticate parameters for peer device, this interface can only used by devicemanager Fa. + * + * @param authParam authparam for peer device + * @systemapi this method can be used only by system applications. + */ + getAuthenticationParam(): AuthParam; + + /** + * Set user Operation from devicemanager Fa, this interface can only used by devicemanager Fa. + * + * @param operateAction User Operation Actions. + * @systemapi this method can be used only by system applications. + */ + setUserOperation(operateAction: UserOperationAction): void; + + /** + * Register a callback from deviceManager service so that the devicemanager Fa can be notified when some events happen. + * this interface can only used by devicemanager Fa. + * + * @param callback for devicemanager Fa to register. + * @systemapi this method can be used only by system applications. + */ + on(type: 'dmFaCallback', callback: Callback<{ param: string}>): void; + + /** + * UnRegister dmFaCallback, this interface can only used by devicemanager Fa. + * + * @param callback for devicemanager Fa to register. + * @systemapi this method can be used only by system applications. + */ + off(type: 'dmFaCallback', callback?: Callback<{ param: string}>): void; + + /** + * Register a device state callback so that the application can be notified upon device state changes based on + * the application bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * @param callback Indicates the device state callback to register. + */ + on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void; + + /** + * UnRegister device state callback based on the application bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * @param callback Indicates the device state callback to register. + */ + off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void; + + /** + * Register a device found callback so that the application can be notified when the device was found + * + * @param callback Indicates the device found callback to register. + * @systemapi this method can be used only by system applications. + */ + on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: DeviceInfo }>): void; + + /** + * UnRegister a device found callback so that the application can be notified when the device was found + * + * @param callback Indicates the device found callback to register. + * @systemapi this method can be used only by system applications. + */ + off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: DeviceInfo }>): void; + + /** + * Register a device found result callback so that the application can be notified when the device discover was failed + * + * @param callback Indicates the device found result callback to register. + * @systemapi this method can be used only by system applications. + */ + on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: number }>): void; + + /** + * UnRegister a device found result callback so that the application can be notified when the device discover was failed + * + * @param callback Indicates the device found result callback to register. + * @systemapi this method can be used only by system applications. + */ + off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: number }>): void; + + /** + * Register a serviceError callback so that the application can be notified when devicemanager service died + * + * @param callback Indicates the service error callback to register. + */ + on(type: 'serviceDie', callback: () => void): void; + + /** + * UnRegister a serviceError callback so that the application can be notified when devicemanager service died + * + * @param callback Indicates the service error callback to register. + */ + off(type: 'serviceDie', callback?: () => void): void; + } +} + +export default deviceManager; diff --git a/display/build.gradle b/display/build.gradle new file mode 100644 index 000000000..151e80b67 --- /dev/null +++ b/display/build.gradle @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + // Top-level build file where you can add configuration options common to all sub-projects/modules. +apply plugin: 'com.huawei.ohos.app' + +ohos { + compileSdkVersion 6 + defaultConfig { + compatibleSdkVersion 6 + } +} + +buildscript { + repositories { + maven { + url 'http://repo.ark.tools.huawei.com/artifactory/maven-public/' + } + maven { + url 'https://mirrors.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + jcenter() + } + dependencies { + classpath 'com.huawei.ohos:hap:2.4.4.3-RC' + } +} + +allprojects { + repositories { + maven { + url 'http://repo.ark.tools.huawei.com/artifactory/maven-public/' + } + maven { + url 'https://mirrors.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + jcenter() + } +} \ No newline at end of file diff --git a/display/entry/build.gradle b/display/entry/build.gradle new file mode 100644 index 000000000..1f560cd47 --- /dev/null +++ b/display/entry/build.gradle @@ -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. + */ + + apply plugin: 'com.huawei.ohos.hap' +apply plugin: 'com.huawei.ohos.decctest' +//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 +ohos { + compileSdkVersion 6 + defaultConfig { + compatibleSdkVersion 6 + } + buildTypes { + release { + proguardOpt { + proguardEnabled false + rulesFiles 'proguard-rules.pro' + } + } + } + +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) + testImplementation 'junit:junit:4.13' + ohosTestImplementation 'com.huawei.ohos.testkit:runner:1.0.0.200' +} +decc { + supportType = ['html', 'xml'] +} diff --git a/display/entry/src/main/config.json b/display/entry/src/main/config.json new file mode 100644 index 000000000..946df5f47 --- /dev/null +++ b/display/entry/src/main/config.json @@ -0,0 +1,61 @@ +{ + "app": { + "bundleName": "com.ohos.devicemanagerui", + "vendor": "ohos", + "version": { + "code": 1000000, + "name": "1.0.0" + } + }, + "deviceConfig": {}, + "module": { + "package": "com.ohos.devicemanagerui", + "name": ".MyApplication", + "mainAbility": "com.ohos.devicemanagerui.MainAbility", + "deviceType": [ + "phone", + "tablet", + "tv", + "wearable" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry", + "installationFree": false + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "visible": true, + "name": "com.ohos.devicemanagerui.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "$string:entry_MainAbility", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": true + } + } + ] + } +} \ No newline at end of file diff --git a/display/entry/src/main/js/default/app.js b/display/entry/src/main/js/default/app.js new file mode 100644 index 000000000..8e47afff1 --- /dev/null +++ b/display/entry/src/main/js/default/app.js @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + onCreate() { + console.info('AceApplication onCreate'); + }, + onDestroy() { + console.info('AceApplication onDestroy'); + } +}; diff --git a/display/entry/src/main/js/default/i18n/en-US.json b/display/entry/src/main/js/default/i18n/en-US.json new file mode 100644 index 000000000..9e5209101 --- /dev/null +++ b/display/entry/src/main/js/default/i18n/en-US.json @@ -0,0 +1,4 @@ +{ + "strings": { + } +} \ No newline at end of file diff --git a/display/entry/src/main/js/default/i18n/zh-CN.json b/display/entry/src/main/js/default/i18n/zh-CN.json new file mode 100644 index 000000000..9e5209101 --- /dev/null +++ b/display/entry/src/main/js/default/i18n/zh-CN.json @@ -0,0 +1,4 @@ +{ + "strings": { + } +} \ No newline at end of file diff --git a/display/entry/src/main/js/default/pages/index/index.css b/display/entry/src/main/js/default/pages/index/index.css new file mode 100644 index 000000000..132302197 --- /dev/null +++ b/display/entry/src/main/js/default/pages/index/index.css @@ -0,0 +1,169 @@ +/* + * 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. + */ + +.container { + flex-direction: column; + justify-content: center; + align-items: center; + opacity: 0.8; + background-color: azure; +} + +.container > div { + flex-direction: column; + justify-content: center; + align-items: center; +} + +.main-pin > .pin-numb { + flex-direction: row; + justify-content: space-around; + align-items: center; + padding: 15px 30px 10px 30px; +} +.main-pin > .pin-numb > .pin-numb-item { + font-size: 30px; + line-height: 30px; + height: 40px; + padding-bottom: 5px; + font-weight: 800; + width: 30px; + border-bottom-width: 2px; + border-bottom-color: darkgray; + text-align: center; +} + +.main-pin > .input { + flex-direction: row; + justify-content: space-around; + align-items: center; + padding: 5px 30px 5px 30px; +} + +.main-pin > .input > .numb { + text-color: black; + padding: 5px; + flex-shrink: 0; + flex-basis: 60px; + background-color: white; + border: 1px; +} + +.join-auth { + padding-top: 30px; +} +.join-auth-image > image { + height: 170px; +} +.join-authorize { + padding-top: 10px; +} +.join-pin { + padding: 10px 0; +} +.join-pin > .pin { + font-size: 50px; + line-height: 90px; + font-weight: bolder; + color: #000000; +} + +.join-auth > .title, +.join-auth-image > .title, +.join-authorize > .title { + font-size: 18px; + line-height: 80px; + font-weight: 800; + color: #000000; +} +.join-auth > .title { + line-height: 40px; +} +.join-auth-image > .title { + line-height: 26px; +} +.join-pin > .title { + font-size: 28px; + line-height: 60px; + font-weight: 800; +} +.main-pin > .title { + font-size: 30px; + line-height: 40px; + font-weight: bolder; +} + +.join-auth > .title-tip, +.join-auth-image > .title-tip, +.main-pin > .title-tip, +.join-authorize > .title-tip { + font-size: 15px; + line-height: 40px; + color: #5A5A5A; +} +.join-auth > .title-tip { + line-height: 40px; +} +.join-auth-image > .title-tip { + line-height: 24px; +} +.join-pin > .title-tip { + font-size: 20px; + line-height: 50px; + font-weight: 600; +} +.main-pin > .title-tip { + font-size: 18px; + line-height: 30px; + font-weight: 800; +} + +.join-auth > .dialog-foot, +.join-auth-image > .dialog-foot, +.join-authorize > .dialog-foot { + flex-direction: row; + justify-content: center; + align-items: center; + justify-content: space-around; + margin: 80px 20px 30px 20px; +} +.join-authorize > .dialog-foot { + margin: 100px 20px 30px 20px; +} +.join-auth-image > .dialog-foot { + margin: 10px 20px 10px 20px; +} +.join-pin > .dialog-foot { + margin: 10px 20px 10px 20px; +} + +.join-auth .button-cancel, +.join-auth-image .button-cancel, +.join-authorize .button-cancel { + width: 160px; + height: 36px; +} +.join-pin .button-cancel { + width: 100%; + font-size: 26px; + height: 50px; +} + +.join-auth .button-ok, +.join-auth-image .button-ok, +.join-authorize .button-ok { + width: 150px; + height: 36px; +} \ No newline at end of file diff --git a/display/entry/src/main/js/default/pages/index/index.hml b/display/entry/src/main/js/default/pages/index/index.hml new file mode 100644 index 000000000..7f388b212 --- /dev/null +++ b/display/entry/src/main/js/default/pages/index/index.hml @@ -0,0 +1,98 @@ + + +

+
+ PIN码连接 + 请输入平板上显示的PIN码 +
+ {{pin[0]}} + {{pin[1]}} + {{pin[2]}} + {{pin[3]}} + {{pin[4]}} + {{pin[5]}} +
+
+ + + + +
+
+ + + + +
+
+ + + + +
+
+
+ 是否允许{{statusInfo.deviceName}}连接本机 + 用于资源访问 +
+ + +
+
+
+ {{ statusInfo.appName }} + 是否允许打开apply auth? + 来自{{statusInfo.deviceName}} +
+ + +
+
+
+ + {{ statusInfo.appName }} + 是否允许打开apply auth? + 来自{{statusInfo.deviceName}} +
+ + +
+
+
+ PIN码连接 + 请在主控端输入连接码进行验证 + {{statusInfo.pinCode.split('').join(' ')}} +
+ +
+
+
diff --git a/display/entry/src/main/js/default/pages/index/index.js b/display/entry/src/main/js/default/pages/index/index.js new file mode 100644 index 000000000..0304a8d52 --- /dev/null +++ b/display/entry/src/main/js/default/pages/index/index.js @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import router from '@system.router'; +import deviceManager from '@ohos.distributedHardware.deviceManager'; +function uint8ArrayToBase64(array) { + array = new Uint8Array(array); + let table = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'], + base64Str = '', length = array.byteLength, i = 0; + for(i = 0; length - i >= 3; i += 3) { + let num1 = array[i], num2 = array[i + 1], num3 = array[i + 2]; + base64Str += table[num1 >>> 2] + table[((num1 & 0b11) << 4) | (num2 >>> 4)] + table[((num2 & 0b1111) << 2) | (num3 >>> 6)] + table[num3 & 0b111111]; + } + const lastByte = length - i; + if (lastByte === 1) { + const lastNum1 = array[i]; + base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4)] + '=='; + } else if (lastByte === 2) { + const lastNum1 = array[i]; + const lastNum2 = array[i + 1]; + base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4) | (lastNum2 >>> 4)] + table[(lastNum2 & 0b1111) << 2] + '='; + } + return 'data:image/png;base64,' + base64Str; +} +const TAG = "DeviceManagerUI:"; +let dmClass; + +export default { + data: { + // showType: ['main-pin','join-authorize','join-auth','join-auth-image','join-pin'] + status: "", + // showInfo + statusInfo: { + deviceName: "AppName", + appName: 'PackageName', + appIcon: null, + pinCode: '', + pinToken: '' + }, + // join: join-authorize timing + timeRemaining: 0, + // input pinCode + pin: ['','','','','',''], + // input pinCode next number + pinNumb: 0 + }, + + log(m) { + console.info(TAG + m); + }, + + onDestroy() { + if (dmClass != null) { + dmClass.off('dmFaCallback'); + dmClass.off('deviceStateChange'); + dmClass.off('serviceDie'); + dmClass.release(); + dmClass = null + } + }, + + onShow() { + if (dmClass) { + this.initStatue() + } else { + this.log('createDeviceManager') + deviceManager.createDeviceManager('com.ohos.devicemanagerui', (err, dm) => { + this.log("createDeviceManager err:" + JSON.stringify(err) + ' --success:' + JSON.stringify(dm)) + if (err) return; + dmClass = dm; + dmClass.on('dmFaCallback', () => router.back()) + this.initStatue() + }); + } + }, + + onHide() { + this.timeRemaining = 0 + }, + + /** + * Get authentication param + */ + initStatue() { + this.log('initStatue') + const data = dmClass.getAuthenticationParam() + this.log('getAuthenticationParam:' + JSON.stringify(data)) + // Authentication type, 1 for pin code. + if (data && data.authType == 1) { + this.statusInfo = { + deviceName: data.extraInfo.PackageName, + appName: data.extraInfo.appName, + appIcon: uint8ArrayToBase64(data.appIcon), + pinCode: data.extraInfo.pinCode + '', + pinToken: data.extraInfo.pinToken + } + // direction: 1(main)/0(join) + if (data.extraInfo.direction == 1) { + this.mainPin() + } else if (data.appIcon) { + this.joinAuthImage() + } else if (data.extraInfo.business == 0) { + // business: 0(FA流转)/1(资源访问) + this.joinAuth() + } else { + this.joinAuthorize() + } + } + }, + + /** + * Set user Operation from devicemanager Fa, this interface can only used by devicemanager Fa. + * + * @param operateAction User Operation Actions. + * ACTION_ALLOW_AUTH = 0, allow authentication + * ACTION_CANCEL_AUTH = 1, cancel authentication + * ACTION_AUTH_CONFIRM_TIMEOUT = 2, user operation timeout for authentication confirm + * ACTION_CANCEL_PINCODE_DISPLAY = 3, cancel pinCode display + * ACTION_CANCEL_PINCODE_INPUT = 4, cancel pinCode input + */ + setUserOperation(operation) { + this.log('setUserOperation: ' + operation) + if (dmClass != null) { + var data = dmClass.setUserOperation(operation); + this.log('setUserOperation result: ' + JSON.stringify(data)) + } else { + this.log('deviceManagerObject not exit') + } + }, + + /** + * verify auth info, such as pin code. + * @param pinCode + * @return + */ + verifyAuthInfo(pinCode) { + this.log('verifyAuthInfo: ' + pinCode) + if (dmClass != null) { + dmClass.verifyAuthInfo({ + "authType": 1, + "token": this.statusInfo.pinToken, + "extraInfo": { + "pinCode": +pinCode + } + }, (err, data) => { + if (err) { + this.log("verifyAuthInfo err:" + JSON.stringify(err)) + } + this.log("verifyAuthInfo result:" + JSON.stringify(data)) + router.back() + }); + } else { + this.log('deviceManagerObject not exit') + } + }, + + /** + * Input pinCode at the main control terminal + */ + mainPin() { + this.status = 'main-pin' + }, + + /** + * Enter a number with the keyboard + * @param s + * @return + */ + mainInputPin(s) { + this.log('mainInputPin input: ' + s + '-' + this.pin) + if (this.pinNumb == 6) return + if (this.pinNumb < 6) { + this.pin[this.pinNumb] = s + ++this.pinNumb + this.pin = [...this.pin] + } + this.log('mainInputPin pin: ' + this.pin + '-' + this.pin.join('')) + if (this.pinNumb == 6) { + // input end + this.log('mainInputPin end: ' + this.pin + '-' + this.pin.join('')) + this.verifyAuthInfo(this.pin.join('')) + } + }, + + /** + * Keyboard delete number + */ + mainInputPinBack() { + if (this.pinNumb > 0) { + --this.pinNumb + this.pin[this.pinNumb] = '' + this.pin = [...this.pin] + } + }, + + /** + * Cancel pinCode input + */ + mainInputPinCancel() { + this.setUserOperation(4) + }, + + /** + * Join end authorization, business(FA流转)/1(资源访问): 0 + */ + joinAuthorize() { + this.status = 'join-authorize' + this.timing(60, 'join-authorize', () => { + this.setUserOperation(2) + router.back() + }) + }, + + /** + * Join end authorization, business(FA流转)/1(资源访问): 1 + */ + joinAuth() { + this.status = 'join-auth' + this.timing(60, 'join-auth', () => { + this.setUserOperation(2) + router.back() + }) + }, + + /** + * Join end authorization, business(FA流转)/1(资源访问): 1, show application icon + */ + joinAuthImage() { + this.status = 'join-auth-image' + this.timing(60, 'join-auth-image', () => { + this.setUserOperation(2) + router.back() + }) + }, + + /** + * Display pinCode at join end + */ + joinPin() { + this.status = 'join-pin' + }, + + /** + * Cancel authorization + */ + joinAuthorizeCancel() { + this.setUserOperation(1) + router.back() + }, + + /** + * Confirm authorization + */ + joinAuthorizeOk() { + this.setUserOperation(0) + this.joinPin() + }, + + /** + * Cancel authorization + */ + joinAuthCancel() { + this.setUserOperation(1) + router.back() + }, + + /** + * Confirm authorization + */ + joinAuthOk() { + this.setUserOperation(0) + this.joinPin() + }, + + /** + * Cancel authorization + */ + joinAuthImageCancel() { + this.setUserOperation(1) + router.back() + }, + + /** + * Confirm authorization + */ + joinAuthImageOk() { + this.setUserOperation(0) + this.joinPin() + }, + + /** + * Cancel authorization + */ + joinPinCancel() { + this.setUserOperation(3) + router.back() + }, + + /** + * Pure function countdown + * @param numb second + * @param status + * @param callback + * @return + */ + timing(numb, status, callback) { + this.timeRemaining = numb + const next = () => { + if (status != this.status) return + --this.timeRemaining + if (this.timeRemaining > 0) { + setTimeout(next, 1000) + } else { + callback() + } + } + next() + } +} diff --git a/display/entry/src/main/resources/base/element/string.json b/display/entry/src/main/resources/base/element/string.json new file mode 100644 index 000000000..0bae6bd40 --- /dev/null +++ b/display/entry/src/main/resources/base/element/string.json @@ -0,0 +1,12 @@ +{ + "string": [ + { + "name": "entry_MainAbility", + "value": "entry_MainAbility" + }, + { + "name": "mainability_description", + "value": "JS_Empty Ability" + } + ] +} \ No newline at end of file diff --git a/display/entry/src/main/resources/base/media/icon.png b/display/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c GIT binary patch literal 6790 zcmX|G1ymHk)?T_}Vd;>R?p|tHQo6fg38|$UVM!6BLrPFWk?s;$LOP{GmJpBl$qoSA!PUg~PA65-S00{{S`XKG6NkG0RgjEntPrmV+?0|00mu7;+5 zrdpa{2QLqPJ4Y{j7=Mrl{BaxrkdY69+c~(w{Fv-v&aR%aEI&JYSeRTLWm!zbv;?)_ ziZB;fwGbbeL5Q}YLx`J$lp~A09KK8t_z}PZ=4ZzgdeKtgoc+o5EvN9A1K1_<>M?MBqb#!ASf&# zEX?<)!RH(7>1P+j=jqG(58}TVN-$psA6K}atCuI!KTJD&FMmH-78ZejBm)0qc{ESp z|LuG1{QnBUJRg_E=h1#XMWt2%fcoN@l7eAS!Es?Q+;XsRNPhiiE=@AqlLkJzF`O18 zbsbSmKN=aaq8k3NFYZfDWpKmM!coBU0(XnL8R{4=i|wi{!uWYM2je{U{B*K2PVdu&=E zTq*-XsEsJ$u5H4g6DIm2Y!DN`>^v|AqlwuCD;w45K0@eqauiqWf7l&o)+YLHm~|L~ z7$0v5mkobriU!H<@mVJHLlmQqzQ3d6Rh_-|%Yy2li*tHO>_vcnuZ7OR_xkAIuIU&x z-|8Y0wj|6|a6_I(v91y%k_kNw6pnkNdxjqG8!%Vz_d%c_!X+6-;1`GC9_FpjoHev5fEV7RhJ>r=mh-jp$fqbqRJ=obwdgLDVP5+s zy1=_DWG0Y-Jb3t^WXmkr(d9~08k-|#Ly zaNOmT(^9tIb&eb4%CzIT zAm3CUtWSr1t4?h1kk#NBi{U|pJslvME{q|_eS^3En>SOqSxyuN1x;Is@8~m?*>}** znrRFArP!K_52RpX*&JHMR<^lVdm8ypJ}0R(SD(51j;6@ni$6bQ+2XL+R^|NnSp5}(kzvMZ^(@4fD_{QVu$(&K6H|C37TG1Am9Re{<<3gd zh@`>;BqkXMW&p0T6rt|iB$)~CvFe(XC)F9WgAZn*0@t$oZo;!*}r@_`h?KKH&6A@3= zISXoQB+~`op>NP-buiA*^0n{@i{_?MRG)&k)c)k_F+-2Lud!S9pc+i`s74NpBCaGF zXN+pHkubw*msGBTY27BKHv)RRh3;nMg4&$fD_6X9Vt~;_4D+5XPH~#Kn-yjcy!$}1 zigv#FNY>TqMhtIBb@UoF!cE~Q8~;!Pek>SQQwHnHuWKoVBosAiOr}q>!>aE*Krc)V zBUMEcJ5NU0g8}-h6i1zpMY9>m4ne?=U2~`w7K7Q0gB_=p@$5K7p6}thw z-~3dMj?YNX2X$lZ+7ngQ$=s}3mizNN@kE%OtB)?c&i~2L55z8^=yz;xMHLmlY>&Q# zJj?!)M#q_SyfkQh)k?j8IfLtB)ZCp|*vf4_B zos?73yd^h-Ac+;?E4*bpf=o*^3x3-`TVjbY4n6!EN10K6o@fxdyps05Vo3PU)otB} z`3kR+2w7_C#8Z!q`J)p{Vh!+m9-UP!$STp+Hb}}#@#_u^SsUQg<}59< zTvH3%XS4G+6FF^(m6bVF&nSUIXcl;nw{=H$%fgeJ>CgDYiLdpDXr{;-AnG z8dvcrHYVMI&`R6;GWekI@Ir3!uo)oz4^{6q0m^}@f2tM9&=YHNi6-?rh0-{+k@cQm zdp`g#YdQn%MDVg2GR>wZ`n2<0l4)9nx1Wfr&!Dvz=bPwU!h2S?ez6MVc5APE4-xLB zi&W9Q8k2@0w!C53g?iAIQ}~p*3O(@zja6KQ=M3zfW*_6o5SwR-)6VBh~m7{^-=MC-owYH5-u40a}a0liho3QZZ5L{bS_xM1)4}19)zTU$$MY zq3eZML1WC{K%YFd`Be0M-rkO^l?h{kM{$2oK1*A@HVJ57*yhDkUF!2WZ&oA4Y-sK( zCY69%#`mBCi6>6uw(x4gbFaP0+FD*JKJ-q!F1E?vLJ+d35!I5d7@^eU?(CS|C^tmI5?lv@s{{*|1F zFg|OzNpZ0hxljdjaW%45O0MOttRrd(Z?h{HYbB-KFUx&9GfFL3b8NwZ$zNu)WbBD` zYkj$^UB5%3Pj1MDr>S2Ejr9pUcgA!;ZG!@{uAy12)vG=*^9-|dNQBc8&`oxBlU~#y zs!anJX&T?57Jdr^sb>e+V`MVfY>Y0ESg7MG<7W0g&bR-ZYzzZ%2H&Etcp zcd6QeXO1D!5A#zM0lx*GH}`M)2~ZFLE;sP^RSB5wVMNfiZXPd(cmO>j=OSA3`o5r& zna(|^jGXbdN7PK)U8b7^zYtYkkeb%<%F~=OqB~kXMQkq}ii|skh@WSRt>5za;cjP0 zZ~nD%6)wzedqE}BMLt~qKwlvTr33))#uP~xyw#*Eaa|DbMQ_%mG0U8numf8)0DX`r zRoG2bM;#g|p-8gWnwRV5SCW0tLjLO&9Z?K>FImeIxlGUgo0Zk`9Qzhj1eco~7XZy+hXc@YF&ZQ=? zn*^1O56yK^x{y}q`j7}blGCx%dydV!c7)g~tJzmHhV=W~jbWRRR{1<^oDK+1clprm zz$eCy7y9+?{E|YgkW~}}iB#I4XoJ*xr8R?i_Hv$=Cof5bo-Nj~f`-DLebH}&0% zfQj9@WGd4;N~Y?mzQsHJTJq6!Qzl^-vwol(+fMt#Pl=Wh#lI5Vmu@QM0=_r+1wHt` z+8WZ~c2}KQQ+q)~2Ki77QvV&`xb|xVcTms99&cD$Zz4+-^R4kvUBxG8gDk7Y`K*)JZ^2rL(+ZWV~%W(@6 z)0bPArG#BROa_PHs~&WplQ_UIrpd)1N1QGPfv!J(Z9jNT#i%H?CE6|pPZb9hJ1JW4 z^q;ft#!HRNV0YgPojzIYT`8LuET2rUe-J|c!9l4`^*;4WtY@Ew@pL>wkjmMgGfN7 ze}}GtmU0@<_#08~I-Suk=^*9GLW=H4xhsml;vAV{%hy5Eegl@!6qKqbG024%n2HHw zCc@ivW_$@5ZoHP70(7D+(`PvgjW1Pd`wsiuv-aCukMrafwDm)B!xXVy*j2opohhoU zcJz%ADmj>i3`-3-$7nQKBQQuGY;2Qt&+(L~C>vSGFj5{Mlv?T_^dql;{zkpe4R1}R z%XfZyQ}wr*sr>jrKgm*PWLjuVc%6&&`Kbf1SuFpHPN&>W)$GmqC;pIoBC`=4-hPY8 zT*>%I2fP}vGW;R=^!1be?ta2UQd2>alOFFbVl;(SQJ4Jk#)4Z0^wpWEVvY4=vyDk@ zqlModi@iVPMC+{?rm=4(n+<;|lmUO@UKYA>EPTS~AndtK^Wy^%#3<;(dQdk3WaUkRtzSMC9}7x2||CNpF#(3T4C)@ z$~RWs`BNABKX|{cmBt>Q=&gkXl&x!!NK_%5hW0LS)Z4PB>%sV?F-{Wyj#s7W%$F{D zXdK^Fp3wvy+48+GP6F_|^PCRx=ddcTO3sG;B23A49~Qaw31SZ0Rc~`r4qqt%#OGW{ zCA_(LG5^N>yzUn&kAgVmxb=EA8s&tBXC}S1CZ(KoW)(%^JjLTPo^fs`Va;`=YlVPgmB$!yB}<(4ym6OeZ3xAJJ#;)2+B%p3P1Wt+d$eo`vz`T zXfUP2))kBDPoscH;Jc7I3NU<({|@wM$&GaDt`n7WLgIY3IA7A6-_R?z8N3mz|}*i z(zl5ot--Oq@f2-nv{X(ujT2T(k1vY_qh93pK@>H-qc%2Xta)IP0Q%zt%bqYgI`o!wv!0QerB`nCN^1n|@$sVOQ!V0teVG!I z_fD%JvfDeT1cK#-{o6Gv7}& zY0#NWin~kVaf$aufV&;63Hbs|`QVZWpDX6IMk1Hj2G}fiH9e-^6u2zf^FIr^BwD<6zjw63+{yUe8PUFvk8v{sJ=R{d#`O!sz`Q13~< zPT$JS(w=yQfU2`zPCNfSw=&zup@DXc(98afjhv@1w_f!m2Z>rMJ19AB&dB%P#Ls3b z=lK7OILM+SQ&VEd=1GN6o&>YVVtIzoZ%=Z_SdqJN2}E43{bE`>w+A;=y->@^k{oCC z$F*WTY&?34;kfyFV?b*Xb1Pq`Z=%OgwEg)Rz)tx=`f%5#w_INP=x&z5!jI;#;N$ma zhO)+MDm;SxOEVL15; zGq(v2pL3&P1Sl)8P*;G-fd{l1QJsv@e@d8)1PK4w2m*M%V3j-V~L^$i|&C@b?D?9tfwE{B^}Z$k8e5FmQ>v7Xz)sG32g9t}YBt zyR$+*_00RmPx+0mW+vVG4mxd(n$(eQf3-w>JPl2UJpafrPaL5@2j}%{VE-) zBI%6Qpj*dsdH<;g!S!avA~bv^0E+ zfyJbSjPb+j;J52U)<|cIcntQBI2T#>2;tOxu{%D?kML476AErF(qN9hPva5Nkc@BF zC-tLF@3ZFb%Kpj)M<{)x*l|*Ia@ECeXo2E4h2f!aV=cHAhi_E_mfUth(sM4^hJq7B zQsGWqdZUm9S%F`$nQ*_#NcuD`&)Ek%_s{&^78{9Hm ztri&rYLOxgFdG>O@+XHy z9#;|&vBCPXH5Mon^I`jSuR$&~ZWtyB67ujzFSj!51>#C}C17~TffQ{c-!QFQkTQ%! zIR^b1`zHx|*1GU?tbBx23weFLz5H?y_Q%N&t$}k?w+``2A=aotj0;2v$~AL z{scF-cL{wsdrmPvf#a9OHyYLcwQD4Kcm)`LLwMh4WT~p29f7M!iafJSU`IV}QY5Wa z(n44-9oA}?J{a+ah*@31WTs#&J#o1`H98#6IQf;Wv0N_!);f&9g7o-k(lW5rWnDUR zQBFIRG+X=6NnsI@mxnwm;tf5;_Uxg?jZ8m-m0}&6+DA!qam(p$mN5R})yA_7m$q@| zFEd|dpS595rxQr-n#GjI5i-AhnUE>Cr;jpCqSrD~EwK_DqI^7%3#p5)%T_od!t3SOmH9MyXeeGO2(UQL;ax|x?Ncixmeo1=$ z{-);Au{*tfzOG?KQ~K|ak8-HQ?`Pekhe2WM(8s{xv-p>Zmu_6{G!-oE$7$mY`MOJorI=+mMx?H;`pr!;fVYz?5~yXBACruWB`Ph zZM}90_<^OBxIhyZ9BW$`>6JvO;%VFpqVr8|7t3~AmxYak6?`Pp#c;**_SYmi`&z23 z`p6_~ePvH)C6x-G9$hgL=eVALq`-AiamN>!3~Lxw&{H(b{B(7xSRm6<3<{%{yXiH# zos5Rv1L+8fUKJLo%P>4I&$}y + +#include +#include +#include + +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +enum AbilityRole { ABILITY_ROLE_PASSIVE = 0, ABILITY_ROLE_INITIATIVE = 1, ABILITY_ROLE_UNKNOWN = 2 }; + +enum AbilityStatus { ABILITY_STATUS_FAILED = 0, ABILITY_STATUS_SUCCESS = 1, ABILITY_STATUS_START = 2 }; + +enum FaAction { + USER_OPERATION_TYPE_ALLOW_AUTH = 0, + USER_OPERATION_TYPE_CANCEL_AUTH = 1, + USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT = 2, + USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY = 3, + USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT = 4 +}; + +class DmAbilityManager { +public: + AbilityRole GetAbilityRole(); + AbilityStatus StartAbility(AbilityRole role); + void StartAbilityDone(); + +private: + void waitForTimeout(uint32_t timeout_s); + +private: + sem_t mSem_; + AbilityStatus mStatus_; + AbilityRole mAbilityStatus_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h new file mode 100644 index 000000000..099107ed1 --- /dev/null +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_CRYPTO_ADAPTER_H +#define OHOS_DM_CRYPTO_ADAPTER_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class ICryptoAdapter { +public: + virtual ~ICryptoAdapter() = default; + virtual std::string GetName() = 0; + virtual std::string GetVersion() = 0; + virtual int32_t MbedTlsEncrypt(const uint8_t *plainText, int32_t plainTextLen, uint8_t *cipherText, + int32_t cipherTextLen, int32_t *outLen) = 0; + virtual int32_t MbedTlsDecrypt(const uint8_t *cipherText, int32_t cipherTextLen, uint8_t *plainText, + int32_t plainTextLen, int32_t *outLen) = 0; +}; + +using CreateICryptoAdapterFuncPtr = ICryptoAdapter *(*)(void); + +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_CRYPTO_ADAPTER_H diff --git a/services/devicemanagerservice/include/adapter/decision_adapter.h b/services/devicemanagerservice/include/adapter/decision_adapter.h new file mode 100644 index 000000000..7e96a823d --- /dev/null +++ b/services/devicemanagerservice/include/adapter/decision_adapter.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_DM_DECISION_ADAPTER_H +#define OHOS_DM_DECISION_ADAPTER_H + +#include +#include + +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IDecisionAdapter { +public: + virtual ~IDecisionAdapter() = default; + virtual std::string GetName() = 0; + virtual std::string GetVersion() = 0; + virtual int32_t FilterDeviceList(std::vector &infoList, const std::string &filterOptions) = 0; + virtual int32_t SortDeviceList(std::vector &infoList, const std::string &sortOptions) = 0; +}; + +using CreateIDecisionAdapterFuncPtr = IDecisionAdapter *(*)(void); + +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_DECISION_ADAPTER_H diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h new file mode 100644 index 000000000..b290e8367 --- /dev/null +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_ADAPTER_MANAGER_H +#define OHOS_DM_ADAPTER_MANAGER_H + +#include + +#include "crypto_adapter.h" +#include "decision_adapter.h" +#include "profile_adapter.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class IProfileAdapter; +class DmAdapterManager { + DECLARE_SINGLE_INSTANCE(DmAdapterManager); + +public: + std::shared_ptr GetDecisionAdapter(const std::string &soName); + std::shared_ptr GetProfileAdapter(const std::string &soName); + std::shared_ptr GetCryptoAdapter(const std::string &soName); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_ADAPTER_MANAGER_H diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h new file mode 100644 index 000000000..39f5a3de7 --- /dev/null +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PROFILE_ADAPTER_H +#define OHOS_DM_PROFILE_ADAPTER_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceStateManager; +class IProfileAdapter { +public: + virtual ~IProfileAdapter() = default; + virtual int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterProfileListener(const std::string &pkgName) = 0; +}; + +using CreateIProfileAdapterFuncPtr = IProfileAdapter *(*)(void); + +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_PROFILE_ADAPTER_H diff --git a/services/devicemanagerservice/include/authentication/auth_message_processor.h b/services/devicemanagerservice/include/authentication/auth_message_processor.h new file mode 100644 index 000000000..73226f7a8 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_AUTH_MESSAGE_PROCESSOR_H +#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_H + +#include +#include + +#include "crypto_adapter.h" +#include "dm_auth_manager.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManager; +struct DmAuthRequestContext; +struct DmAuthResponseContext; +class ICryptoAdapter; +class AuthMessageProcessor { +public: + AuthMessageProcessor(std::shared_ptr authMgr); + ~AuthMessageProcessor(); + std::vector CreateAuthRequestMessage(); + std::string CreateSimpleMessage(int32_t msgType); + int32_t ParseMessage(const std::string &message); + void SetRequestContext(std::shared_ptr authRequestContext); + void SetResponseContext(std::shared_ptr authResponseContext); + std::shared_ptr GetResponseContext(); + std::shared_ptr GetRequestContext(); + +private: + std::string CreateRequestAuthMessage(nlohmann::json &json); + void CreateNegotiateMessage(nlohmann::json &json); + void CreateSyncGroupMessage(nlohmann::json &json); + void CreateResponseAuthMessage(nlohmann::json &json); + void ParseAuthResponseMessage(nlohmann::json &json); + void ParseAuthRequestMessage(); + void ParseNegotiateMessage(const nlohmann::json &json); + void CreateResponseFinishMessage(nlohmann::json &json); + void ParseResponseFinishMessage(nlohmann::json &json); + +private: + std::weak_ptr authMgr_; + std::shared_ptr cryptoAdapter_; + std::shared_ptr authRequestContext_; + std::shared_ptr authResponseContext_; + std::vector authSplitJsonList_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MESSAGE_PROCESSOR_H diff --git a/services/devicemanagerservice/include/authentication/auth_request_state.h b/services/devicemanagerservice/include/authentication/auth_request_state.h new file mode 100644 index 000000000..a1a3343e8 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_request_state.h @@ -0,0 +1,95 @@ +/* + * 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_AUTH_REQUEST_STATE_H +#define OHOS_DM_AUTH_REQUEST_STATE_H +#include +#include +#include + +#include "dm_log.h" +namespace OHOS { +namespace DistributedHardware { +class DmAuthManager; +struct DmAuthRequestContext; +class AuthRequestState : public std::enable_shared_from_this { +public: + virtual ~AuthRequestState() + { + authManager_.reset(); + LOGE("~AuthRequestState"); + }; + virtual int32_t GetStateType() = 0; + virtual void Enter() = 0; + void Leave(); + void TransitionTo(std::shared_ptr state); + void SetAuthManager(std::shared_ptr authManager); + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); + +protected: + std::weak_ptr authManager_; + std::shared_ptr context_; +}; + +class AuthRequestInitState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthRequestNegotiateState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; +class AuthRequestNegotiateDoneState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthRequestReplyState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthRequestInputState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthRequestJoinState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthRequestNetworkState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthRequestFinishState : public AuthRequestState { +public: + int32_t GetStateType() override; + void Enter() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_REQUEST_STATE_H diff --git a/services/devicemanagerservice/include/authentication/auth_response_state.h b/services/devicemanagerservice/include/authentication/auth_response_state.h new file mode 100644 index 000000000..f84e54ba9 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_response_state.h @@ -0,0 +1,82 @@ +/* + * 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_AUTH_RESPONSE_STATE_H +#define OHOS_DM_AUTH_RESPONSE_STATE_H + +#include + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthManager; +struct DmAuthResponseContext; +class AuthResponseState : public std::enable_shared_from_this { +public: + virtual ~AuthResponseState() + { + authManager_.reset(); + }; + virtual int32_t GetStateType() = 0; + virtual void Enter() = 0; + void Leave(); + void TransitionTo(std::shared_ptr state); + void SetAuthManager(std::shared_ptr authManager); + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); + +protected: + std::weak_ptr authManager_; + std::shared_ptr context_; +}; + +class AuthResponseInitState : public AuthResponseState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthResponseNegotiateState : public AuthResponseState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthResponseConfirmState : public AuthResponseState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthResponseGroupState : public AuthResponseState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthResponseShowState : public AuthResponseState { +public: + int32_t GetStateType() override; + void Enter() override; +}; + +class AuthResponseFinishState : public AuthResponseState { +public: + int32_t GetStateType() override; + void Enter() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_RESPONSE_STATE_H diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h new file mode 100644 index 000000000..4ba96cb50 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_ui.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_AUTH_UI_H +#define OHOS_DM_AUTH_UI_H + +#include + +#include "dm_ability_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class AuthUi { +public: + AuthUi(); + int32_t ShowConfirmDialog(std::shared_ptr dmAbilityManager); + +private: + int32_t StartFaService(); + +private: + std::shared_ptr dmAbilityMgr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_UI_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h new file mode 100644 index 000000000..5783f1112 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/authentication.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_AUTHENTICATION_H +#define OHOS_DM_AUTHENTICATION_H + +#include "dm_ability_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class IAuthentication { +public: + virtual ~IAuthentication() = default; + virtual int32_t ShowAuthInfo() = 0; + virtual int32_t StartAuth(std::shared_ptr dmAbilityManager) = 0; + virtual int32_t VerifyAuthentication(std::string pinToken, int32_t code, const std::string &authParam) = 0; +}; + +using CreateIAuthAdapterFuncPtr = IAuthentication *(*)(void); +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTHENTICATION_H diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h new file mode 100644 index 000000000..5bf2d4a04 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -0,0 +1,182 @@ +/* + * 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_AUTH_MANAGER_H +#define OHOS_DM_AUTH_MANAGER_H + +#include +#include + +#include "auth_message_processor.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "auth_ui.h" +#include "authentication.h" +#include "device_manager_service_listener.h" +#include "dm_ability_manager.h" +#include "dm_adapter_manager.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_timer.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { + +typedef enum AuthState { + AUTH_REQUEST_INIT = 1, + AUTH_REQUEST_NEGOTIATE, + AUTH_REQUEST_NEGOTIATE_DONE, + AUTH_REQUEST_REPLY, + AUTH_REQUEST_INPUT, + AUTH_REQUEST_JOIN, + AUTH_REQUEST_NETWORK, + AUTH_REQUEST_FINISH, + AUTH_RESPONSE_INIT = 20, + AUTH_RESPONSE_NEGOTIATE, + AUTH_RESPONSE_CONFIRM, + AUTH_RESPONSE_GROUP, + AUTH_RESPONSE_SHOW, + AUTH_RESPONSE_FINISH, +} AuthState; + +enum DmMsgType : int32_t { + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_NEGOTIATE = 80, + MSG_TYPE_RESP_NEGOTIATE = 90, + MSG_TYPE_REQ_AUTH = 100, + MSG_TYPE_INVITE_AUTH_INFO = 102, + MSG_TYPE_REQ_AUTH_TERMINATE = 104, + MSG_TYPE_RESP_AUTH = 200, + MSG_TYPE_JOIN_AUTH_INFO = 201, + MSG_TYPE_RESP_AUTH_TERMINATE = 205, + MSG_TYPE_CHANNEL_CLOSED = 300, + MSG_TYPE_SYNC_GROUP = 400, + MSG_TYPE_AUTH_BY_PIN = 500, +}; + +typedef struct DmAuthRequestContext { + int32_t authType; + std::string localDeviceId; + std::string deviceId; + std::string deviceName; + std::string deviceTypeId; + int32_t sessionId; + int32_t groupVisibility; + bool cryptoSupport; + std::string cryptoName; + std::string cryptoVer; + std::string hostPkgName; + std::string targetPkgName; + std::string appName; + std::string appDesc; + std::string appIcon; + std::string appThumbnail; + std::string token; + int32_t reason; + std::vector syncGroupList; +} DmAuthRequestContext; + +typedef struct DmAuthResponseContext { + int32_t authType; + std::string deviceId; + std::string localDeviceId; + int32_t msgType; + int32_t sessionId; + bool cryptoSupport; + std::string cryptoName; + std::string cryptoVer; + int32_t reply; + std::string networkId; + std::string groupId; + std::string groupName; + std::string hostPkgName; + std::string targetPkgName; + std::string appName; + std::string appDesc; + std::string appIcon; + std::string appThumbnail; + std::string token; + int64_t requestId; + int32_t code; + std::vector syncGroupList; +} DmAuthResponseContext; + +class AuthMessageProcessor; + +class DmAuthManager final : public ISoftbusSessionCallback, + public IHiChainConnectorCallback, + public std::enable_shared_from_this { +public: + DmAuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener); + ~DmAuthManager(); + int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId); + int32_t VerifyAuthentication(const std::string &authParam); + void OnSessionOpened(const std::string &pkgName, int32_t sessionId, int32_t sessionSide, int32_t result); + void OnSessionClosed(const std::string &pkgName, int32_t sessionId); + void OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message); + void OnGroupCreated(int64_t requestId, const std::string &groupId); + void OnMemberJoin(int64_t requestId, int32_t status); + + // auth state machine + void EstablishAuthChannel(const std::string &deviceId); + void StartNegotiate(const int32_t &sessionId); + void RespNegotiate(const int32_t &sessionId); + void SendAuthRequest(const int32_t &sessionId); + void StartAuthProcess(const int32_t &authType); + void StartRespAuthProcess(); + void CreateGroup(); + void AddMember(const std::string &deviceId); + std::string GetConnectAddr(std::string deviceId); + void JoinNetwork(); + void AuthenticateFinish(); + void GetIsCryptoSupport(bool &isCryptoSupport); + void SetAuthRequestState(std::shared_ptr authRequestState); + void SetAuthResponseState(std::shared_ptr authResponseState); + int32_t GetPinCode(); + std::string GenerateGroupName(); + void HandleAuthenticateTimeout(); + void CancelDisplay(); + int32_t GeneratePincode(); + void ShowConfigDialog(); + void ShowAuthInfoDialog(); + void ShowStartAuthDialog(); + int32_t GetAuthenticationParam(DmAuthParam &authParam); + int32_t RegisterSessionCallback(); + int32_t OnUserOperation(int32_t action); + +private: + std::shared_ptr softbusConnector_; + std::shared_ptr hiChainConnector_; + std::shared_ptr listener_; + std::shared_ptr adapterMgr_; + std::map> authenticationMap_; + std::shared_ptr authRequestState_ = nullptr; + std::shared_ptr authResponseState_ = nullptr; + std::shared_ptr authRequestContext_; + std::shared_ptr authResponseContext_; + std::shared_ptr authMessageProcessor_; + std::map> timerMap_; + std::shared_ptr dmAbilityMgr_; + bool isCryptoSupport_ = false; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_H diff --git a/services/devicemanagerservice/include/config/config_manager.h b/services/devicemanagerservice/include/config/config_manager.h new file mode 100644 index 000000000..4a410a1e7 --- /dev/null +++ b/services/devicemanagerservice/include/config/config_manager.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OHOS_DM_CONFIG_MANAGER_H +#define OHOS_OHOS_DM_CONFIG_MANAGER_H + +#include +#include +#include +#include +#include +#include +#include + +#include "authentication.h" +#include "crypto_adapter.h" +#include "decision_adapter.h" +#include "profile_adapter.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +typedef struct { + std::string name; + std::string type; + std::string version; + std::string funcName; + std::string soName; + std::string soPath; +} AdapterSoLoadInfo; + +typedef struct { + int32_t authType; + std::string name; + std::string type; + std::string version; + std::string funcName; + std::string soName; + std::string soPath; +} AuthSoLoadInfo; + +class DmConfigManager final { + DECLARE_SINGLE_INSTANCE_BASE(DmConfigManager); + +public: + ~DmConfigManager(); + void GetAllAuthType(std::vector &allAuthType); + std::shared_ptr GetDecisionAdapter(const std::string &soName); + std::shared_ptr GetProfileAdapter(const std::string &soName); + std::shared_ptr GetCryptoAdapter(const std::string &soName); + void GetAuthAdapter(std::map> &authAdapter); + +private: + DmConfigManager(); + +private: + std::mutex authAdapterMutex_; + std::mutex cryptoAdapterMutex_; + std::mutex decisionAdapterMutex_; + std::mutex profileAdapterMutex_; + std::map soAuthLoadInfo_; + std::map soAdapterLoadInfo_; + std::map> decisionAdapterPtr_; + std::map> profileAdapterPtr_; + std::map> cryptoAdapterPtr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_OHOS_DM_CONFIG_MANAGER_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/config/json_config.h b/services/devicemanagerservice/include/config/json_config.h new file mode 100644 index 000000000..a1c495cc0 --- /dev/null +++ b/services/devicemanagerservice/include/config/json_config.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OHOS_DM_JSON_CONFIG_H +#define OHOS_OHOS_DM_JSON_CONFIG_H + +#include + +namespace OHOS { +namespace DistributedHardware { +const std::string adapterJsonConfigString = + R"({ + "devicemanager_adapter_components": [ + { + "name": "crypto_adapter", + "type": "CPYPTO", + "version": "1.0", + "funcName": "CreateCryptoAdapterObject", + "soName": "libdevicemanager_crypto_adapter.z.so", + "soPath": "/system/lib/" + }, + { + "name": "device_profile", + "type": "PROFILE", + "version": "1.0", + "funcName": "CreateDeviceProfileObject", + "soName": "libdevicemanagerext_profile.z.so", + "soPath": "/system/lib/" + } + ] +})"; + +const std::string authJsonConfigString = + R"({ + "devicemanager_auth_components": [ + { + "name": "pin_auth", + "type": "AUTHENTICATE", + "version": "1.0", + "authType": 1, + "funcName": "CreatePinAuthObject", + "soName": "libdevicemanagerext_pin_auth.z.so", + "soPath": "/system/lib/" + }, + { + "name": "QRcode_auth", + "type": "AUTHENTICATE", + "version": "1.0", + "authType": 2, + "funcName": "CreateQRcodeAuthObject", + "soName": "libdevicemanager_qrcodeauth.z.so", + "soPath": "/system/lib/" + }, + { + "name": "nfc_auth", + "type": "AUTHENTICATE", + "version": "1.0", + "authType": 3, + "funcName": "CreateNfcAuthObject", + "soName": "libdevicemanager_nfcauth.z.so", + "soPath": "/system/lib/" + } + ] +})"; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_OHOS_DM_JSON_CONFIG_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h b/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h new file mode 100644 index 000000000..be733f983 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_EVENT_MANAGER_ADAPT_H +#define OHOS_EVENT_MANAGER_ADAPT_H + +#include +#include + +#include "common_event.h" +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "dm_log.h" +#include "matching_skills.h" + +namespace OHOS { +namespace DistributedHardware { + +using CommomEventCallback = void (*)(void); + +class DmCommonEventManager { +public: + static DmCommonEventManager &GetInstance(); + +public: + bool SubscribeServiceEvent(const std::string &event, CommomEventCallback callback); + bool UnsubscribeServiceEvent(const std::string &event); + + class EventSubscriber : public EventFwk::CommonEventSubscriber { + public: + explicit EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) + : EventFwk::CommonEventSubscriber(subscribeInfo) + { + } + + void OnReceiveEvent(const EventFwk::CommonEventData &data); + void addEventCallback(const std::string &event, CommomEventCallback callback); + void deleteEventCallback(const std::string &event); + + private: + std::mutex callbackLock_; + std::map dmEventCallback_; + }; + +private: + DmCommonEventManager() = default; + virtual ~DmCommonEventManager(); + DmCommonEventManager(const DmCommonEventManager &) = delete; + DmCommonEventManager &operator=(const DmCommonEventManager &) = delete; + DmCommonEventManager(DmCommonEventManager &&) = delete; + DmCommonEventManager &operator=(DmCommonEventManager &&) = delete; + +private: + static void DealCallback(void); + static void InitCallbackThread(void); + +private: + static std::once_flag onceFlag_; + static std::list callbackQueue_; + static std::mutex callbackQueueMutex_; + static std::condition_variable notEmpty_; + std::map> dmEventSubscriber_; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_EVENT_MANAGER_ADAPT_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h new file mode 100644 index 000000000..895441bf4 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_HICHAIN_CONNECTOR_H +#define OHOS_HICHAIN_CONNECTOR_H + +#include +#include +#include +#include +#include + +#include "device_auth.h" +#include "hichain_connector_callback.h" +#include "nlohmann/json.hpp" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +struct GroupInfo { + std::string groupName; + std::string groupId; + std::string groupOwner; + int32_t groupType; + int32_t groupVisibility; + + GroupInfo() : groupName(""), groupId(""), groupOwner(""), groupType(0), groupVisibility(0) + { + } +}; + +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); + +public: + HiChainConnector(); + ~HiChainConnector(); + int32_t RegisterHiChainCallback(const std::string &pkgName, std::shared_ptr callback); + int32_t UnRegisterHiChainCallback(const std::string &pkgName); + int32_t CreateGroup(int64_t requestId, const std::string &groupName); + int32_t AddMember(std::string deviceId, std::string &connectInfo); + int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); + void DeleteGroup(std::string &groupId); + bool IsDevicesInGroup(std::string hostDevice, std::string peerDevice); + void GetRelatedGroups(std::string DeviceId, std::vector &groupList); + +private: + int64_t GenRequestId(); + void SyncGroups(std::string deviceId, std::vector &remoteGroupIdList); + void GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList); + int32_t GetGroupInfo(std::string queryParams, std::vector &groupList); + std::string GetConnectPara(std::string deviceId, std::string reqDeviceId); + bool IsGroupCreated(std::string groupName, GroupInfo &groupInfo); + bool IsGroupInfoInvalid(GroupInfo &group); + +private: + const DeviceGroupManager *deviceGroupManager_ = nullptr; + DeviceAuthCallback deviceAuthCallback_; + static std::map> hiChainConnectorCallbackMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_HICHAIN_CONNECTOR_H diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h new file mode 100644 index 000000000..f6504949a --- /dev/null +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H +#define OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H + +namespace OHOS { +namespace DistributedHardware { +class IHiChainConnectorCallback { +public: + virtual void OnGroupCreated(int64_t requestId, const std::string &groupId) = 0; + virtual void OnMemberJoin(int64_t requestId, int32_t status) = 0; + virtual std::string GetConnectAddr(std::string deviceId) = 0; + virtual int32_t GetPinCode() = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h new file mode 100644 index 000000000..1e08a4709 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -0,0 +1,93 @@ +/* + * 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_SOFTBUS_CONNECTOR_H +#define OHOS_DM_SOFTBUS_CONNECTOR_H + +#include +#include +#include +#include +#include + +#include "discovery_service.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "softbus_bus_center.h" +#include "softbus_discovery_callback.h" +#include "softbus_session.h" +#include "softbus_state_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class SoftbusConnector { +public: + static void OnPublishSuccess(int32_t publishId); + static void OnPublishFail(int32_t 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 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); + static bool IsDeviceOnLine(const std::string &deviceId); + static int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); + static int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); + static int32_t GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info, + int32_t infoLen); + +public: + SoftbusConnector(); + ~SoftbusConnector(); + int32_t RegisterSoftbusStateCallback(const std::string &pkgName, + const std::shared_ptr callback); + int32_t UnRegisterSoftbusStateCallback(const std::string &pkgName); + int32_t RegisterSoftbusDiscoveryCallback(const std::string &pkgName, + const std::shared_ptr callback); + int32_t UnRegisterSoftbusDiscoveryCallback(const std::string &pkgName); + int32_t GetTrustedDeviceList(std::vector &deviceInfoList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo); + int32_t StartDiscovery(const DmSubscribeInfo &subscribeInfo); + int32_t StopDiscovery(uint16_t subscribeId); + std::shared_ptr GetSoftbusSession(); + bool HaveDeviceInMap(std::string deviceId); + +private: + int32_t Init(); + static void CovertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo); + static void CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo); + static ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); + +private: + enum PulishStatus { + STATUS_UNKNOWN = 0, + ALLOW_BE_DISCOVERY = 1, + NOT_ALLOW_BE_DISCOVERY = 2, + }; + static PulishStatus publishStatus; + static INodeStateCb softbusNodeStateCb_; + static IDiscoveryCallback softbusDiscoveryCallback_; + static IPublishCallback softbusPublishCallback_; + std::shared_ptr softbusSession_; + static std::map> discoveryDeviceInfoMap_; + static std::map> stateCallbackMap_; + static std::map> discoveryCallbackMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_CONNECTOR_H diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h new file mode 100644 index 000000000..c8b1f57cd --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h @@ -0,0 +1,29 @@ +/* + * 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_SOFTBUS_DISCOVERY_CALLBACK_H +#define OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H + +namespace OHOS { +namespace DistributedHardware { +class ISoftbusDiscoveryCallback { +public: + virtual void OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) = 0; + virtual void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) = 0; + virtual void OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h new file mode 100644 index 000000000..084df4817 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SOFTBUS_SESSION_H +#define OHOS_DM_SOFTBUS_SESSION_H + +#include +#include +#include +#include +#include + +#include "inner_session.h" +#include "session.h" +#include "softbus_session_callback.h" + +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); + +public: + SoftbusSession(); + ~SoftbusSession(); + int32_t RegisterSessionCallback(const std::string &pkgName, std::shared_ptr callback); + int32_t UnRegisterSessionCallback(const std::string &pkgName); + int32_t OpenAuthSession(const std::string &deviceId); + void CloseAuthSession(int32_t sessionId); + int32_t SendData(int32_t sessionId, std::string &message); + void GetPeerDeviceId(int32_t sessionId, std::string &peerDevId); + +private: + static std::map> sessionCallbackMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_SESSION_H diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h new file mode 100644 index 000000000..9569a3313 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SOFTBUS_SESSION_CALLBACK_H +#define OHOS_DM_SOFTBUS_SESSION_CALLBACK_H + +namespace OHOS { +namespace DistributedHardware { +class ISoftbusSessionCallback { +public: + virtual void OnSessionOpened(const std::string &pkgName, int32_t sessionId, int32_t sessionSide, + int32_t result) = 0; + virtual void OnSessionClosed(const std::string &pkgName, int32_t sessionId) = 0; + virtual void OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message) = 0; + virtual void GetIsCryptoSupport(bool &isCryptoSupport) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_SESSION_CALLBACK_H diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h new file mode 100644 index 000000000..15a08a2e3 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SOFTBUS_STATE_CALLBACK_H +#define OHOS_DM_SOFTBUS_STATE_CALLBACK_H + +namespace OHOS { +namespace DistributedHardware { +class ISoftbusStateCallback { +public: + virtual void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) = 0; + virtual void OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) = 0; + virtual void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) = 0; + virtual void OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_STATE_CALLBACK_H diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h new file mode 100644 index 000000000..66a0adbf3 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIMER_H +#define TIMER_H +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +typedef void (*TimeoutHandle)(void *data); + +#define MAXEVENTS 255 + +enum DmTimerStatus : int32_t { + DM_STATUS_INIT = 0, + DM_STATUS_RUNNING = 1, + DM_STATUS_BUSY = 2, + DM_STATUS_CREATE_ERROR = 3, + DM_STATUS_FINISH = 6, +}; + +class DmTimer { +public: + DmTimer(std::string &name); + ~DmTimer(); + DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data); + void Stop(int32_t code); + void WaitForTimeout(); + +private: + int32_t CreateTimeFd(); + void Release(); + +private: + DmTimerStatus mStatus_; + uint32_t mTimeOutSec_; + TimeoutHandle mHandle_; + void *mHandleData_; + int32_t mTimeFd_[2]; + struct epoll_event mEv_; + struct epoll_event mEvents_[MAXEVENTS]; + int32_t mEpFd_; + std::thread mThread_; + std::string mTimerName_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h new file mode 100644 index 000000000..53e33b1d6 --- /dev/null +++ b/services/devicemanagerservice/include/device_manager_service.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_DM_SERVICE_H +#define OHOS_DM_SERVICE_H + +#include +#include + +#include "dm_ability_manager.h" +#include "dm_auth_manager.h" +#include "dm_device_info.h" +#include "dm_device_info_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "single_instance.h" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerService { + DECLARE_SINGLE_INSTANCE(DeviceManagerService); + +public: + int32_t Init(); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &info); + int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid); + int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid); + int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra); + int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId); + int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId); + int32_t VerifyAuthentication(const std::string &authParam); + int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam); + int32_t SetUserOperation(std::string &pkgName, int32_t action); + +private: + bool intFlag_ = false; + std::shared_ptr authMgr_; + std::shared_ptr deviceInfoMgr_; + std::shared_ptr deviceStateMgr_; + std::shared_ptr discoveryMgr_; + std::shared_ptr softbusConnector_; + std::shared_ptr listener_; + std::shared_ptr abilityMgr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SERVICE_H diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h new file mode 100644 index 000000000..4ad17f9f8 --- /dev/null +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SERVICE_LISTENER_H +#define OHOS_DM_SERVICE_LISTENER_H + +#include +#include + +#include "dm_device_info.h" +#include "ipc_notify_dmfa_result_req.h" +#include "ipc_server_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerServiceListener { +public: + void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info); + void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info); + void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason); + void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId); + void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, + const std::string &reason); + void OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode, + const std::string &flag); + void OnFaCall(std::string &pkgName, std::string ¶mJson); + +private: + IpcServerListener ipcServerListener_; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_SERVICE_LISTENER_H diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h new file mode 100644 index 000000000..9dfe5b159 --- /dev/null +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.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_DM_DEVICEINFO_MANAGER_H +#define OHOS_DM_DEVICEINFO_MANAGER_H + +#include +#include + +#include "dm_adapter_manager.h" +#include "dm_device_info.h" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceInfoManager { +public: + DmDeviceInfoManager(std::shared_ptr &softbusConnectorPtr); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &info); + +private: + std::shared_ptr softbusConnector_; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_DEVICEINFO_MANAGER_H diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h new file mode 100644 index 000000000..a54ef47ef --- /dev/null +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_DEVICE_STATE_MANAGER_H +#define OHOS_DM_DEVICE_STATE_MANAGER_H + +#include "device_manager_service_listener.h" +#include "dm_adapter_manager.h" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceStateManager final : public ISoftbusStateCallback, + public std::enable_shared_from_this { +public: + DmDeviceStateManager(std::shared_ptr softbusConnector, + std::shared_ptr listener); + ~DmDeviceStateManager(); + void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info); + void OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info); + void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info); + void OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info); + void OnProfileReady(const std::string &pkgName, const std::string deviceId); + int32_t RegisterSoftbusStateCallback(); + +private: + std::shared_ptr softbusConnector_; + std::shared_ptr adapterMgr_; + std::shared_ptr listener_; + std::map deviceStateMap_; + std::map remoteDeviceInfos_; + std::string profileSoName_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DEVICE_STATE_MANAGER_H diff --git a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h new file mode 100644 index 000000000..20c30ec8b --- /dev/null +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_DISCOVERY_MANAGER_H +#define OHOS_DM_DISCOVERY_MANAGER_H + +#include + +#include "device_manager_service_listener.h" +#include "dm_timer.h" +#include "softbus_connector.h" +namespace OHOS { +namespace DistributedHardware { + +typedef struct DmDiscoveryContext { + std::string pkgName; + std::string extra; + uint16_t subscribeId; +} DmDiscoveryContext; + +class DmDiscoveryManager final : public ISoftbusDiscoveryCallback, + public std::enable_shared_from_this { +public: + DmDiscoveryManager(std::shared_ptr softbusConnector, + std::shared_ptr listener); + ~DmDiscoveryManager(); + int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra); + int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId); + void OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info); + void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId); + void OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason); + void HandleDiscoveryTimeout(); + +private: + std::shared_ptr softbusConnector_; + std::shared_ptr listener_; + std::queue discoveryQueue_; + std::map discoveryContextMap_; + std::shared_ptr discoveryTimer_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DISCOVERY_MANAGER_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h new file mode 100644 index 000000000..4cf1b62ce --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.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_DM_IPC_SERVER_LISTENER_H +#define OHOS_DM_IPC_SERVER_LISTENER_H + +#include + +#include "ipc_req.h" +#include "ipc_rsp.h" +#include "ipc_server_listenermgr.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerListener { +public: + IpcServerListener() = default; + virtual ~IpcServerListener() = default; + +public: + int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + +private: + void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity); + int32_t GetIdentityByPkgName(std::string &name, SvcIdentity *svc); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SERVER_LISTENER_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h new file mode 100644 index 000000000..2d0ed61c4 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_SERVER_LISTENER_MGR_H +#define OHOS_DM_IPC_SERVER_LISTENER_MGR_H + +#include +#include +#include +#include + +#include "liteipc_adapter.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +typedef struct CommonSvcId { + uint32_t handle; + uint32_t token; + uint32_t cookie; + IpcContext *ipcCtx; + uint32_t cbId; +} CommonSvcId; + +class IpcServerListenermgr { + DECLARE_SINGLE_INSTANCE(IpcServerListenermgr); + +public: + int32_t RegisterListener(std::string &pkgName, const CommonSvcId *svcId); + int32_t GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId); + int32_t UnregisterListener(std::string &pkgName); + const std::map &GetAllListeners(); + +private: + std::map dmListenerMap_; + std::mutex lock_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SERVER_LISTENER_MGR_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h new file mode 100644 index 000000000..fc22d9471 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_SERVER_STUB_H +#define OHOS_DM_IPC_SERVER_STUB_H + +#include + +#include "liteipc_adapter.h" + +int32_t IpcServerStubInit(void); +int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply); +int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply); +#endif // OHOS_DM_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h new file mode 100644 index 000000000..f1fbd2405 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h @@ -0,0 +1,35 @@ +/* + * 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_IPC_SERVER_CLIENT_PROXY_H +#define OHOS_DM_IPC_SERVER_CLIENT_PROXY_H + +#include "ipc_remote_broker.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerClientProxy : public IRemoteProxy { +public: + explicit IpcServerClientProxy(const sptr &impl) : IRemoteProxy(impl){}; + ~IpcServerClientProxy(){}; + int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SERVER_CLIENT_PROXY_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h new file mode 100644 index 000000000..1ee6680b9 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_SERVER_LISTENER_H +#define OHOS_DM_IPC_SERVER_LISTENER_H + +#include + +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerListener { +public: + IpcServerListener() = default; + virtual ~IpcServerListener() = default; + +public: + int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SERVER_LISTENER_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h new file mode 100644 index 000000000..93d0f7878 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_SERVER_STUB_H +#define OHOS_DM_IPC_SERVER_STUB_H + +#include +#include +#include +#include +#include + +#include "hichain_connector.h" +#include "ipc_remote_broker.h" +#include "iremote_stub.h" +#include "nlohmann/json.hpp" +#include "single_instance.h" +#include "system_ability.h" +#include "thread_pool.h" + +namespace OHOS { +namespace DistributedHardware { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; + +class AppDeathRecipient : public IRemoteObject::DeathRecipient { +public: + void OnRemoteDied(const wptr &remote) override; + AppDeathRecipient() = default; + ~AppDeathRecipient() = default; +}; + +class IpcServerStub : public SystemAbility, public IRemoteStub { + DECLARE_SYSTEM_ABILITY(IpcServerStub); + DECLARE_SINGLE_INSTANCE_BASE(IpcServerStub); + +public: + void OnStart() override; + void OnStop() override; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; + int32_t RegisterDeviceManagerListener(std::string &pkgName, sptr listener); + int32_t UnRegisterDeviceManagerListener(std::string &pkgName); + ServiceRunningState QueryServiceState() const; + const std::map> &GetDmListener(); + const sptr GetDmListener(std::string pkgName) const; + +private: + IpcServerStub(); + ~IpcServerStub() = default; + bool Init(); + +private: + bool registerToService_; + ServiceRunningState state_; + std::mutex listenerLock_; + std::map> appRecipient_; + std::map> dmListener_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp new file mode 100644 index 000000000..e81442c7d --- /dev/null +++ b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_ability_manager.h" + +#include "dm_constants.h" +#include "semaphore.h" + +namespace OHOS { +namespace DistributedHardware { +AbilityRole DmAbilityManager::GetAbilityRole() +{ + return mAbilityStatus_; +} + +AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) +{ + // not support for L1 yet, do nothing. jsut save status and role + mAbilityStatus_ = role; + mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + return mStatus_; +} + +void DmAbilityManager::waitForTimeout(uint32_t timeout_s) +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout_s; + sem_timedwait(&mSem_, &ts); +} + +void DmAbilityManager::StartAbilityDone() +{ + mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + sem_post(&mSem_); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp new file mode 100644 index 000000000..ce077df93 --- /dev/null +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_ability_manager.h" + +#include "ability_manager_client.h" +#include "ability_manager_service.h" +#include "ability_record.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "parameter.h" +#include "semaphore.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const int32_t ABILITY_START_TIMEOUT = 3; // 3 second +const std::string bundleName = "com.ohos.devicemanagerui"; +const std::string abilityName = "com.ohos.devicemanagerui.MainAbility"; +} // namespace + +AbilityRole DmAbilityManager::GetAbilityRole() +{ + return mAbilityStatus_; +} + +AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) +{ + mAbilityStatus_ = role; + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string deviceId = localDeviceId; + mStatus_ = AbilityStatus::ABILITY_STATUS_START; + AAFwk::Want want; + AppExecFwk::ElementName element(deviceId, bundleName, abilityName); + want.SetElement(element); + AAFwk::AbilityManagerClient::GetInstance()->Connect(); + ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); + if (result != OHOS::ERR_OK) { + LOGE("Start Ability faild"); + mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; + return mStatus_; + } + waitForTimeout(ABILITY_START_TIMEOUT); + return mStatus_; +} + +void DmAbilityManager::waitForTimeout(uint32_t timeout_s) +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout_s; + sem_timedwait(&mSem_, &ts); +} + +void DmAbilityManager::StartAbilityDone() +{ + mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + sem_post(&mSem_); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp new file mode 100644 index 000000000..219002770 --- /dev/null +++ b/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_adapter_manager.h" + +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +DmAdapterManager &DmAdapterManager::GetInstance() +{ + static DmAdapterManager instance; + return instance; +} + +DmAdapterManager::DmAdapterManager() +{ + LOGI("DmAdapterManager constructor"); +} + +DmAdapterManager::~DmAdapterManager() +{ + LOGI("DmAdapterManager destructor"); +} + +std::shared_ptr DmAdapterManager::GetDecisionAdapter() +{ + return decisionAdapterPtr_; +} + +std::shared_ptr DmAdapterManager::GetProfileAdapter() +{ + return profileAdapterPtr_; +} + +std::shared_ptr DmAdapterManager::GetCryptoAdapter() +{ + return cryptoAdapterPtr_; +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp new file mode 100644 index 000000000..693656d50 --- /dev/null +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_adapter_manager.h" + +#include + +#include "config_manager.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +DmAdapterManager &DmAdapterManager::GetInstance() +{ + static DmAdapterManager instance; + return instance; +} + +std::shared_ptr DmAdapterManager::GetDecisionAdapter(const std::string &soName) +{ + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + return dmConfigManager.GetDecisionAdapter(soName); +} + +std::shared_ptr DmAdapterManager::GetProfileAdapter(const std::string &soName) +{ + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + return dmConfigManager.GetProfileAdapter(soName); +} + +std::shared_ptr DmAdapterManager::GetCryptoAdapter(const std::string &soName) +{ + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + return dmConfigManager.GetCryptoAdapter(soName); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp new file mode 100644 index 000000000..1b547a60f --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -0,0 +1,291 @@ +/* + * 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 "auth_message_processor.h" + +#include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +AuthMessageProcessor::AuthMessageProcessor(std::shared_ptr authMgr) : authMgr_(authMgr) +{ + LOGI("AuthMessageProcessor constructor"); +} + +AuthMessageProcessor::~AuthMessageProcessor() +{ + authMgr_.reset(); +} + +std::vector AuthMessageProcessor::CreateAuthRequestMessage() +{ + LOGI("AuthMessageProcessor::CreateAuthRequestMessage start."); + std::vector jsonStrVec; + int32_t thumbnailSize = authRequestContext_->appThumbnail.size(); + int32_t thumbnailSlice = ((thumbnailSize / MSG_MAX_SIZE) + (thumbnailSize % MSG_MAX_SIZE) == 0 ? 0 : 1); + nlohmann::json jsonObj; + jsonObj[TAG_VER] = DM_ITF_VER; + jsonObj[TAG_TYPE] = MSG_TYPE_REQ_AUTH; + jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1; + jsonObj[TAG_INDEX] = 0; + jsonObj[TAG_REQUESTER] = authRequestContext_->deviceName; + jsonObj[TAG_DEVICE_ID] = authRequestContext_->deviceId; + jsonObj[TAG_DEVICE_TYPE] = authRequestContext_->deviceTypeId; + jsonObj[TAG_AUTH_TYPE] = authRequestContext_->authType; + jsonObj[TAG_TOKEN] = authRequestContext_->token; + jsonObj[TAG_VISIBILITY] = authRequestContext_->groupVisibility; + if (authRequestContext_->groupVisibility == GROUP_VISIBILITY_IS_PRIVATE) { + jsonObj[TAG_TARGET] = authRequestContext_->targetPkgName; + jsonObj[TAG_HOST] = authRequestContext_->hostPkgName; + } + jsonObj[TAG_APP_NAME] = authRequestContext_->appName; + jsonObj[TAG_APP_DESCRIPTION] = authRequestContext_->appDesc; + jsonObj[TAG_APP_ICON] = authRequestContext_->appIcon; + jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; + jsonStrVec.push_back(jsonObj.dump()); + + for (int32_t idx = 0; idx < thumbnailSlice; idx++) { + nlohmann::json jsonThumbnailObj; + jsonThumbnailObj[TAG_VER] = DM_ITF_VER; + jsonThumbnailObj[TAG_TYPE] = MSG_TYPE_REQ_AUTH; + jsonThumbnailObj[TAG_SLICE_NUM] = thumbnailSlice + 1; + jsonThumbnailObj[TAG_INDEX] = idx + 1; + jsonThumbnailObj[TAG_DEVICE_ID] = authRequestContext_->deviceId; + jsonThumbnailObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; + + int32_t leftLen = thumbnailSize - idx * MSG_MAX_SIZE; + int32_t sliceLen = (leftLen > MSG_MAX_SIZE) ? MSG_MAX_SIZE : leftLen; + LOGD("TAG_APP_THUMBNAIL encode, idx %d, sliceLen %d, thumbnailSize %d", idx, sliceLen, thumbnailSize); + jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); + jsonStrVec.push_back(jsonThumbnailObj.dump()); + } + return jsonStrVec; +} + +std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) +{ + LOGI("AuthMessageProcessor::CreateSimpleMessage start. msgType is %d", msgType); + nlohmann::json jsonObj; + jsonObj[TAG_VER] = DM_ITF_VER; + jsonObj[TAG_TYPE] = msgType; + switch (msgType) { + case MSG_TYPE_NEGOTIATE: + case MSG_TYPE_RESP_NEGOTIATE: + CreateNegotiateMessage(jsonObj); + break; + case MSG_TYPE_SYNC_GROUP: + CreateSyncGroupMessage(jsonObj); + break; + case MSG_TYPE_RESP_AUTH: + CreateResponseAuthMessage(jsonObj); + break; + case MSG_TYPE_REQ_AUTH_TERMINATE: + CreateResponseFinishMessage(jsonObj); + break; + default: + break; + } + return jsonObj.dump(); +} + +void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) +{ + if (cryptoAdapter_ == nullptr) { + json[TAG_CRYPTO_SUPPORT] = false; + } else { + json[TAG_CRYPTO_SUPPORT] = true; + json[TAG_CRYPTO_NAME] = cryptoAdapter_->GetName(); + json[TAG_CRYPTO_VERSION] = cryptoAdapter_->GetVersion(); + json[TAG_DEVICE_ID] = authRequestContext_->deviceId; + } + json[TAG_REPLY] = authResponseContext_->reply; + json[TAG_LOCAL_DEVICE_ID] = authResponseContext_->localDeviceId; +} + +void AuthMessageProcessor::CreateSyncGroupMessage(nlohmann::json &json) +{ + json[TAG_DEVICE_ID] = authRequestContext_->deviceId; + json[TAG_GROUPIDS] = authRequestContext_->syncGroupList; +} + +void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) +{ + json[TAG_REPLY] = authResponseContext_->reply; + json[TAG_DEVICE_ID] = authResponseContext_->deviceId; + json[TAG_TOKEN] = authResponseContext_->token; + // json[TAG_GROUPIDS] = authResponseContext_->deviceId; //? + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %d,%d", authResponseContext_->reply, + authResponseContext_->code); + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str()); + if (authResponseContext_->reply == 0) { + std::string groupId = authResponseContext_->groupId; + LOGI("AuthMessageProcessor::CreateSimpleMessage groupId %d", groupId.c_str()); + nlohmann::json jsonObject = nlohmann::json::parse(groupId, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + groupId = jsonObject[TAG_GROUP_ID]; + json[PIN_CODE_KEY] = authResponseContext_->code; + json[TAG_NET_ID] = authResponseContext_->networkId; + json[TAG_REQUEST_ID] = authResponseContext_->requestId; + json[TAG_GROUP_ID] = groupId; + json[TAG_GROUP_NAME] = authResponseContext_->groupName; + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s", groupId.c_str(), + authResponseContext_->groupName.c_str()); + } +} + +void AuthMessageProcessor::CreateResponseFinishMessage(nlohmann::json &json) +{ + json[TAG_REPLY] = authResponseContext_->reply; +} + +int32_t AuthMessageProcessor::ParseMessage(const std::string &message) +{ + LOGE(" AuthMessageProcessor ParseMessage"); + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + if (!jsonObject.contains(TAG_TYPE)) { + LOGE("err json string, first time"); + return DM_FAILED; + } + int32_t sliceNum = 0; + int32_t msgType = jsonObject[TAG_TYPE]; + authResponseContext_->msgType = msgType; + LOGI("AuthMessageProcessor::ParseAuthRequestMessage======== %d", authResponseContext_->msgType); + switch (msgType) { + case MSG_TYPE_NEGOTIATE: + ParseNegotiateMessage(jsonObject); + break; + case MSG_TYPE_REQ_AUTH: + if (!jsonObject.contains(TAG_INDEX) || !jsonObject.contains(TAG_DEVICE_ID) || + !jsonObject.contains(TAG_SLICE_NUM)) { + LOGE("err json string, first time"); + return DM_FAILED; + } + authResponseContext_->deviceId = jsonObject[TAG_DEVICE_ID]; + authResponseContext_->authType = jsonObject[TAG_AUTH_TYPE]; + authResponseContext_->appDesc = jsonObject[TAG_APP_DESCRIPTION]; + authResponseContext_->token = jsonObject[TAG_TOKEN]; + authResponseContext_->targetPkgName = jsonObject[TAG_TARGET]; + authResponseContext_->appName = jsonObject[TAG_APP_NAME]; + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str()); + sliceNum = jsonObject[TAG_SLICE_NUM]; + if ((int32_t)authSplitJsonList_.size() < sliceNum) { + authSplitJsonList_.push_back(message); + } else { + ParseAuthRequestMessage(); + } + break; + case MSG_TYPE_RESP_AUTH: + ParseAuthResponseMessage(jsonObject); + break; + case MSG_TYPE_REQ_AUTH_TERMINATE: + ParseResponseFinishMessage(jsonObject); + break; + default: + break; + } + return DM_OK; +} + +void AuthMessageProcessor::ParseResponseFinishMessage(nlohmann::json &json) +{ + authResponseContext_->reply = json[TAG_REPLY]; +} + +void AuthMessageProcessor::ParseAuthResponseMessage(nlohmann::json &json) +{ + LOGI("AuthMessageProcessor::ParseAuthResponseMessage "); + authResponseContext_->reply = json[TAG_REPLY]; + authResponseContext_->deviceId = json[TAG_DEVICE_ID]; + authResponseContext_->token = json[TAG_TOKEN]; + // authResponseContext_->deviceId = json[TAG_GROUPIDS]; + if (authResponseContext_->reply == 0) { + authResponseContext_->code = json[PIN_CODE_KEY]; + authResponseContext_->networkId = json[TAG_NET_ID]; + authResponseContext_->requestId = json[TAG_REQUEST_ID]; + authResponseContext_->groupId = json[TAG_GROUP_ID]; + authResponseContext_->groupName = json[TAG_GROUP_NAME]; + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s", authResponseContext_->groupId.c_str(), + authResponseContext_->groupName.c_str()); + } + LOGI("AuthMessageProcessor::ParseAuthResponseMessage "); +} + +void AuthMessageProcessor::ParseAuthRequestMessage() +{ + nlohmann::json jsonObject = authSplitJsonList_.front(); + authResponseContext_->deviceId = jsonObject[TAG_DEVICE_ID]; + authResponseContext_->reply = jsonObject[TAG_REPLY]; + // authResponseContext_->syncGroupList = jsonObject[TAG_GROUPIDS]; + authResponseContext_->authType = jsonObject[TAG_AUTH_TYPE]; + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %d,%d", authResponseContext_->reply); + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str()); + if (authResponseContext_->reply == AUTH_REPLY_ACCEPT) { + authResponseContext_->networkId = jsonObject[TAG_NET_ID]; + authResponseContext_->groupId = jsonObject[TAG_GROUP_ID]; + authResponseContext_->groupName = jsonObject[TAG_GROUP_NAME]; + authResponseContext_->requestId = jsonObject[TAG_REQUEST_ID]; + } + authSplitJsonList_.clear(); +} + +void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) +{ + if (json.contains(TAG_CRYPTO_SUPPORT)) { + authResponseContext_->cryptoSupport = json[TAG_CRYPTO_SUPPORT]; + } + if (json.contains(TAG_CRYPTO_NAME)) { + authResponseContext_->cryptoSupport = json[TAG_CRYPTO_NAME]; + } + if (json.contains(TAG_CRYPTO_VERSION)) { + authResponseContext_->cryptoSupport = json[TAG_CRYPTO_VERSION]; + } + if (json.contains(TAG_DEVICE_ID)) { + authResponseContext_->deviceId = json[TAG_DEVICE_ID]; + } + authResponseContext_->localDeviceId = json[TAG_LOCAL_DEVICE_ID]; + authResponseContext_->reply = json[TAG_REPLY]; +} + +void AuthMessageProcessor::SetRequestContext(std::shared_ptr authRequestContext) +{ + authRequestContext_ = authRequestContext; +} + +void AuthMessageProcessor::SetResponseContext(std::shared_ptr authResponseContext) +{ + authResponseContext_ = authResponseContext; +} + +std::shared_ptr AuthMessageProcessor::GetResponseContext() +{ + return authResponseContext_; +} + +std::shared_ptr AuthMessageProcessor::GetRequestContext() +{ + return authRequestContext_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/authentication/auth_request_state.cpp b/services/devicemanagerservice/src/authentication/auth_request_state.cpp new file mode 100644 index 000000000..1323b4e6d --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -0,0 +1,205 @@ +/* + * 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 "auth_request_state.h" + +#include + +#include "dm_auth_manager.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +void AuthRequestState::Leave() +{ +} + +void AuthRequestState::SetAuthManager(std::shared_ptr authManager) +{ + authManager_ = std::move(authManager); +} + +// void AuthRequestState::SetLastState(std::shared_ptr state) { +// lastState_ = state; +// } + +void AuthRequestState::SetAuthContext(std::shared_ptr context) +{ + context_ = std::move(context); +} + +std::shared_ptr AuthRequestState::GetAuthContext() +{ + return context_; +} + +void AuthRequestState::TransitionTo(std::shared_ptr state) +{ + LOGE("AuthRequestState::TransitionTo"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + state->SetAuthManager(stateAuthManager); + stateAuthManager->SetAuthRequestState(state); + state->SetAuthContext(context_); + this->Leave(); + state->Enter(); +} + +int32_t AuthRequestInitState::GetStateType() +{ + return AuthState::AUTH_REQUEST_INIT; +} + +void AuthRequestInitState::Enter() +{ + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->EstablishAuthChannel(context_->deviceId); +} + +int32_t AuthRequestNegotiateState::GetStateType() +{ + return AuthState::AUTH_REQUEST_NEGOTIATE; +} + +void AuthRequestNegotiateState::Enter() +{ + // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->StartNegotiate(context_->sessionId); +} + +int32_t AuthRequestNegotiateDoneState::GetStateType() +{ + return AuthState::AUTH_REQUEST_NEGOTIATE_DONE; +} + +void AuthRequestNegotiateDoneState::Enter() +{ + // //1. 获取对端加解密信息,并对比两端状态 + // + // //2. 保存加解密状态,发送认证请求 + // authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH); + // std::string message; + // softbusSession_->SendData(context_.sessionId, message); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->SendAuthRequest(context_->sessionId); +} + +int32_t AuthRequestReplyState::GetStateType() +{ + return AuthState::AUTH_REQUEST_REPLY; +} + +void AuthRequestReplyState::Enter() +{ + // 1. 收到请求响应,判断用户响应结果 + + // 2. 用户授权同意 + + // 3. 回调给认证实现模块,启动认证 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->StartRespAuthProcess(); +} + +int32_t AuthRequestInputState::GetStateType() +{ + return AuthState::AUTH_REQUEST_INPUT; +} + +void AuthRequestInputState::Enter() +{ + // //1. 获取用户输入 + // + // //2. 验证认证信息 + LOGE("DmAuthManager::AuthRequestInputState"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->ShowStartAuthDialog(); +} + +int32_t AuthRequestJoinState::GetStateType() +{ + return AuthState::AUTH_REQUEST_JOIN; +} + +void AuthRequestJoinState::Enter() +{ + // 1. 加入群组 + LOGE("DmAuthManager::AuthRequestJoinState"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->AddMember(context_->deviceId); +} + +int32_t AuthRequestNetworkState::GetStateType() +{ + return AuthState::AUTH_REQUEST_NETWORK; +} + +void AuthRequestNetworkState::Enter() +{ + // 1. 进行组网 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->JoinNetwork(); +} + +int32_t AuthRequestFinishState::GetStateType() +{ + return AuthState::AUTH_REQUEST_FINISH; +} + +void AuthRequestFinishState::Enter() +{ + // 1. 清理资源 + // 2. 通知对端认证结束,并关闭认证通道 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->AuthenticateFinish(); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp new file mode 100644 index 000000000..10c4c17f1 --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -0,0 +1,159 @@ +/* + * 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 "auth_response_state.h" + +#include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +void AuthResponseState::Leave() +{ +} + +void AuthResponseState::SetAuthContext(std::shared_ptr context) +{ + context_ = std::move(context); +} + +std::shared_ptr AuthResponseState::GetAuthContext() +{ + return context_; +} + +void AuthResponseState::SetAuthManager(std::shared_ptr authManager) +{ + authManager_ = std::move(authManager); +} + +void AuthResponseState::TransitionTo(std::shared_ptr state) +{ + LOGI("AuthRequestState:: TransitionTo"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + state->SetAuthManager(stateAuthManager); + stateAuthManager->SetAuthResponseState(state); + state->SetAuthContext(context_); + this->Leave(); + state->Enter(); +} + +int32_t AuthResponseInitState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_INIT; +} + +void AuthResponseInitState::Enter() +{ + LOGI("AuthResponse:: AuthResponseInitState Enter"); + // 1.认证通道建立后,进入该状态 +} + +int32_t AuthResponseNegotiateState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_NEGOTIATE; +} + +void AuthResponseNegotiateState::Enter() +{ + // 1.收到协商消息后进入 + + // 2. 获取本地加解密模块信息,并回复消 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->RespNegotiate(context_->sessionId); +} + +int32_t AuthResponseConfirmState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_CONFIRM; +} + +void AuthResponseConfirmState::Enter() +{ + //委托授权UI模块进行用户交互 + //如果交互成功 + // TransitionTo(new AuthResponseGroupState()); + LOGI("AuthResponse:: AuthResponseConfirmState Enter"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->ShowConfigDialog(); +} + +int32_t AuthResponseGroupState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_GROUP; +} + +void AuthResponseGroupState::Enter() +{ + // //1.创建群组, + // authManagerPtr_->GetHiChainConnector()->CreateGroup(); + LOGI("AuthResponse:: AuthResponseGroupState Enter"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->CreateGroup(); +} + +int32_t AuthResponseShowState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_SHOW; +} + +void AuthResponseShowState::Enter() +{ + // 1.委托认证实现模块进行用户交互 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->ShowAuthInfoDialog(); +} + +int32_t AuthResponseFinishState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_FINISH; +} + +void AuthResponseFinishState::Enter() +{ + // 1.结束UI显示 + + // 2.清理资源,结束状态机 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->AuthenticateFinish(); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp new file mode 100644 index 000000000..b3afce453 --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "auth_ui.h" + +#include "dm_ability_manager.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +AuthUi::AuthUi() +{ + LOGI("AuthUi constructor"); +} + +int32_t AuthUi::ShowConfirmDialog(std::shared_ptr dmAbilityManager) +{ + if (dmAbilityManager == nullptr) { + LOGE("AuthUi::dmAbilityManager is null"); + return DM_FAILED; + } + dmAbilityMgr_ = dmAbilityManager; + return StartFaService(); +} + +int32_t AuthUi::StartFaService() +{ + AbilityStatus status = dmAbilityMgr_->StartAbility(AbilityRole::ABILITY_ROLE_PASSIVE); + if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { + LOGE("AuthUi::StartFaService timeout"); + return DM_FAILED; + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp new file mode 100644 index 000000000..dcce54d50 --- /dev/null +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -0,0 +1,754 @@ +/* + * 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_auth_manager.h" + +#include "auth_message_processor.h" +#include "auth_ui.h" +#include "config_manager.h" +#include "dm_ability_manager.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_random.h" +#include "nlohmann/json.hpp" +#include "parameter.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; +std::string NEGOTIATE_TIMEOUT_TASK = "negotiateTimeoutTask"; +std::string CONFIRM_TIMEOUT_TASK = "confirmTimeoutTask"; +std::string SHOW_TIMEOUT_TASK = "showTimeoutTask"; +std::string INPUT_TIMEOUT_TASK = "inputTimeoutTask"; +std::string ADD_TIMEOUT_TASK = "addTimeoutTask"; +std::string WAIT_NEGOTIATE_TIMEOUT_TASK = "waitNegotiateTimeoutTask"; +std::string WAIT_REQUEST_TIMEOUT_TASK = "waitRequestTimeoutTask"; + +int32_t SESSION_CANCEL_TIMEOUT = 0; +int32_t AUTHENTICATE_TIMEOUT = 120; +int32_t CONFIRM_TIMEOUT = 60; +int32_t NEGOTIATE_TIMEOUT = 10; +int32_t INPUT_TIMEOUT = 60; +int32_t ADD_TIMEOUT = 10; +int32_t WAIT_NEGOTIATE_TIMEOUT = 10; +int32_t WAIT_REQUEST_TIMEOUT = 10; +int32_t CANCEL_PICODE_DISPLAY = 1; +int32_t DEVICE_ID_HALF = 2; +} // namespace + +static void TimeOut(void *data) +{ + LOGE("time out "); + DmAuthManager *authMgr = (DmAuthManager *)data; + if (authMgr == nullptr) { + LOGE("time out error"); + return; + } + authMgr->HandleAuthenticateTimeout(); +} + +DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener) + : softbusConnector_(softbusConnector), listener_(listener) +{ + LOGI("DmAuthManager constructor"); + // TODO: load library so for different auth type + hiChainConnector_ = std::make_shared(); + + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + dmConfigManager.GetAuthAdapter(authenticationMap_); +} + +DmAuthManager::~DmAuthManager() +{ + LOGI("DmAuthManager destructor"); +} + +int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra) +{ + // TODO:检查pkgName的权限 + + // std::shared_ptr authentication = authenticationMap_[authType]; + // if (authentication == nullptr) { + // LOGE("DmAuthManager::AuthenticateDevice authType %d not support.", authType); + // return DM_AUTH_NOT_SUPPORT; + // } + LOGE("DmAuthManager::AuthenticateDevice is"); + if (authRequestState_ != nullptr && authResponseState_ != nullptr) { + LOGE("DmAuthManager::AuthenticateDevice %s is request authentication.", + authRequestState_->GetAuthContext()->hostPkgName.c_str()); + listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT, + std::to_string(DM_AUTH_BUSINESS_BUSY)); + return DM_AUTH_BUSINESS_BUSY; + } + + if (!softbusConnector_->HaveDeviceInMap(deviceId)) { + LOGE("AuthenticateDevice failed, the discoveryDeviceInfoMap_ not have this device"); + listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT, + std::to_string(DM_AUTH_INPUT_FAILED)); + return DM_AUTH_INPUT_FAILED; + } + if (extra.empty()) { + LOGE("AuthenticateDevice failed, extra is empty"); + listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT, + std::to_string(DM_AUTH_BUSINESS_BUSY)); + return DM_INPUT_PARA_EMPTY; + } + if (authType != AUTH_TYPE_PIN && authType != AUTH_TYPE_SCAN && authType != AUTH_TYPE_TOUCH) { + LOGE("AuthenticateDevice failed, authType is not support"); + listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT, + std::to_string(DM_AUTH_NOT_SUPPORT)); + return DM_AUTH_NOT_SUPPORT; + } + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(pkgName); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(pkgName, shared_from_this()); + + authMessageProcessor_ = std::make_shared(shared_from_this()); + authRequestContext_ = std::make_shared(); + authRequestContext_->hostPkgName = pkgName; + authRequestContext_->authType = authType; + authRequestContext_->deviceId = deviceId; + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (!jsonObject.is_discarded()) { + if (jsonObject.contains(TARGET_PKG_NAME_KEY)) { + authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY]; + } + if (jsonObject.contains(APP_NAME_KEY)) { + authRequestContext_->appName = jsonObject[APP_NAME_KEY]; + } + if (jsonObject.contains(APP_DESCRIPTION_KEY)) { + authRequestContext_->appDesc = jsonObject[APP_DESCRIPTION_KEY]; + } + if (jsonObject.contains(APP_THUMBNAIL)) { + authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL]; + } + if (jsonObject.contains(APP_ICON_KEY)) { + authRequestContext_->appIcon = jsonObject[APP_ICON_KEY]; + } + } + authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); + authRequestState_ = std::shared_ptr(new AuthRequestInitState()); + authRequestState_->SetAuthManager(shared_from_this()); + authRequestState_->SetAuthContext(authRequestContext_); + authRequestState_->Enter(); + std::shared_ptr authenticateStartTimer = std::make_shared(AUTHENTICATE_TIMEOUT_TASK); + timerMap_[AUTHENTICATE_TIMEOUT_TASK] = authenticateStartTimer; + authenticateStartTimer->Start(AUTHENTICATE_TIMEOUT, TimeOut, this); + LOGI("DmAuthManager::AuthenticateDevice complete"); + return DM_OK; +} + +int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) +{ + if (pkgName.empty()) { + LOGI(" DmAuthManager::UnAuthenticateDevice failed pkgName is null"); + return DM_FAILED; + } + + /* Get UDID by NetworkID */ + uint8_t udid[UDID_BUF_LEN] = {0}; + int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(deviceId.c_str(), NodeDeivceInfoKey::NODE_KEY_UDID, udid, + sizeof(udid)); + if (ret != DM_OK) { + LOGE("UnAuthenticateDevice GetNodeKeyInfo failed"); + return DM_FAILED; + } + std::string deviceUdid = (char *)udid; + + std::string groupId = ""; + std::vector groupList; + hiChainConnector_->GetRelatedGroups(deviceUdid, groupList); + if (groupList.size() > 0) { + groupId = groupList.front().groupId; + LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s, deviceUdid=%s", groupId.c_str(), + deviceId.c_str(), deviceUdid.c_str()); + hiChainConnector_->DeleteGroup(groupId); + } else { + LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0"); + return DM_FAILED; + } + // groupId = authResponseContext_->groupId; + return DM_OK; +} + +int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) +{ + LOGI("DmAuthManager::VerifyAuthentication"); + timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + + std::shared_ptr ptr; + if (authenticationMap_.find(1) == authenticationMap_.end()) { + LOGE("DmAuthManager::authenticationMap_ is null"); + return DM_FAILED; + } + ptr = authenticationMap_[1]; + + int32_t ret = ptr->VerifyAuthentication(authRequestContext_->token, authResponseContext_->code, authParam); + switch (ret) { + case DM_OK: + { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); + } + break; + case DM_AUTH_INPUT_FAILED: + { + std::string flag = ""; + listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, + DM_AUTH_INPUT_FAILED, flag); + } + break; + default: + { + CancelDisplay(); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } + } + + LOGI("DmAuthManager::VerifyAuthentication complete"); + return DM_OK; +} + +void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("DmAuthManager::OnSessionOpened sessionId=%d result=%d", sessionId, result); + if (sessionSide == AUTH_SESSION_SIDE_SERVER) { + if (authResponseState_ == nullptr) { + authMessageProcessor_ = std::make_shared(shared_from_this()); + authResponseState_ = std::shared_ptr(new AuthResponseInitState()); + authResponseState_->SetAuthManager(shared_from_this()); + authResponseState_->Enter(); + hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this()); + authResponseContext_ = std::make_shared(); + std::shared_ptr waitStartTimer = std::make_shared(WAIT_NEGOTIATE_TIMEOUT_TASK); + timerMap_[WAIT_NEGOTIATE_TIMEOUT_TASK] = waitStartTimer; + waitStartTimer->Start(WAIT_NEGOTIATE_TIMEOUT, TimeOut, this); + std::shared_ptr authenticateStartTimer = std::make_shared(AUTHENTICATE_TIMEOUT_TASK); + timerMap_[AUTHENTICATE_TIMEOUT_TASK] = authenticateStartTimer; + authenticateStartTimer->Start(AUTHENTICATE_TIMEOUT, TimeOut, this); + } else { + std::shared_ptr authMessageProcessor = + std::make_shared(shared_from_this()); + std::shared_ptr authResponseContext = std::make_shared(); + authResponseContext->reply = AuthState::AUTH_RESPONSE_INIT; + authMessageProcessor->SetResponseContext(authResponseContext); + std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + } + } else { + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this()); + authRequestContext_->sessionId = sessionId; + authRequestState_->SetAuthContext(authRequestContext_); + authMessageProcessor_->SetRequestContext(authRequestContext_); + authResponseContext_ = std::make_shared(); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); + } else { + LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType()); + } + } +} + +void DmAuthManager::OnSessionClosed(const std::string &pkgName, int32_t sessionId) +{ + LOGI("DmAuthManager::OnSessionOpened sessionId=%d", sessionId); +} + +void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message) +{ + LOGI("DmAuthManager::OnDataReceived start"); + if (authRequestState_ == nullptr && authResponseState_ == nullptr) { + LOGI("DmAuthManager::GetAuthState failed"); + return; + } + authResponseContext_->sessionId = sessionId; + authMessageProcessor_->SetResponseContext(authResponseContext_); + int32_t ret = authMessageProcessor_->ParseMessage(message); + if (ret != DM_OK) { + LOGE("OnDataReceived, parse message error"); + return; + } + authResponseContext_ = authMessageProcessor_->GetResponseContext(); + if (authResponseState_ == nullptr) { + authRequestContext_ = authMessageProcessor_->GetRequestContext(); + authRequestState_->SetAuthContext(authRequestContext_); + } else { + authResponseState_->SetAuthContext(authResponseContext_); + } + switch (authResponseContext_->msgType) { + case MSG_TYPE_NEGOTIATE: + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { + timerMap_[WAIT_NEGOTIATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); + } else { + LOGE("Device manager auth state error"); + } + break; + case MSG_TYPE_REQ_AUTH: + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { + timerMap_[WAIT_REQUEST_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseConfirmState())); + } else { + LOGE("Device manager auth state error"); + } + break; + case MSG_TYPE_RESP_AUTH: + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestReplyState())); + } else { + LOGE("Device manager auth state error"); + } + break; + case MSG_TYPE_RESP_NEGOTIATE: + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateDoneState())); + } else { + LOGE("Device manager auth state error"); + } + break; + case MSG_TYPE_REQ_AUTH_TERMINATE: + if (authResponseState_ != nullptr && + authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); + } else if (authRequestState_ != nullptr && + authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { + LOGE("Device manager auth state error"); + } + break; + default: + break; + } +} + +void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId) +{ + //创建群组成功 + //发送认证响应消息给请求端 + LOGI("DmAuthManager::OnGroupCreated start"); + if (authResponseState_ == nullptr) { + LOGI("DmAuthManager::AuthenticateDevice end"); + return; + } + if (groupId == "{}") { + authResponseContext_->reply = DM_HICHAIN_GROUP_CREATE_FAILED; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + return; + } + authResponseContext_->groupId = groupId; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseShowState())); +} + +void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) +{ + LOGI("DmAuthManager OnMemberJoin start"); + CancelDisplay(); + + LOGE("DmAuthManager OnMemberJoin start"); + if (authRequestState_ != nullptr) { + timerMap_[ADD_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + if (status != DM_OK || authResponseContext_->requestId != requestId) { + if (authRequestState_ == nullptr) { + // authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); + } else { + authResponseContext_->reply = AuthState::AUTH_REQUEST_JOIN; + authRequestContext_->reason = DM_AUTH_INPUT_FAILED; + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + return; + } + } + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNetworkState())); + } +} + +void DmAuthManager::HandleAuthenticateTimeout() +{ + // 1. 状态机走到结束状态,并清理资源 + LOGI("DmAuthManager::HandleAuthenticateTimeout start"); + if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { + if (authResponseContext_ == nullptr) { + authResponseContext_ = std::make_shared(); + } + authResponseContext_->reply = authRequestState_->GetStateType(); + authRequestContext_->reason = DM_TIME_OUT; + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } + LOGI("DmAuthManager::HandleAuthenticateTimeout start complete"); +} + +void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) +{ + // TODO:检查crypto模块是否适配 + // TODO:兼容性处理,兼容与手机的认证 + int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + if (sessionId < 0) { + LOGE("OpenAuthSession failed, stop the authentication"); + authResponseContext_ = std::make_shared(); + authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE; + authRequestContext_->reason = DM_AUTH_OPEN_SESSION_FAILED; + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } +} + +void DmAuthManager::StartNegotiate(const int32_t &sessionId) +{ + LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + authResponseContext_->localDeviceId = localDeviceId; + authResponseContext_->reply = DM_AUTH_NOT_AUTH; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + std::shared_ptr negotiateStartTimer = std::make_shared(NEGOTIATE_TIMEOUT_TASK); + timerMap_[NEGOTIATE_TIMEOUT_TASK] = negotiateStartTimer; + negotiateStartTimer->Start(NEGOTIATE_TIMEOUT, TimeOut, this); +} + +void DmAuthManager::RespNegotiate(const int32_t &sessionId) +{ + LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, localDeviceId); + if (ret != true){ + LOGE("DmAuthManager::EstablishAuthChannel device is in group"); + authResponseContext_->reply = DM_AUTH_PEER_REJECT; + } else { + authResponseContext_->reply = DM_AUTH_NOT_AUTH; + } + + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + } + authResponseContext_ = authResponseState_->GetAuthContext(); + if (jsonObject[TAG_CRYPTO_SUPPORT] == "true" && authResponseContext_->cryptoSupport == true) { + if (jsonObject[TAG_CRYPTO_NAME] == authResponseContext_->cryptoName && + jsonObject[TAG_CRYPTO_VERSION] == authResponseContext_->cryptoVer) { + isCryptoSupport_ = true; + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + return; + } + } + jsonObject[TAG_CRYPTO_SUPPORT] = "false"; + message = jsonObject.dump(); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + std::shared_ptr waitStartTimer = std::make_shared(WAIT_REQUEST_TIMEOUT_TASK); + timerMap_[WAIT_REQUEST_TIMEOUT_TASK] = waitStartTimer; + waitStartTimer->Start(WAIT_REQUEST_TIMEOUT, TimeOut, this); +} + +void DmAuthManager::SendAuthRequest(const int32_t &sessionId) +{ + LOGE("DmAuthManager::EstablishAuthChannel session id"); + timerMap_[NEGOTIATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + if (authResponseContext_->cryptoSupport == true) { + isCryptoSupport_ = true; + } + + if (authResponseContext_->reply == DM_AUTH_PEER_REJECT) { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + return; + } + + std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); + for (auto msg : messageList) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + } + std::shared_ptr confirmStartTimer = std::make_shared(CONFIRM_TIMEOUT_TASK); + timerMap_[CONFIRM_TIMEOUT_TASK] = confirmStartTimer; + confirmStartTimer->Start(CONFIRM_TIMEOUT, TimeOut, this); +} + +void DmAuthManager::StartAuthProcess(const int32_t &action) +{ + // 1. 收到请求响应,判断用户响应结果 + // 2. 用户授权同意 + // 3. 回调给认证实现模块,启动认证 + LOGI("DmAuthManager:: StartAuthProcess"); + authResponseContext_->reply = action; + if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH && + authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseGroupState())); + } else { + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + } +} + +void DmAuthManager::StartRespAuthProcess() +{ + LOGI("DmAuthManager::StartRespAuthProcess StartRespAuthProcess", authResponseContext_->sessionId); + timerMap_[CONFIRM_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { + std::shared_ptr inputStartTimer = std::make_shared(INPUT_TIMEOUT_TASK); + timerMap_[INPUT_TIMEOUT_TASK] = inputStartTimer; + inputStartTimer->Start(INPUT_TIMEOUT, TimeOut, this); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestInputState())); + } else { + LOGE("do not accept"); + authResponseContext_->reply = AuthState::AUTH_REQUEST_REPLY; + authRequestContext_->reason = DM_AUTH_PEER_REJECT; + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } +} + +void DmAuthManager::CreateGroup() +{ + LOGI("DmAuthManager:: CreateGroup"); + authResponseContext_->groupName = GenerateGroupName(); + authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); + hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName); +} + +void DmAuthManager::AddMember(const std::string &deviceId) +{ + LOGI("DmAuthManager::AddMember start"); + nlohmann::json jsonObject; + jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId; + jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName; + jsonObject[PIN_CODE_KEY] = authResponseContext_->code; + jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; + jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; + std::string connectInfo = jsonObject.dump(); + std::shared_ptr joinStartTimer = std::make_shared(ADD_TIMEOUT_TASK); + timerMap_[ADD_TIMEOUT_TASK] = joinStartTimer; + joinStartTimer->Start(ADD_TIMEOUT, TimeOut, this); + int32_t ret = hiChainConnector_->AddMember(deviceId, connectInfo); + if (ret != 0) { + return; + } + LOGI("DmAuthManager::authRequestContext CancelDisplay start"); + CancelDisplay(); +} + +std::string DmAuthManager::GetConnectAddr(std::string deviceId) +{ + LOGI("DmAuthManager::GetConnectAddr"); + std::string connectAddr; + softbusConnector_->GetConnectAddr(deviceId, connectAddr); + return connectAddr; +} + +void DmAuthManager::JoinNetwork() +{ + // TODO: + LOGE("DmAuthManager JoinNetwork start"); + timerMap_[AUTHENTICATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + authResponseContext_->reply = AuthState::AUTH_REQUEST_FINISH; + authRequestContext_->reason = DM_OK; + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); +} + +void DmAuthManager::AuthenticateFinish() +{ + LOGI("DmAuthManager::AuthenticateFinish start"); + if (authResponseState_ != nullptr) { + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { + CancelDisplay(); + } + if (!timerMap_.empty()) { + for (auto &iter : timerMap_) { + iter.second->Stop(SESSION_CANCEL_TIMEOUT); + } + timerMap_.clear(); + } + authResponseContext_ = nullptr; + authResponseState_ = nullptr; + authMessageProcessor_ = nullptr; + } else if (authRequestState_ != nullptr) { + std::string flag = ""; + if (authResponseContext_->reply < AuthState::AUTH_RESPONSE_INIT) { + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + } + + + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT) { + CancelDisplay(); + } + + listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, + authRequestContext_->token, authResponseContext_->reply, + std::to_string(authRequestContext_->reason)); + + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(authRequestContext_->hostPkgName); + softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); + if (!timerMap_.empty()) { + for (auto &iter : timerMap_) { + iter.second->Stop(SESSION_CANCEL_TIMEOUT); + } + timerMap_.clear(); + } + authRequestContext_ = nullptr; + authResponseContext_ = nullptr; + authRequestState_ = nullptr; + authMessageProcessor_ = nullptr; + } + LOGI("DmAuthManager::AuthenticateFinish complete"); +} + +void DmAuthManager::CancelDisplay() +{ + LOGI("DmAuthManager::CancelDisplay start"); + nlohmann::json jsonObj; + jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PICODE_DISPLAY; + std::string paramJson = jsonObj.dump(); + std::string pkgName = "com.ohos.devicemanagerui"; + listener_->OnFaCall(pkgName, paramJson); +} + +int32_t DmAuthManager::GeneratePincode() +{ + return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); +} + +std::string DmAuthManager::GenerateGroupName() +{ + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string sLocalDeviceID = localDeviceId; + std::string groupName = authResponseContext_->targetPkgName + authResponseContext_->hostPkgName + + sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); + return groupName; +} + +void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) +{ + LOGI("DmAuthManager::GetIsCryptoSupport start"); + if (authResponseState_ == nullptr) { + isCryptoSupport = false; + return; + } + if (authRequestState_ == nullptr) { + if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + isCryptoSupport = false; + return; + } + } else { + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + isCryptoSupport = false; + return; + } + } + + isCryptoSupport = isCryptoSupport_; +} + +void DmAuthManager::SetAuthRequestState(std::shared_ptr authRequestState) +{ + authRequestState_ = authRequestState; +} + +void DmAuthManager::SetAuthResponseState(std::shared_ptr authResponseState) +{ + authResponseState_ = authResponseState; +} + +int32_t DmAuthManager::GetPinCode() +{ + return authResponseContext_->code; +} + +void DmAuthManager::ShowConfigDialog() +{ + std::shared_ptr authUi_ = std::make_shared(); + dmAbilityMgr_ = std::make_shared(); + authUi_->ShowConfirmDialog(dmAbilityMgr_); +} + +void DmAuthManager::ShowAuthInfoDialog() +{ + return; +} + +void DmAuthManager::ShowStartAuthDialog() +{ + LOGI("DmAuthManager::ShowStartAuthDialog start"); + dmAbilityMgr_ = std::make_shared(); + std::shared_ptr ptr; + if (authenticationMap_.find(1) == authenticationMap_.end()) { + LOGE("DmAuthManager::authenticationMap_ is null"); + return; + } + ptr = authenticationMap_[1]; + ptr->StartAuth(dmAbilityMgr_); +} + +int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) +{ + dmAbilityMgr_->StartAbilityDone(); + AbilityRole role = dmAbilityMgr_->GetAbilityRole(); + authParam.direction = (int32_t)role; + // Currently, only Support PinCode, authType not save. + authParam.authType = AUTH_TYPE_PIN; + authParam.authToken = authResponseContext_->token; + + if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { + // 生成pincode + authResponseContext_->code = GeneratePincode(); + authParam.packageName = authResponseContext_->targetPkgName; + authParam.appName = authResponseContext_->appName; + authParam.appDescription = authResponseContext_->appDesc; + // currently, only support BUSINESS_FA_MIRGRATION + authParam.business = BUSINESS_FA_MIRGRATION; + // 获取生成的pincode + authParam.pincode = authResponseContext_->code; + } + return DM_OK; +} + +int32_t DmAuthManager::RegisterSessionCallback() +{ + LOGI("DmAuthManager constructor111"); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(DM_PKG_NAME, shared_from_this()); + return DM_OK; +} + +int32_t DmAuthManager::OnUserOperation(int32_t action) +{ + switch (action) + { + case USER_OPERATION_TYPE_ALLOW_AUTH: + case USER_OPERATION_TYPE_CANCEL_AUTH: + StartAuthProcess(action); + break; + case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: + AuthenticateFinish(); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: + CancelDisplay(); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: + AuthenticateFinish(); + break; + default: + LOGE("this action id not support"); + break; + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/config/config_manager.cpp b/services/devicemanagerservice/src/config/config_manager.cpp new file mode 100644 index 000000000..76b77a308 --- /dev/null +++ b/services/devicemanagerservice/src/config/config_manager.cpp @@ -0,0 +1,299 @@ +/* + * 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 "config_manager.h" + +#include + +#include "dm_constants.h" +#include "dm_log.h" +#include "json_config.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +void from_json(const nlohmann::json &jsonObject, AdapterSoLoadInfo &soLoadInfo) +{ + if (!jsonObject.contains("name") || !jsonObject.contains("type") || !jsonObject.contains("version") || + !jsonObject.contains("funcName") || !jsonObject.contains("soName") || !jsonObject.contains("soPath")) { + LOGE("AdapterSoLoadInfo json key Not complete"); + return; + } + + jsonObject["name"].get_to(soLoadInfo.name); + jsonObject["type"].get_to(soLoadInfo.type); + jsonObject["version"].get_to(soLoadInfo.version); + jsonObject["funcName"].get_to(soLoadInfo.funcName); + jsonObject["soName"].get_to(soLoadInfo.soName); + jsonObject["soPath"].get_to(soLoadInfo.soPath); +} + +void from_json(const nlohmann::json &jsonObject, AuthSoLoadInfo &soLoadInfo) +{ + if (!jsonObject.contains("name") || !jsonObject.contains("type") || !jsonObject.contains("version") || + !jsonObject.contains("funcName") || !jsonObject.contains("soName") || !jsonObject.contains("soPath") || + !jsonObject.contains("authType")) { + LOGE("AuthSoLoadInfo json key Not complete"); + return; + } + + jsonObject["name"].get_to(soLoadInfo.name); + jsonObject["type"].get_to(soLoadInfo.type); + jsonObject["version"].get_to(soLoadInfo.version); + jsonObject["authType"].get_to(soLoadInfo.authType); + jsonObject["funcName"].get_to(soLoadInfo.funcName); + jsonObject["soName"].get_to(soLoadInfo.soName); + jsonObject["soPath"].get_to(soLoadInfo.soPath); +} + +DmConfigManager &DmConfigManager::GetInstance() +{ + static DmConfigManager instance; + return instance; +} + +DmConfigManager::DmConfigManager() +{ + LOGI("DmConfigManager constructor"); + do { + nlohmann::json adapterJsonObject = nlohmann::json::parse(adapterJsonConfigString, nullptr, false); + if (adapterJsonObject.is_discarded()) { + LOGE("adapter json config string parse error"); + break; + } + const char *jsonKey = ADAPTER_LOAD_JSON_KEY.c_str(); + if (!adapterJsonObject.contains(jsonKey)) { + LOGE("adapter json config string key not exist"); + break; + } + auto soLoadInfo = adapterJsonObject[jsonKey].get>(); + for (uint32_t i = 0; i < soLoadInfo.size(); i++) { + if (soLoadInfo[i].name.size() == 0 || soLoadInfo[i].type.size() == 0 || soLoadInfo[i].version.size() == 0 || + soLoadInfo[i].funcName.size() == 0 || soLoadInfo[i].soName.size() == 0 || + soLoadInfo[i].soPath.size() == 0) { + LOGE("adapter json config string exist invalid members"); + continue; + } + soAdapterLoadInfo_[soLoadInfo[i].soName] = soLoadInfo[i]; + LOGI("soAdapterLoadInfo name is: %s", soLoadInfo[i].name.c_str()); + LOGI("soAdapterLoadInfo type is: %s", soLoadInfo[i].type.c_str()); + LOGI("soAdapterLoadInfo version is: %s", soLoadInfo[i].version.c_str()); + LOGI("soAdapterLoadInfo funcName is: %s", soLoadInfo[i].funcName.c_str()); + LOGI("soAdapterLoadInfo soName is: %s", soLoadInfo[i].soName.c_str()); + LOGI("soAdapterLoadInfo soPath is: %s", soLoadInfo[i].soPath.c_str()); + } + } while (0); + + do { + nlohmann::json authJsonObject = nlohmann::json::parse(authJsonConfigString, nullptr, false); + if (authJsonObject.is_discarded()) { + LOGE("auth json config string parse error!\n"); + break; + } + const char *jsonKey = AUTH_LOAD_JSON_KEY.c_str(); + if (!authJsonObject.contains(jsonKey)) { + LOGE("auth json config string key not exist!\n"); + break; + } + auto soLoadInfo = authJsonObject[jsonKey].get>(); + for (uint32_t i = 0; i < soLoadInfo.size(); i++) { + if (soLoadInfo[i].name.size() == 0 || soLoadInfo[i].type.size() == 0 || soLoadInfo[i].version.size() == 0 || + soLoadInfo[i].funcName.size() == 0 || soLoadInfo[i].soName.size() == 0 || + soLoadInfo[i].soPath.size() == 0) { + LOGE("adapter json config string exist invalid members"); + continue; + } + soAuthLoadInfo_[soLoadInfo[i].authType] = soLoadInfo[i]; + LOGI("soAuthLoadInfo name is: %s", soLoadInfo[i].name.c_str()); + LOGI("soAuthLoadInfo type is: %s", soLoadInfo[i].type.c_str()); + LOGI("soAuthLoadInfo version is: %s", soLoadInfo[i].version.c_str()); + LOGI("soAuthLoadInfo funcName is: %s", soLoadInfo[i].funcName.c_str()); + LOGI("soAuthLoadInfo soName is: %s", soLoadInfo[i].soName.c_str()); + LOGI("soAuthLoadInfo soPath is: %s", soLoadInfo[i].soPath.c_str()); + LOGI("soAuthLoadInfo authType is: %d", soLoadInfo[i].authType); + } + } while (0); +} + +DmConfigManager::~DmConfigManager() +{ + void *so_handle = nullptr; + for (auto iter = soAdapterLoadInfo_.begin(); iter != soAdapterLoadInfo_.end(); iter++) { + std::string soPathName = (iter->second).soPath + (iter->second).soName; + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle != nullptr) { + dlclose(so_handle); + } + } + for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) { + std::string soPathName = (iter->second).soPath + (iter->second).soName; + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle != nullptr) { + dlclose(so_handle); + } + } + LOGI("DmAdapterManager destructor"); +} + +std::shared_ptr DmConfigManager::GetDecisionAdapter(const std::string &soName) +{ + if (soName.empty()) { + LOGE("soName size is zero"); + return nullptr; + } + auto soInfoIter = soAdapterLoadInfo_.find(soName); + if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != DECISION_JSON_TYPE_KEY) { + LOGE("not find so info or type key not match"); + return nullptr; + } + std::unique_lock locker(decisionAdapterMutex_); + auto ptrIter = decisionAdapterPtr_.find(soName); + if (ptrIter != decisionAdapterPtr_.end()) { + return decisionAdapterPtr_[soName]; + } + void *so_handle = nullptr; + std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName; + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(soPathName.c_str(), RTLD_NOW); + if (so_handle == nullptr) { + LOGE("load decision so %s failed", soName.c_str()); + return nullptr; + } + } + dlerror(); + auto func = (CreateIDecisionAdapterFuncPtr)dlsym(so_handle, (soInfoIter->second).funcName.c_str()); + if (dlerror() != nullptr || func == nullptr) { + LOGE("Create object function is not exist"); + return nullptr; + } + std::shared_ptr iDecisionAdapter(func()); + decisionAdapterPtr_[soName] = iDecisionAdapter; + return decisionAdapterPtr_[soName]; +} + +std::shared_ptr DmConfigManager::GetProfileAdapter(const std::string &soName) +{ + if (soName.empty()) { + LOGE("soName size is zero"); + return nullptr; + } + + auto soInfoIter = soAdapterLoadInfo_.find(soName); + if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != PROFILE_JSON_TYPE_KEY) { + LOGE("not find so info or type key not match"); + return nullptr; + } + std::unique_lock locker(profileAdapterMutex_); + auto ptrIter = profileAdapterPtr_.find(soName); + if (ptrIter != profileAdapterPtr_.end()) { + return profileAdapterPtr_[soName]; + } + void *so_handle = nullptr; + std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName; + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(soPathName.c_str(), RTLD_NOW); + if (so_handle == nullptr) { + LOGE("load profile so %s failed", soName.c_str()); + return nullptr; + } + } + dlerror(); + auto func = (CreateIProfileAdapterFuncPtr)dlsym(so_handle, (soInfoIter->second).funcName.c_str()); + if (dlerror() != nullptr || func == nullptr) { + LOGE("Create object function is not exist"); + return nullptr; + } + std::shared_ptr iProfileAdapter(func()); + profileAdapterPtr_[soName] = iProfileAdapter; + return profileAdapterPtr_[soName]; +} + +std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::string &soName) +{ + if (soName.empty()) { + LOGE("soName size is zero"); + return nullptr; + } + + auto soInfoIter = soAdapterLoadInfo_.find(soName); + if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != CPYPTO_JSON_TYPE_KEY) { + LOGE("not find so info or type key not match"); + return nullptr; + } + + std::unique_lock locker(cryptoAdapterMutex_); + auto ptrIter = cryptoAdapterPtr_.find(soName); + if (ptrIter != cryptoAdapterPtr_.end()) { + return cryptoAdapterPtr_[soName]; + } + + void *so_handle = nullptr; + std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName; + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(soPathName.c_str(), RTLD_NOW); + if (so_handle == nullptr) { + LOGE("load crypto so %s failed", soName.c_str()); + return nullptr; + } + } + + dlerror(); + auto func = (CreateICryptoAdapterFuncPtr)dlsym(so_handle, (soInfoIter->second).funcName.c_str()); + if (dlerror() != nullptr || func == nullptr) { + LOGE("Create object function is not exist"); + return nullptr; + } + + std::shared_ptr iCryptoAdapter(func()); + cryptoAdapterPtr_[soName] = iCryptoAdapter; + return cryptoAdapterPtr_[soName]; +} + +void DmConfigManager::GetAuthAdapter(std::map> &authAdapter) +{ + authAdapter.clear(); + for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) { + if ((iter->second).type != AUTH_JSON_TYPE_KEY) { + LOGE("type key not match"); + continue; + } + + void *so_handle = nullptr; + std::string soPathName = (iter->second).soPath + (iter->second).soName; + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(soPathName.c_str(), RTLD_NOW); + if (so_handle == nullptr) { + LOGE("load auth so %s failed", (iter->second).soName.c_str()); + continue; + } + } + + dlerror(); + auto func = (CreateIAuthAdapterFuncPtr)dlsym(so_handle, (iter->second).funcName.c_str()); + if (dlerror() != nullptr || func == nullptr) { + LOGE("Create object function is not exist"); + continue; + } + + std::shared_ptr iAuthentication(func()); + authAdapter[iter->first] = iAuthentication; + LOGI("so name: %s, auth type: %d", (iter->second).soName.c_str(), iter->first); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp b/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp new file mode 100644 index 000000000..91e7fba25 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "event_manager_adapt.h" + +#include + +#include "dm_constants.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace DistributedHardware { +std::once_flag DmCommonEventManager::onceFlag_; +std::list DmCommonEventManager::callbackQueue_; +std::mutex DmCommonEventManager::callbackQueueMutex_; +std::condition_variable DmCommonEventManager::notEmpty_; + +DmCommonEventManager &DmCommonEventManager::GetInstance() +{ + static DmCommonEventManager instance; + std::call_once(onceFlag_, [] { + std::thread th(DealCallback); + th.detach(); + }); + return instance; +} + +void DmCommonEventManager::DealCallback(void) +{ + while (1) { + std::unique_lock callbackQueueLock(callbackQueueMutex_); + notEmpty_.wait(callbackQueueLock, [] { return !callbackQueue_.empty(); }); + CommomEventCallback funcPrt = callbackQueue_.front(); + funcPrt(); + callbackQueue_.pop_front(); + } +} + +bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, CommomEventCallback callback) +{ + LOGI("Subscribe event: %s", event.c_str()); + if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end()) { + LOGE("Subscribe event:%s has been added", event.c_str()); + return false; + } + + MatchingSkills matchingSkills; + matchingSkills.AddEvent(event); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + std::shared_ptr subscriber = std::make_shared(subscriberInfo); + if (subscriber == nullptr) { + LOGE("subscriber is nullptr %s", event.c_str()); + return false; + } + subscriber->addEventCallback(event, callback); + + bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber); + if (subscribeResult) { + LOGE("Subscribe service event success: %s", event.c_str()); + dmEventSubscriber_[event] = subscriber; + return subscribeResult; + } else { + LOGE("Subscribe service event failed: %s", event.c_str()); + return false; + } +} + +bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event) +{ + LOGI("UnSubscribe event: %s", event.c_str()); + if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end()) { + LOGE("UnSubscribe event: %s not been exist", event.c_str()); + return false; + } + + bool unsubscribeResult = CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event]); + if (unsubscribeResult) { + LOGI("Unsubscribe service event success: %s", event.c_str()); + dmEventSubscriber_[event]->deleteEventCallback(event); + dmEventSubscriber_.erase(event); + return unsubscribeResult; + } else { + LOGE("Unsubscribe service event failed: %s", event.c_str()); + return false; + } +} + +DmCommonEventManager::~DmCommonEventManager() +{ + for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { + bool unsubscribeResult = CommonEventManager::UnSubscribeCommonEvent(iter->second); + if (unsubscribeResult) { + LOGI("Unsubscribe service event success: %s", iter->first.c_str()); + } + } +} + +void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + std::string event = data.GetWant().GetAction(); + LOGI("Received event: %s, value: %d", event.c_str()); + + std::unique_lock callbackLock(callbackLock_); + auto iter = dmEventCallback_.find(event); + if (iter != dmEventCallback_.end()) { + CommomEventCallback funcPrt = iter->second; + callbackLock_.unlock(); + + std::unique_lock callbackQueueLock(callbackQueueMutex_); + if (callbackQueue_.size() <= COMMON_CALLBACK_MAX_SIZE) { + callbackQueue_.push_back(funcPrt); + notEmpty_.notify_one(); + } else { + LOGE("event callback Queue is too long"); + } + } +} + +void DmCommonEventManager::EventSubscriber::addEventCallback(const std::string &event, CommomEventCallback callback) +{ + std::unique_lock callbackLock(callbackLock_); + if (dmEventCallback_.find(event) == dmEventCallback_.end()) { + dmEventCallback_[event] = callback; + LOGI("add event success: %s", event.c_str()); + } +} + +void DmCommonEventManager::EventSubscriber::deleteEventCallback(const std::string &event) +{ + std::unique_lock callbackLock(callbackLock_); + if (dmEventCallback_.find(event) != dmEventCallback_.end()) { + dmEventCallback_.erase(event); + LOGI("delete event failed: %s", event.c_str()); + } +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp new file mode 100644 index 000000000..551872517 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -0,0 +1,424 @@ +/* + * 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 "hichain_connector.h" + +#include + +#include +#include +#include + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_random.h" +#include "hichain_connector_callback.h" +#include "nlohmann/json.hpp" +#include "parameter.h" + +namespace OHOS { +namespace DistributedHardware { +void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo) +{ + if (jsonObject.find(FIELD_GROUP_NAME) != jsonObject.end()) { + groupInfo.groupName = jsonObject.at(FIELD_GROUP_NAME).get(); + } + + if (jsonObject.find(FIELD_GROUP_ID) != jsonObject.end()) { + groupInfo.groupId = jsonObject.at(FIELD_GROUP_ID).get(); + } + + if (jsonObject.find(FIELD_GROUP_OWNER) != jsonObject.end()) { + groupInfo.groupOwner = jsonObject.at(FIELD_GROUP_OWNER).get(); + } + + if (jsonObject.find(FIELD_GROUP_TYPE) != jsonObject.end()) { + groupInfo.groupType = jsonObject.at(FIELD_GROUP_TYPE).get(); + } + + if (jsonObject.find(FIELD_GROUP_VISIBILITY) != jsonObject.end()) { + groupInfo.groupVisibility = jsonObject.at(FIELD_GROUP_VISIBILITY).get(); + } +} + +std::map> HiChainConnector::hiChainConnectorCallbackMap_ = {}; + +HiChainConnector::HiChainConnector() +{ + LOGI("HiChainConnector::constructor"); + deviceAuthCallback_ = {.onTransmit = nullptr, + .onFinish = HiChainConnector::onFinish, + .onError = HiChainConnector::onError, + .onRequest = HiChainConnector::onRequest}; + InitDeviceAuthService(); + deviceGroupManager_ = GetGmInstance(); + if (deviceGroupManager_ == nullptr) { + LOGI("HiChainConnector::constructor, failed to init group manager!"); + return; + } + deviceGroupManager_->regCallback(DM_PKG_NAME.c_str(), &deviceAuthCallback_); + LOGI("HiChainConnector::constructor success."); +} + +HiChainConnector::~HiChainConnector() +{ + LOGI("HiChainConnector::destructor."); +} + +int32_t HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + hiChainConnectorCallbackMap_.emplace(pkgName, callback); + return DM_OK; +} + +int32_t HiChainConnector::UnRegisterHiChainCallback(const std::string &pkgName) +{ + hiChainConnectorCallbackMap_.erase(pkgName); + return DM_OK; +} + +int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &groupName) +{ + if (deviceGroupManager_ == nullptr) { + LOGE("HiChainConnector::CreateGroup group manager is null, requestId %lld.", requestId); + return DM_INVALID_VALUE; + } + GroupInfo groupInfo; + if (IsGroupCreated(groupName, groupInfo)) { + DeleteGroup(groupInfo.groupId); + } + LOGI("HiChainConnector::CreateGroup requestId %lld", requestId); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string sLocalDeviceID = localDeviceId; + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + jsonObj[FIELD_DEVICE_ID] = sLocalDeviceID; + jsonObj[FIELD_GROUP_NAME] = groupName; + jsonObj[FIELD_USER_TYPE] = 0; + jsonObj[FIELD_GROUP_VISIBILITY] = GROUP_VISIBILITY_PUBLIC; + jsonObj[FIELD_EXPIRE_TIME] = FIELD_EXPIRE_TIME_VALUE; + int32_t ret = deviceGroupManager_->createGroup(requestId, DM_PKG_NAME.c_str(), jsonObj.dump().c_str()); + if (ret != 0) { + LOGE("Failed to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); + return DM_HICHAIN_GROUP_CREATE_FAILED; + } + return DM_OK; +} + +bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInfo) +{ + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); + std::string queryParams = jsonObj.dump(); + std::vector groupList; + if (GetGroupInfo(queryParams, groupList)) { + groupInfo = groupList[0]; + return true; + } + return false; +} + +int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vector &groupList) +{ + char *groupVec = nullptr; + uint32_t num = 0; + + int32_t ret = deviceGroupManager_->getGroupInfo(DM_PKG_NAME.c_str(), queryParams.c_str(), &groupVec, &num); + if (ret != 0) { + LOGE("HiChainConnector::GetGroupInfo failed , ret: %d.", ret); + return false; + } + if (groupVec == nullptr) { + LOGE("HiChainConnector::GetGroupInfo failed , returnGroups is nullptr"); + return false; + } + if (num == 0) { + LOGE("HiChainConnector::GetGroupInfo group failed, groupNum is 0."); + return false; + } + LOGI("HiChainConnector::GetGroupInfo group(%s), groupNum(%d)", groupVec, num); + std::string relatedGroups = std::string(groupVec); + deviceGroupManager_->destroyInfo(&groupVec); + nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups); + if (jsonObject.is_discarded()) { + LOGE("returnGroups parse error"); + return false; + } + std::vector groupInfos = jsonObject.get>(); + if (groupInfos.size() == 0) { + LOGE("HiChainConnector::GetGroupInfo group failed, groupInfos is empty."); + return false; + } + groupList = groupInfos; + return true; +} + +int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectInfo) +{ + LOGI("HiChainConnector::AddMember"); + if (deviceGroupManager_ == nullptr) { + LOGI("HiChainConnector::AddMember group manager is null."); + return -1; + } + nlohmann::json jsonObject = nlohmann::json::parse(connectInfo, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string connectInfomation = GetConnectPara(deviceId, jsonObject[TAG_DEVICE_ID]); + + int32_t pinCode = jsonObject[PIN_CODE_KEY]; + std::string groupId = jsonObject[TAG_GROUP_ID]; + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = groupId; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str(); + jsonObj[FIELD_IS_ADMIN] = false; + jsonObj[FIELD_DEVICE_ID] = localDeviceId; + jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME]; + jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str(); + std::string tmpStr = jsonObj.dump(); + int64_t requestId = jsonObject[TAG_REQUEST_ID]; + // LOGI("HiChainConnector::AddMember completed requestId%d, jsonObject[TAG_GROUP_ID]%s ", requestId, + // groupId.c_str()); LOGI("HiChainConnector::AddMember completed DM_PKG_NAME %s", DM_PKG_NAME.c_str()); + // LOGI("HiChainConnector::AddMember completedtmpStr%s", tmpStr.c_str()); + int32_t ret = deviceGroupManager_->addMemberToGroup(requestId, DM_PKG_NAME.c_str(), tmpStr.c_str()); + LOGI("HiChainConnector::AddMember completed"); + return ret; +} + +void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) +{ + std::string data = ""; + if (returnData != nullptr) { + data = std::string(returnData); + } + LOGI("HiChainConnector::onFinish reqId:%lld, operation:%d", requestId, operationCode); + if (operationCode == GroupOperationCode::MEMBER_JOIN) { + LOGI("Add Member To Group success"); + for (auto &iter : hiChainConnectorCallbackMap_) { + iter.second->OnMemberJoin(requestId, DM_OK); + } + } + if (operationCode == GroupOperationCode::GROUP_CREATE) { + LOGI("Create group success"); + for (auto &iter : hiChainConnectorCallbackMap_) { + iter.second->OnGroupCreated(requestId, data); + } + } + if (operationCode == GroupOperationCode::MEMBER_DELETE) { + LOGI("Delete Member from group success"); + } + if (operationCode == GroupOperationCode::GROUP_DISBAND) { + LOGI("Disband group success"); + } +} + +void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn) +{ + (void)errorReturn; + LOGI("HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", requestId, operationCode, errorCode); + if (operationCode == GroupOperationCode::MEMBER_JOIN) { + LOGE("Add Member To Group failed"); + for (auto &iter : hiChainConnectorCallbackMap_) { + iter.second->OnMemberJoin(requestId, DM_FAILED); + } + } + if (operationCode == GroupOperationCode::GROUP_CREATE) { + LOGE("Create group failed"); + for (auto &iter : hiChainConnectorCallbackMap_) { + iter.second->OnGroupCreated(requestId, "{}"); + } + } + if (operationCode == GroupOperationCode::MEMBER_DELETE) { + LOGE("Delete Member from group failed"); + } + if (operationCode == GroupOperationCode::GROUP_DISBAND) { + LOGE("Disband group failed"); + } +} + +char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams) +{ + if (operationCode != GroupOperationCode::MEMBER_JOIN) { + LOGE("HiChainAuthCallBack::onRequest operationCode %d", operationCode); + return nullptr; + } + int32_t pinCode = 0; + for (auto &iter : hiChainConnectorCallbackMap_) { + pinCode = iter.second->GetPinCode(); + } + nlohmann::json jsonObj; + if (pinCode == DM_FAILED) { + jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; + } + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str(); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + jsonObj[FIELD_DEVICE_ID] = localDeviceId; + + std::string jsonStr = jsonObj.dump(); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + +int64_t HiChainConnector::GenRequestId() +{ + return GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); +} + +std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string reqDeviceId) +{ + std::string connectAddr = ""; + for (auto &iter : hiChainConnectorCallbackMap_) { + connectAddr = iter.second->GetConnectAddr(deviceId); + } + LOGE("HiChainConnector::GetConnectPara get addrInfo"); + nlohmann::json jsonObject = nlohmann::json::parse(connectAddr, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return connectAddr; + } + jsonObject[DEVICE_ID] = reqDeviceId; + + return jsonObject.dump(); +} + +void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList) +{ + LOGI("HiChainConnector::GetRelatedGroups Start to get local related groups."); + uint32_t groupNum = 0; + char *returnGroups = nullptr; + int32_t ret = + deviceGroupManager_->getRelatedGroups(DM_PKG_NAME.c_str(), deviceId.c_str(), &returnGroups, &groupNum); + if (ret != 0) { + LOGE("HiChainConnector::GetRelatedGroups faild , ret: %d.", ret); + return; + } + if (returnGroups == nullptr) { + LOGE("HiChainConnector::GetRelatedGroups failed , returnGroups is nullptr"); + return; + } + if (groupNum == 0) { + LOGE("HiChainConnector::GetRelatedGroups group failed, groupNum is 0."); + return; + } + std::string relatedGroups = std::string(returnGroups); + nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups); + if (jsonObject.is_discarded()) { + LOGE("returnGroups parse error"); + return; + } + std::vector groupInfos = jsonObject.get>(); + if (groupInfos.size() == 0) { + LOGE("HiChainConnector::GetRelatedGroups group failed, groupInfos is empty."); + return; + } + groupList = groupInfos; +} + +void HiChainConnector::GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList) +{ + if (groupList.empty()) { + LOGE("groupList is empty."); + return; + } + for (auto group : groupList) { + if (IsGroupInfoInvalid(group)) { + continue; + } + syncGroupList.push_back(group.groupId); + } +} + +bool HiChainConnector::IsDevicesInGroup(std::string hostDevice, std::string peerDevice) +{ + LOGE("HiChainConnector::IsDevicesInGroup"); + std::vector hostGroupInfoList; + GetRelatedGroups(hostDevice, hostGroupInfoList); + std::vector peerGroupInfoList; + GetRelatedGroups(peerDevice, peerGroupInfoList); + for (auto &hostGroupInfo : hostGroupInfoList) { + for (auto &peerGroupInfo : peerGroupInfoList) { + if (hostGroupInfo.groupId == peerGroupInfo.groupId && hostGroupInfo.groupName == peerGroupInfo.groupName) { + LOGE("these are authenticated"); + return false; + } + } + } + return true; +} + +bool HiChainConnector::IsGroupInfoInvalid(GroupInfo &group) +{ + if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC || + group.groupOwner != DM_PKG_NAME) { + return true; + } + return false; +} + +void HiChainConnector::SyncGroups(std::string deviceId, std::vector &remoteGroupIdList) +{ + std::vector groupInfoList; + GetRelatedGroups(deviceId, groupInfoList); + for (auto &groupInfo : groupInfoList) { + if (IsGroupInfoInvalid(groupInfo)) { + continue; + } + auto iter = std::find(remoteGroupIdList.begin(), remoteGroupIdList.end(), groupInfo.groupId); + if (iter == remoteGroupIdList.end()) { + (void)DelMemberFromGroup(groupInfo.groupId, deviceId); + } + } +} + +int32_t HiChainConnector::DelMemberFromGroup(std::string groupId, std::string deviceId) +{ + int64_t requestId = GenRequestId(); + LOGI("Start to delete memeber from group, requestId %lld, deviceId %s, groupId %s", requestId, + GetAnonyString(deviceId).c_str(), GetAnonyString(groupId).c_str()); + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = groupId; + jsonObj[FIELD_DELETE_ID] = deviceId; + std::string deleteParams = jsonObj.dump(); + int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DM_PKG_NAME.c_str(), deleteParams.c_str()); + if (ret != 0) { + LOGE("HiChainConnector::DelMemberFromGroup failed , ret: %d.", ret); + return ret; + } + return DM_OK; +} + +void HiChainConnector::DeleteGroup(std::string &groupId) +{ + int64_t requestId = GenRequestId(); + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = groupId; + std::string disbandParams = jsonObj.dump(); + int32_t ret = deviceGroupManager_->deleteGroup(requestId, DM_PKG_NAME.c_str(), disbandParams.c_str()); + if (ret != 0) { + LOGE("HiChainConnector::DeleteGroup failed , ret: %d.", ret); + } +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp new file mode 100644 index 000000000..475cef153 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -0,0 +1,561 @@ +/* + * 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 "softbus_connector.h" + +#include +#include + +#include +#include + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" +#include "parameter.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { + +SoftbusConnector::PulishStatus SoftbusConnector::publishStatus = SoftbusConnector::STATUS_UNKNOWN; +std::map> SoftbusConnector::discoveryDeviceInfoMap_ = {}; +std::map> SoftbusConnector::stateCallbackMap_ = {}; +std::map> SoftbusConnector::discoveryCallbackMap_ = {}; + +IPublishCallback SoftbusConnector::softbusPublishCallback_ = {.OnPublishSuccess = SoftbusConnector::OnPublishSuccess, + .OnPublishFail = SoftbusConnector::OnPublishFail}; + +IDiscoveryCallback SoftbusConnector::softbusDiscoveryCallback_ = { + .OnDeviceFound = SoftbusConnector::OnSoftbusDeviceFound, + .OnDiscoverFailed = SoftbusConnector::OnSoftbusDiscoveryFailed, + .OnDiscoverySuccess = SoftbusConnector::OnSoftbusDiscoverySuccess}; + +INodeStateCb SoftbusConnector::softbusNodeStateCb_ = { + .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED, + .onNodeOnline = SoftbusConnector::OnSoftBusDeviceOnline, + .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, + .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged}; + +SoftbusConnector::SoftbusConnector() +{ + softbusSession_ = std::make_shared(); + Init(); +} + +SoftbusConnector::~SoftbusConnector() +{ + LOGI("SoftbusConnector destructor"); +} + +int32_t SoftbusConnector::Init() +{ + int32_t ret; + int32_t retryTimes = 0; + do { + ret = RegNodeDeviceStateCb(DM_PKG_NAME.c_str(), &softbusNodeStateCb_); + if (ret != DM_OK) { + ++retryTimes; + LOGE("RegNodeDeviceStateCb failed with ret %d, retryTimes %d", ret, retryTimes); + usleep(SOFTBUS_CHECK_INTERVAL); + } + } while (ret != DM_OK); + LOGI("RegNodeDeviceStateCb success."); + + PublishInfo dmPublishInfo; + dmPublishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; + dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; + dmPublishInfo.medium = ExchanageMedium::AUTO; + dmPublishInfo.freq = ExchangeFreq::HIGH; + dmPublishInfo.capability = DM_CAPABILITY_OSD; + dmPublishInfo.capabilityData = nullptr; + dmPublishInfo.dataLen = 0; + + 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) { + ret = SetParameter(DISCOVER_STATUS_KEY.c_str(), DISCOVER_STATUS_ON.c_str()); + LOGI("service set poatrameter result is : %d", ret); + + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); + if (ret == DM_OK) { + publishStatus = ALLOW_BE_DISCOVERY; + } + LOGI("service publish result is : %d", ret); + } else if (ret >= 0 && strcmp(discoverStatus, DISCOVER_STATUS_ON.c_str()) == 0) { + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); + if (ret == DM_OK) { + publishStatus = ALLOW_BE_DISCOVERY; + } + LOGI("service publish result is : %d", ret); + } else if (ret >= 0 && strcmp(discoverStatus, DISCOVER_STATUS_OFF.c_str()) == 0) { + ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + if (ret == DM_OK) { + publishStatus = NOT_ALLOW_BE_DISCOVERY; + } + LOGI("service unpublish result is : %d", ret); + } + +// ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); + LOGI("register Watch Parameter result is : %d"); + return ret; +} + +int32_t SoftbusConnector::RegisterSoftbusDiscoveryCallback(const std::string &pkgName, + const std::shared_ptr callback) +{ + discoveryCallbackMap_.emplace(pkgName, callback); + return DM_OK; +} + +int32_t SoftbusConnector::UnRegisterSoftbusDiscoveryCallback(const std::string &pkgName) +{ + discoveryCallbackMap_.erase(pkgName); + return DM_OK; +} + +int32_t SoftbusConnector::RegisterSoftbusStateCallback(const std::string &pkgName, + const std::shared_ptr callback) +{ + stateCallbackMap_.emplace(pkgName, callback); + return DM_OK; +} + +int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgName) +{ + stateCallbackMap_.erase(pkgName); + return DM_OK; +} + +int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &deviceInfoList) +{ + LOGD("SoftbusConnector::GetTrustDevices start"); + int32_t infoNum = 0; + NodeBasicInfo *nodeInfo = nullptr; + int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeInfo, &infoNum); + if (ret != 0) { + LOGE("GetAllNodeDeviceInfo failed with ret %d", ret); + return DM_FAILED; + } + DmDeviceInfo *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (infoNum)); + if (info == nullptr) { + FreeNodeInfo(nodeInfo); + return DM_MALLOC_ERROR; + } + DmDeviceInfo **pInfoList = &info; + for (int32_t i = 0; i < infoNum; ++i) { + NodeBasicInfo *nodeBasicInfo = nodeInfo + i; + DmDeviceInfo *deviceInfo = *pInfoList + i; + CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, *deviceInfo); + deviceInfoList.push_back(*deviceInfo); + } + FreeNodeInfo(nodeInfo); + free(info); + LOGD("SoftbusConnector::GetTrustDevices success, deviceCount %d", infoNum); + return DM_OK; +} + +int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) +{ + LOGD("SoftbusConnector::GetLocalDeviceInfo start"); + NodeBasicInfo nodeBasicInfo; + int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeBasicInfo); + if (ret != 0) { + LOGE("GetLocalNodeDeviceInfo failed with ret %d", ret); + return DM_FAILED; + } + CovertNodeBasicInfoToDmDevice(nodeBasicInfo, deviceInfo); + LOGD("SoftbusConnector::GetLocalDeviceInfo success"); + return DM_OK; +} + +int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) +{ + SubscribeInfo subscribeInfo; + subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; + subscribeInfo.mode = (DiscoverMode)dmSubscribeInfo.mode; + subscribeInfo.medium = (ExchanageMedium)dmSubscribeInfo.medium; + subscribeInfo.freq = (ExchangeFreq)dmSubscribeInfo.freq; + subscribeInfo.isSameAccount = dmSubscribeInfo.isSameAccount; + subscribeInfo.isWakeRemote = dmSubscribeInfo.isWakeRemote; + subscribeInfo.capability = dmSubscribeInfo.capability; + subscribeInfo.capabilityData = nullptr; + subscribeInfo.dataLen = 0; + int32_t ret = ::StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); + if (ret != 0) { + LOGE("StartDiscovery failed with ret %d.", ret); + return DM_DISCOVERY_FAILED; + } + return DM_OK; +} + +int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) +{ + LOGI("StopDiscovery begin, subscribeId:%d", (int32_t)subscribeId); + int32_t ret = ::StopDiscovery(DM_PKG_NAME.c_str(), subscribeId); + if (ret != 0) { + LOGE("StopDiscovery failed with ret %d", ret); + return ret; + } + LOGI("SoftbusConnector::StopDiscovery completed"); + return DM_OK; +} + +int32_t SoftbusConnector::GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info, + int32_t infoLen) +{ + LOGI("GetNodeKeyInfoByNetworkId begin"); + + int32_t ret = GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId, key, info, infoLen); + if (ret != DM_OK) { + LOGE("GetNodeKeyInfoByNetworkId GetNodeKeyInfo failed"); + return DM_FAILED; + } + + LOGI("SoftbusConnector::GetNodeKeyInfoByNetworkId completed"); + return DM_OK; +} + +int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string &udid) +{ + LOGI("GetUdidByNetworkId begin"); + uint8_t mUdid[UDID_BUF_LEN] = {0}; + int32_t ret = + GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId, NodeDeivceInfoKey::NODE_KEY_UDID, mUdid, sizeof(mUdid)); + if (ret != DM_OK) { + LOGE("GetUdidByNetworkId GetNodeKeyInfo failed"); + return DM_FAILED; + } + udid = (char *)mUdid; + LOGI("SoftbusConnector::GetUdidByNetworkId completed"); + return DM_OK; +} + +int32_t SoftbusConnector::GetUuidByNetworkId(const char *networkId, std::string &uuid) +{ + LOGI("GetUuidByNetworkId begin"); + uint8_t mUuid[UUID_BUF_LEN] = {0}; + int32_t ret = + GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId, NodeDeivceInfoKey::NODE_KEY_UUID, mUuid, sizeof(mUuid)); + if (ret != DM_OK) { + LOGE("GetUuidByNetworkId GetNodeKeyInfo failed"); + return DM_FAILED; + } + uuid = (char *)mUuid; + LOGI("SoftbusConnector::GetUuidByNetworkId completed"); + return DM_OK; +} + +bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) +{ + NodeBasicInfo *info = nullptr; + int32_t infoNum = 0; + if (GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &info, &infoNum) != DM_OK) { + LOGE("GetAllNodeDeviceInfo failed"); + return false; + } + bool bDeviceOnline = false; + for (int32_t i = 0; i < infoNum; ++i) { + NodeBasicInfo *nodeBasicInfo = info + i; + if (nodeBasicInfo == nullptr) { + LOGE("nodeBasicInfo is empty for index %d, infoNum %d.", i, infoNum); + continue; + } + std::string networkId = nodeBasicInfo->networkId; + if (networkId == deviceId) { + LOGI("DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str()); + bDeviceOnline = true; + break; + } + uint8_t udid[UDID_BUF_LEN] = {0}; + int32_t ret = GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId.c_str(), NodeDeivceInfoKey::NODE_KEY_UDID, udid, + sizeof(udid)); + if (ret != DM_OK) { + LOGE("DM_IsDeviceOnLine GetNodeKeyInfo failed"); + break; + } + if (strcmp((char *)udid, deviceId.c_str()) == 0) { + LOGI("DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str()); + bDeviceOnline = true; + break; + } + } + FreeNodeInfo(info); + return bDeviceOnline; +} + +std::shared_ptr SoftbusConnector::GetSoftbusSession() +{ + return softbusSession_; +} + +bool SoftbusConnector::HaveDeviceInMap(std::string deviceId) +{ + auto iter = discoveryDeviceInfoMap_.find(deviceId); + if (iter == discoveryDeviceInfoMap_.end()) { + LOGE("deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str()); + return false; + } + return true; +} + +int32_t SoftbusConnector::GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress) +{ + auto iter = discoveryDeviceInfoMap_.find(deviceId); + if (iter == discoveryDeviceInfoMap_.end()) { + LOGE("deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str()); + return DM_FAILED; + } + DeviceInfo *deviceInfo = iter->second.get(); + if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { + LOGE("deviceInfo address num not valid, addrNum %d", deviceInfo->addrNum); + return DM_FAILED; + } + for (uint32_t i = 0; i < deviceInfo->addrNum; ++i) { + // currently, only support CONNECT_ADDR_WLAN + if (deviceInfo->addr[i].type != ConnectionAddrType::CONNECTION_ADDR_WLAN && + deviceInfo->addr[i].type != ConnectionAddrType::CONNECTION_ADDR_ETH) { + continue; + } + ipAddress = deviceInfo->addr[i].info.ip.ip; + LOGI("DM_GetConnectionIpAddr get ip ok."); + return DM_OK; + } + LOGE("failed to get ipAddress for deviceId %s", GetAnonyString(deviceId).c_str()); + return DM_FAILED; +} + +ConnectionAddr *SoftbusConnector::GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type) +{ + if (deviceInfo == nullptr) { + return nullptr; + } + for (uint32_t i = 0; i < deviceInfo->addrNum; ++i) { + if (deviceInfo->addr[i].type == type) { + return &deviceInfo->addr[i]; + } + } + return nullptr; +} + +ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) +{ + auto iter = discoveryDeviceInfoMap_.find(deviceId); + if (iter == discoveryDeviceInfoMap_.end()) { + LOGE("deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str()); + return nullptr; + } + DeviceInfo *deviceInfo = iter->second.get(); + if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { + LOGE("deviceInfo addrNum not valid, addrNum %d", deviceInfo->addrNum); + return nullptr; + } + nlohmann::json jsonPara; + ConnectionAddr *addr = nullptr; + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH); + if (addr != nullptr) { + LOGI("get ETH ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + jsonPara[ETH_IP] = addr->info.ip.ip; + jsonPara[ETH_PORT] = addr->info.ip.port; + connectAddr = jsonPara.dump(); + return addr; + } + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); + if (addr != nullptr) { + jsonPara[WIFI_IP] = addr->info.ip.ip; + jsonPara[WIFI_PORT] = addr->info.ip.port; + LOGI("get WLAN ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + connectAddr = jsonPara.dump(); + return addr; + } + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); + if (addr != nullptr) { + jsonPara[BR_MAC] = addr->info.br.brMac; + LOGI("get BLE ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + connectAddr = jsonPara.dump(); + return addr; + } + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); + if (addr != nullptr) { + jsonPara[BLE_MAC] = addr->info.ble.bleMac; + LOGI("get BR ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + connectAddr = jsonPara.dump(); + return addr; + } + LOGE("failed to get ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + return nullptr; +} + +void SoftbusConnector::CovertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo) +{ + (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), nodeBasicInfo.networkId, + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(nodeBasicInfo.networkId))) != DM_OK) { + LOGE("copy data failed"); + } + if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DM_OK) { + LOGE("copy data failed"); + } + dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId; +} + +void SoftbusConnector::CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo) +{ + (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != DM_OK) { + LOGE("copy data failed"); + } + if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { + LOGE("copy data failed"); + } + dmDeviceInfo.deviceTypeId = deviceInfo.devType; +} + +void SoftbusConnector::OnPublishSuccess(int32_t publishId) +{ + LOGI("SoftbusConnector::OnPublishSuccess, publishId: %d", publishId); +} + +void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason) +{ + LOGI("SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason); +} + +void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) +{ + LOGI("device online"); + if (info == nullptr) { + LOGE("SoftbusConnector::OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); + return; + } + + if (discoveryDeviceInfoMap_.empty()) { + return; + } + DmDeviceInfo dmDeviceInfo; + CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); + for (auto &iter : stateCallbackMap_) { + iter.second->OnDeviceOnline(iter.first, dmDeviceInfo); + } + // remove the discovery node map + uint8_t udid[UDID_BUF_LEN] = {0}; + int32_t ret = + GetNodeKeyInfo(DM_PKG_NAME.c_str(), info->networkId, NodeDeivceInfoKey::NODE_KEY_UDID, udid, sizeof(udid)); + if (ret != DM_OK) { + LOGE("GetNodeKeyInfo failed"); + return; + } + std::string deviceId = (char *)udid; + LOGI("device online, deviceId: %s", GetAnonyString(deviceId).c_str()); + discoveryDeviceInfoMap_.erase(deviceId); +} + +void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) +{ + if (info == nullptr) { + LOGE("OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); + return; + } + DmDeviceInfo dmDeviceInfo; + CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); + for (auto &iter : stateCallbackMap_) { + iter.second->OnDeviceOffline(iter.first, dmDeviceInfo); + } +} + +void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) +{ + LOGI("SoftbusConnector::OnSoftbusDeviceInfoChanged."); +} + +void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) +{ + if (device == nullptr) { + LOGE("device is null"); + return; + } + std::string deviceId = device->devId; + LOGI("SoftbusConnector::OnSoftbusDeviceFound device %s found.", GetAnonyString(deviceId).c_str()); + if (IsDeviceOnLine(deviceId)) { + return; + } + std::shared_ptr infoPtr = std::make_shared(); + DeviceInfo *srcInfo = infoPtr.get(); + if (memcpy_s(srcInfo, sizeof(DeviceInfo), device, sizeof(DeviceInfo)) != 0) { + LOGE("save discovery device info failed"); + return; + } + discoveryDeviceInfoMap_[deviceId] = infoPtr; + // Remove the earliest element when reached the max size + if (discoveryDeviceInfoMap_.size() == SOFTBUS_DISCOVER_DEVICE_INFO_MAX_SIZE) { + auto iter = discoveryDeviceInfoMap_.begin(); + discoveryDeviceInfoMap_.erase(iter->second->devId); + } + DmDeviceInfo dmDeviceInfo; + CovertDeviceInfoToDmDevice(*device, dmDeviceInfo); + for (auto &iter : discoveryCallbackMap_) { + iter.second->OnDeviceFound(iter.first, dmDeviceInfo); + } +} + +void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t 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); + for (auto &iter : discoveryCallbackMap_) { + iter.second->OnDiscoveryFailed(iter.first, originId, (int32_t)failReason); + } +} + +void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) +{ + LOGI("In, subscribeId %d", subscribeId); + uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); + for (auto &iter : discoveryCallbackMap_) { + iter.second->OnDiscoverySuccess(iter.first, originId); + } +} + +void SoftbusConnector::OnParameterChgCallback(const char *key, const char *value, void *context) +{ + if (strcmp(value, DISCOVER_STATUS_ON.c_str()) == 0 && publishStatus != ALLOW_BE_DISCOVERY) { + PublishInfo dmPublishInfo; + dmPublishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; + dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; + dmPublishInfo.medium = ExchanageMedium::AUTO; + dmPublishInfo.freq = ExchangeFreq::HIGH; + dmPublishInfo.capability = DM_CAPABILITY_OSD; + dmPublishInfo.capabilityData = nullptr; + dmPublishInfo.dataLen = 0; + int32_t ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); + if (ret == DM_OK) { + publishStatus = ALLOW_BE_DISCOVERY; + } + LOGI("service publish result is : %d", ret); + } else if (strcmp(value, DISCOVER_STATUS_OFF.c_str()) == 0 && publishStatus != NOT_ALLOW_BE_DISCOVERY) { + int32_t ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + if (ret == DM_OK) { + publishStatus = NOT_ALLOW_BE_DISCOVERY; + } + LOGI("service unpublish result is : %d", ret); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp new file mode 100644 index 000000000..7e31b7a3e --- /dev/null +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -0,0 +1,163 @@ +/* + * 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 "softbus_session.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { + +std::map> SoftbusSession::sessionCallbackMap_ = {}; + +SoftbusSession::SoftbusSession() +{ + ISessionListener sessionListener = {.OnSessionOpened = SoftbusSession::OnSessionOpened, + .OnSessionClosed = SoftbusSession::OnSessionClosed, + .OnBytesReceived = SoftbusSession::OnBytesReceived, + .OnMessageReceived = nullptr, + .OnStreamReceived = nullptr}; + int32_t ret = CreateSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str(), &sessionListener); + if (ret != DM_OK) { + LOGD("CreateSessionServer failed"); + } else { + LOGI("CreateSessionServer ok"); + } +} + +SoftbusSession::~SoftbusSession() +{ + RemoveSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str()); +} + +int32_t SoftbusSession::RegisterSessionCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + sessionCallbackMap_[pkgName] = callback; + return DM_OK; +} + +int32_t SoftbusSession::UnRegisterSessionCallback(const std::string &pkgName) +{ + sessionCallbackMap_.erase(pkgName); + return DM_OK; +} + +int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) +{ + LOGE("SoftbusSession::OpenAuthSession"); + int32_t sessionId = -1; + std::string connectAddr; + ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); + if (addrInfo == nullptr) { + LOGE("GetConnectAddr error"); + return sessionId; + } + sessionId = ::OpenAuthSession(DM_SESSION_NAME.c_str(), addrInfo, 1, nullptr); + if (sessionId < 0) { + LOGE("open session error, ret:%d", sessionId); + return sessionId; + } + LOGI("SoftbusSession::OpenAuthSession success. sessionId is:%d", sessionId); + return sessionId; +} + +void SoftbusSession::CloseAuthSession(int32_t sessionId) +{ + LOGI("SoftbusSession::CloseAuthSession"); + ::CloseSession(sessionId); +} + +void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) +{ + char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; + int32_t ret = ::GetPeerDeviceId(sessionId, &peerDeviceId[0], DEVICE_UUID_LENGTH); + if (ret == 0) { + peerDevId = peerDeviceId; + LOGI("GetPeerDeviceId success for session:%d, peerDeviceId:%s", sessionId, GetAnonyString(peerDevId).c_str()); + return; + } + LOGE("GetPeerDeviceId failed for session:%d", sessionId); + peerDevId = ""; +} + +int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) +{ + LOGE("SendData Start"); + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("extrasJson error"); + return DM_FAILED; + } + int32_t msgType = jsonObject[TAG_TYPE]; + LOGI("AuthMessageProcessor::ParseAuthRequestMessage msgType = %d", msgType); + bool isCryptoSupport = false; + for (auto &iter : sessionCallbackMap_) { + iter.second->GetIsCryptoSupport(isCryptoSupport); + } + if (isCryptoSupport) { + LOGI("SoftbusSession::SendData Start encryption"); + } + int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); + if (ret != DM_OK) { + LOGE("SendData Start failed"); + return DM_FAILED; + } + LOGE("SendData Start success"); + return DM_OK; +} + +int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) +{ + int32_t sessionSide = GetSessionSide(sessionId); + for (auto &iter : sessionCallbackMap_) { + iter.second->OnSessionOpened(iter.first, sessionId, sessionSide, result); + } + LOGI("OnSessionOpened, success:"); + return DM_OK; +} + +void SoftbusSession::OnSessionClosed(int32_t sessionId) +{ + LOGI("OnSessionClosed, sessionId:%d", sessionId); +} + +void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + LOGI("OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen); + if (sessionId < 0 || data == nullptr || dataLen <= 0) { + LOGI("OnBytesReceived param check failed"); + return; + } + bool isCryptoSupport = false; + for (auto &iter : sessionCallbackMap_) { + iter.second->GetIsCryptoSupport(isCryptoSupport); + } + if (isCryptoSupport) { + LOGI("SoftbusSession::OnBytesReceived Start decryption"); + } + std::string message = std::string((const char *)data, dataLen); + for (auto &iter : sessionCallbackMap_) { + iter.second->OnDataReceived(iter.first, sessionId, message); + } + LOGI("OnBytesReceived completed"); +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp new file mode 100644 index 000000000..dc9a82b9c --- /dev/null +++ b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp @@ -0,0 +1,153 @@ +/* + * 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 + +#include "securec.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const int32_t MILL_SECONDS_PER_SECOND = 1000; +} +DmTimer::DmTimer(std::string &name) +{ + mStatus_ = DmTimerStatus::DM_STATUS_INIT; + mTimeOutSec_ = 0; + mHandle_ = nullptr; + mHandleData_ = nullptr; + (void)memset_s(mTimeFd_, sizeof(mTimeFd_), 0, sizeof(mTimeFd_)); + (void)memset_s(&mEv_, sizeof(mEv_), 0, sizeof(mEv_)); + (void)memset_s(mEvents_, sizeof(mEvents_), 0, sizeof(mEvents_)); + mEpFd_ = 0; + mTimerName_ = name; +} + +DmTimer::~DmTimer() +{ + LOGI("DmTimer %s Destory in", mTimerName_.c_str()); + Release(); +} + +DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) +{ + LOGI("DmTimer %s start timeout(%d)", mTimerName_.c_str(), timeOut); + if (mStatus_ != DmTimerStatus::DM_STATUS_INIT) { + return DmTimerStatus::DM_STATUS_BUSY; + } + + mTimeOutSec_ = timeOut; + mHandle_ = handle; + mHandleData_ = data; + + if (CreateTimeFd()) { + return DmTimerStatus::DM_STATUS_CREATE_ERROR; + } + + mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; + mThread_ = std::thread(&DmTimer::WaitForTimeout, this); + mThread_.detach(); + + return mStatus_; +} + +void DmTimer::Stop(int32_t code) +{ + LOGI("DmTimer %s Stop code (%d)", mTimerName_.c_str(), code); + if (mTimeFd_[1]) { + char event = 'S'; + if (write(mTimeFd_[1], &event, 1) < 0) { + LOGE("DmTimer %s Stop timer failed, errno %d", mTimerName_.c_str(), errno); + return; + } + LOGI("DmTimer %s Stop success", mTimerName_.c_str()); + } + + return; +} + +void DmTimer::WaitForTimeout() +{ + LOGI("DmTimer %s start timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); + + int32_t nfds = epoll_wait(mEpFd_, mEvents_, MAXEVENTS, mTimeOutSec_ * MILL_SECONDS_PER_SECOND); + if (nfds < 0) { + LOGE("DmTimer %s epoll_wait returned n=%d, error: %d", mTimerName_.c_str(), nfds, errno); + } + + char event = 0; + if (nfds > 0) { + if (mEvents_[0].events & EPOLLIN) { + int num = read(mTimeFd_[0], &event, 1); + if (num > 0) { + LOGI("DmTimer %s exit with event %d", mTimerName_.c_str(), event); + } else { + LOGE("DmTimer %s exit with errno %d", mTimerName_.c_str(), errno); + } + } + Release(); + return; + } + + mHandle_(mHandleData_); + Release(); + + LOGE("DmTimer %s end timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); + return; +} + +int32_t DmTimer::CreateTimeFd() +{ + LOGI("DmTimer %s creatTimeFd", mTimerName_.c_str()); + int ret = 0; + + ret = pipe(mTimeFd_); + if (ret < 0) { + LOGE("DmTimer %s CreateTimeFd fail:(%d) errno(%d)", mTimerName_.c_str(), ret, errno); + return ret; + } + + mEv_.data.fd = mTimeFd_[0]; + mEv_.events = EPOLLIN | EPOLLET; + mEpFd_ = epoll_create(MAXEVENTS); + ret = epoll_ctl(mEpFd_, EPOLL_CTL_ADD, mTimeFd_[0], &mEv_); + if (ret != 0) { + Release(); + } + + return ret; +} + +void DmTimer::Release() +{ + LOGI("DmTimer %s Release in", mTimerName_.c_str()); + if (mStatus_ == DmTimerStatus::DM_STATUS_INIT) { + LOGI("DmTimer %s already Release", mTimerName_.c_str()); + return; + } + mStatus_ = DmTimerStatus::DM_STATUS_INIT; + close(mTimeFd_[0]); + close(mTimeFd_[1]); + if (mEpFd_ >= 0) { + close(mEpFd_); + } + mTimeFd_[0] = 0; + mTimeFd_[1] = 0; + mEpFd_ = 0; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp new file mode 100644 index 000000000..dd013d4e6 --- /dev/null +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -0,0 +1,229 @@ +/* + * 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.h" + +#include "device_manager_service_listener.h" +#include "dm_constants.h" +#include "dm_device_info_manager.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); + +int32_t DeviceManagerService::Init() +{ + if (intFlag_) { + LOGE("Init failed, singleton cannot be initialized multiple times"); + return DM_INT_MULTIPLE; + } + if (softbusConnector_ == nullptr) { + softbusConnector_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, softbusConnector_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (listener_ == nullptr) { + listener_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, listener_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (deviceInfoMgr_ == nullptr) { + deviceInfoMgr_ = std::make_shared(softbusConnector_); + if (deviceInfoMgr_ == nullptr) { + LOGE("Init failed, deviceInfoMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (deviceStateMgr_ == nullptr) { + deviceStateMgr_ = std::make_shared(softbusConnector_, listener_); + if (deviceStateMgr_ == nullptr) { + LOGE("Init failed, deviceStateMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + deviceStateMgr_->RegisterSoftbusStateCallback(); + } + if (discoveryMgr_ == nullptr) { + discoveryMgr_ = std::make_shared(softbusConnector_, listener_); + if (discoveryMgr_ == nullptr) { + LOGE("Init failed, discoveryMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (authMgr_ == nullptr) { + authMgr_ = std::make_shared(softbusConnector_, listener_); + if (authMgr_ == nullptr) { + LOGE("Init failed, authMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + authMgr_->RegisterSessionCallback(); + } + LOGI("Init success, singleton initialized"); + intFlag_ = true; + return DM_OK; +} + +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) +{ + if (!intFlag_) { + LOGE("GetTrustedDeviceList failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + if (pkgName.empty()) { + LOGE("GetTrustedDeviceList failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); +} + +int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) +{ + if (!intFlag_) { + LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + return deviceInfoMgr_->GetLocalDeviceInfo(info); +} + +int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) +{ + if (!intFlag_) { + LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + + if (pkgName.empty()) { + LOGE("StartDeviceDiscovery failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid); + return DM_OK; +} + +int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) +{ + if (!intFlag_) { + LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + + if (pkgName.empty()) { + LOGE("StartDeviceDiscovery failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid); + return DM_OK; +} + +int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra) +{ + if (!intFlag_) { + LOGE("StartDeviceDiscovery failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + if (pkgName.empty()) { + LOGE("StartDeviceDiscovery failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); +} + +int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + if (!intFlag_) { + LOGE("StopDeviceDiscovery failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + if (pkgName.empty()) { + LOGE("StopDeviceDiscovery failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); +} + +int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + if (!intFlag_) { + LOGE("AuthenticateDevice failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + if (pkgName.empty()) { + LOGE("AuthenticateDevice failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + if (deviceId.empty()) { + LOGE("AuthenticateDevice failed, deviceId is empty"); + return DM_INPUT_PARA_EMPTY; + } + return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); +} + +int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) +{ + if (!intFlag_) { + LOGE("UnAuthenticateDevice failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + if (pkgName.empty()) { + LOGE("UnAuthenticateDevice failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + if (deviceId.empty()) { + LOGE("UnAuthenticateDevice failed, deviceId is empty"); + return DM_INPUT_PARA_EMPTY; + } + return authMgr_->UnAuthenticateDevice(pkgName, deviceId); +} + +int32_t DeviceManagerService::VerifyAuthentication(const std::string &authParam) +{ + if (!intFlag_) { + LOGE("VerifyAuthentication failed, singleton not init or init fail"); + return DM_NOT_INIT; + } + return authMgr_->VerifyAuthentication(authParam); +} + +int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam) +{ + if (pkgName.empty()) { + LOGE("GetFaParam failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + authMgr_->GetAuthenticationParam(authParam); + return DM_OK; +} + +int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action) +{ + if (pkgName.empty()) { + LOGE("SetUserOperation failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; + } + authMgr_->OnUserOperation(action); + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp new file mode 100644 index 000000000..c0b3f9929 --- /dev/null +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_service_listener.h" + +#include + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_discover_result_req.h" +#include "ipc_notify_verify_auth_result_req.h" + +namespace OHOS { +namespace DistributedHardware { + +void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, + const DmDeviceInfo &info) +{ + LOGI("OnDeviceStateChange, state=%d", state); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetDeviceState(state); + pReq->SetDeviceInfo(info); + ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); +} + +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()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetSubscribeId(subscribeId); + pReq->SetDeviceInfo(info); + ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); +} + +void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, + int32_t failedReason) +{ + LOGI("OnDiscoveryFailed"); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetSubscribeId(subscribeId); + pReq->SetResult(failedReason); + ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); +} + +void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +{ + LOGI("OnDiscoverySuccess"); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetSubscribeId(subscribeId); + pReq->SetResult(DM_OK); + ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); +} + +void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, + const std::string &token, int32_t status, const std::string &reason) +{ + LOGI("%s, package: %s, deviceId: %s", __FUNCTION__, pkgName.c_str(), GetAnonyString(deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetDeviceId(deviceId); + pReq->SetToken(token); + pReq->SetStatus(status); + // pReq->SetReason(reason); + ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); +} + +void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, const std::string &flag) +{ + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetDeviceId(deviceId); + pReq->SetResult(resultCode); + ipcServerListener_.SendAll(SERVER_VERIFY_AUTH_RESULT, pReq, pRsp); +} + +void DeviceManagerServiceListener::OnFaCall(std::string &pkgName, std::string ¶mJson) +{ + LOGI("OnFaCall in"); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetJsonParam(paramJson); + ipcServerListener_.SendRequest(SERVER_DEVICE_FA_NOTIFY, pReq, pRsp); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp new file mode 100644 index 000000000..dcf240abf --- /dev/null +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_device_info_manager.h" + +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr &softbusConnectorPtr) + : softbusConnector_(softbusConnectorPtr) +{ + LOGI("DmDeviceInfoManager constructor"); +} + +int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) +{ + int32_t ret = softbusConnector_->GetTrustedDeviceList(deviceList); + if (ret != DM_OK) { + LOGE("GetTrustedDeviceList failed"); + return ret; + } + + if (!extra.empty() && !deviceList.empty()) { + std::string soName; + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(soName); + if (decisionAdapter != nullptr) { + decisionAdapter->FilterDeviceList(deviceList, extra); + } else { + LOGE("GetTrustedDeviceList decisionAdapter is nullptr"); + } + } + + return DM_OK; +} + +int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info) +{ + int32_t ret = softbusConnector_->GetLocalDeviceInfo(info); + if (ret != DM_OK) { + LOGE("GetLocalDeviceInfo failed"); + return ret; + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp new file mode 100644 index 000000000..788e75678 --- /dev/null +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -0,0 +1,122 @@ +/* + * 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_device_state_manager.h" + +#include "dm_adapter_manager.h" +#include "dm_constants.h" +#include "dm_log.h" +namespace OHOS { +namespace DistributedHardware { + +DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnector, + std::shared_ptr listener) + : softbusConnector_(softbusConnector), listener_(listener) +{ + LOGI("DmDeviceStateManager constructor"); + profileSoName_ = "libdevicemanagerext_profile.z.so"; +} + +DmDeviceStateManager::~DmDeviceStateManager() +{ + LOGI("DmDeviceStateManager destructor"); + softbusConnector_->UnRegisterSoftbusStateCallback(""); +} + +void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) +{ + LOGI("DmDeviceStateManager::OnDeviceOnline in"); + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_); + if (profileAdapter == nullptr) { + LOGE("OnDeviceOnline profile adapter is null"); + } else { + uint8_t udid[UDID_BUF_LEN] = {0}; + int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(info.deviceId, NodeDeivceInfoKey::NODE_KEY_UDID, udid, + sizeof(udid)); + if (ret != DM_OK) { + LOGE("DmDeviceStateManager::OnDeviceOnline GetNodeKeyInfo failed"); + } else { + std::string deviceUdid = (char *)udid; + DmDeviceInfo saveInfo = info; + std::string uuid; + SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid); + remoteDeviceInfos_[uuid] = saveInfo; + LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s, uuid = %s", + info.deviceId, deviceUdid.c_str(), uuid.c_str()); + //set networkId or udid; + profileAdapter->RegisterProfileListener(pkgName, deviceUdid, shared_from_this()); + LOGI("RegisterProfileListener out"); + } + } + DmDeviceState state = DEVICE_STATE_ONLINE; + deviceStateMap_[info.deviceId] = DEVICE_STATE_ONLINE; + listener_->OnDeviceStateChange(pkgName, state, info); + LOGI("DmDeviceStateManager::OnDeviceOnline out"); +} + +void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) +{ + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_); + if (profileAdapter == nullptr) { + LOGE("OnDeviceOffline profile adapter is null"); + } else { + profileAdapter->UnRegisterProfileListener(pkgName); + std::string uuid; + SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid); + auto iter = remoteDeviceInfos_.find(std::string(info.deviceId)); + if (iter == remoteDeviceInfos_.end()) { + } else { + remoteDeviceInfos_.erase(std::string(info.deviceId)); + } + } + DmDeviceState state = DEVICE_STATE_OFFLINE; + deviceStateMap_[info.deviceId] = DEVICE_STATE_OFFLINE; + listener_->OnDeviceStateChange(pkgName, state, info); +} + +void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) +{ + deviceStateMap_[info.deviceId] = DEVICE_INFO_CHANGED; +} + +void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info) +{ + deviceStateMap_[info.deviceId] = DEVICE_INFO_READY; +} + +void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std::string deviceId) +{ + //deviceId is uuid; + DmDeviceInfo saveInfo; + auto iter = remoteDeviceInfos_.find(deviceId); + if (iter == remoteDeviceInfos_.end()) { + LOGE("DmDeviceStateManager::OnProfileReady complete not find deviceID = %s", deviceId.c_str()); + } else { + saveInfo = iter->second; + } + DmDeviceState state = DEVICE_INFO_READY; + listener_->OnDeviceStateChange(pkgName, state, saveInfo); +} + +int32_t DmDeviceStateManager::RegisterSoftbusStateCallback() +{ + softbusConnector_->RegisterSoftbusStateCallback(DM_PKG_NAME, + std::shared_ptr(shared_from_this())); + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp new file mode 100644 index 000000000..cb4c8f8d5 --- /dev/null +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -0,0 +1,119 @@ +/* + * 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_discovery_manager.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout"; +int32_t DISCOVERY_TIMEOUT = 120; +int32_t SESSION_CANCEL_TIMEOUT = 0; +} // namespace +static void TimeOut(void *data) +{ + LOGE("time out "); + DmDiscoveryManager *discoveryMgr = (DmDiscoveryManager *)data; + if (discoveryMgr == nullptr) { + LOGE("time out error"); + return; + } + discoveryMgr->HandleDiscoveryTimeout(); +} + +DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnector, + std::shared_ptr listener) + : softbusConnector_(softbusConnector), listener_(listener) +{ + LOGI("DmDiscoveryManager constructor"); +} + +DmDiscoveryManager::~DmDiscoveryManager() +{ + LOGI("DmDiscoveryManager destructor"); +} + +int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra) +{ + if (!discoveryQueue_.empty()) { + if (pkgName == discoveryQueue_.front()) { + LOGE("DmDiscoveryManager::StartDeviceDiscovery repeated, pkgName:%s", pkgName.c_str()); + return DM_DISCOVERY_REPEATED; + } else { + LOGD("DmDiscoveryManager::StartDeviceDiscovery stop preview discovery first, the preview pkgName is %s", + discoveryQueue_.front().c_str()); + StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); + } + } + discoveryQueue_.push(pkgName); + DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId}; + discoveryContextMap_.emplace(pkgName, context); + softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, + std::shared_ptr(shared_from_this())); + discoveryTimer_ = std::make_shared(DISCOVERY_TIMEOUT_TASK); + discoveryTimer_->Start(DISCOVERY_TIMEOUT, TimeOut, this); + return softbusConnector_->StartDiscovery(subscribeInfo); +} + +int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + if (!discoveryQueue_.empty()) { + discoveryQueue_.pop(); + } + if (!discoveryContextMap_.empty()) { + discoveryContextMap_.erase(pkgName); + softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); + discoveryTimer_->Stop(SESSION_CANCEL_TIMEOUT); + } + return softbusConnector_->StopDiscovery(subscribeId); +} + +void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) +{ + LOGI("DmDiscoveryManager::OnDeviceFound deviceId=%s", GetAnonyString(info.deviceId).c_str()); + auto iter = discoveryContextMap_.find(pkgName); + if (iter == discoveryContextMap_.end()) { + LOGE("subscribeId not found by pkgName %s", GetAnonyString(pkgName).c_str()); + return; + } + listener_->OnDeviceFound(pkgName, iter->second.subscribeId, info); +} + +void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) +{ + LOGI("DmDiscoveryManager::OnDiscoveryFailed subscribeId=%d reason=%d", subscribeId, failedReason); + StopDeviceDiscovery(pkgName, subscribeId); + listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); +} + +void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +{ + LOGI("DmDiscoveryManager::OnDiscoverySuccess subscribeId=%d", subscribeId); + discoveryContextMap_[pkgName].subscribeId = subscribeId; + listener_->OnDiscoverySuccess(pkgName, subscribeId); +} + +void DmDiscoveryManager::HandleDiscoveryTimeout() +{ + LOGI("DmDiscoveryManager::HandleDiscoveryTimeout"); + StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp new file mode 100644 index 000000000..6e14961b3 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -0,0 +1,256 @@ +/* + * 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.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_discover_result_req.h" +#include "ipc_notify_verify_auth_result_req.h" +#include "ipc_server_stub.h" + +namespace OHOS { +namespace DistributedHardware { +ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t deviceState = pReq->GetDeviceState(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushInt32(&request, deviceState); + IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushUint16(&request, subscribeId); + IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + int32_t result = pReq->GetResult(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushUint16(&request, subscribeId); + IpcIoPushInt32(&request, result); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + std::string token = pReq->GetPinToken(); + int32_t status = pReq->GetStatus(); + int32_t reason = pReq->GetReason(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushString(&request, deviceId.c_str()); + IpcIoPushString(&request, token.c_str()); + IpcIoPushInt32(&request, status); + IpcIoPushInt32(&request, reason); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_VERIFY_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + int32_t result = pReq->GetResult(); + int32_t flag = pReq->GetFlag(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushString(&request, deviceId.c_str()); + IpcIoPushInt32(&request, result); + IpcIoPushInt32(&request, flag); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; +} + +ON_IPC_SERVER_CMD(REGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) +{ + int32_t errCode = RegisterDeviceManagerListener(&req, &reply); + IpcIoPushInt32(&reply, errCode); +} + +ON_IPC_SERVER_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) +{ + int32_t errCode = UnRegisterDeviceManagerListener(&req, &reply); + IpcIoPushInt32(&reply, errCode); +} + +ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) +{ + LOGI("enter GetTrustedDeviceList."); + std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); + std::string extra = (const char *)IpcIoPopString(&req, nullptr); + + std::vector deviceList; + int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + IpcIoPushInt32(&reply, deviceList.size()); + if (deviceList.size() > 0) { + IpcIoPushFlatObj(&reply, deviceList.data(), sizeof(DmDeviceInfo) * deviceList.size()); + } + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(GET_LOCAL_DEVICE_INFO, IpcIo &req, IpcIo &reply) +{ + LOGI("enter GetLocalDeviceInfo."); + DmDeviceInfo dmDeviceInfo; + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo); + IpcIoPushFlatObj(&reply, &dmDeviceInfo, sizeof(DmDeviceInfo)); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) +{ + LOGI("StartDeviceDiscovery service listener."); + std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); + std::string extra = (const char *)IpcIoPopString(&req, nullptr); + + uint32_t size = 0; + DmSubscribeInfo *pDmSubscribeInfo = (DmSubscribeInfo *)IpcIoPopFlatObj(&req, &size); + int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo, extra); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) +{ + LOGI("StopDeviceDiscovery service listener."); + std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); + uint16_t subscribeId = IpcIoPopUint16(&req); + int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) +{ + LOGI("AuthenticateDevice service listener."); + std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); + std::string extra = (const char *)IpcIoPopString(&req, nullptr); + std::string deviceId = (const char *)IpcIoPopString(&req, nullptr); + int32_t authType = IpcIoPopInt32(&req); + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(UNAUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) +{ + LOGI("UnAuthenticateDevice service listener."); + std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); + std::string deviceId = (const char *)IpcIoPopString(&req, nullptr); + + int32_t ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATION, IpcIo &req, IpcIo &reply) +{ + LOGI("VerifyAuthentication service listener."); + std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); + std::string authParam = (const char *)IpcIoPopString(&req, nullptr); + + int32_t ret = DeviceManagerService::GetInstance().VerifyAuthentication(pkgName, authParam); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(SERVER_USER_AUTH_OPERATION, IpcIo &req, IpcIo &reply) +{ + size_t len = 0; + std::string packName = (const char *)IpcIoPopString(&req, &len); + int32_t action = IpcIoPopInt32(&reply); + DeviceManagerService::GetInstance().SetUserOperation(packName, action); + IpcIoPushInt32(&reply, action); +} + +ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagname = pReq->GetPkgName(); + std::string paramJson = pReq->GetJsonParam(); + IpcIoPushString(&request, packagname.c_str()); + IpcIoPushString(&request, paramJson.c_str()); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, IpcIo &request, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp new file mode 100644 index 000000000..6436427d6 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_listener.h" + +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_server_listenermgr.h" + +namespace OHOS { +namespace DistributedHardware { +void IpcServerListener::CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity) +{ + identity->handle = svcId->handle; + identity->token = svcId->token; + identity->cookie = svcId->cookie; +#ifdef __LINUX__ + identity->ipcContext = svcId->ipcCtx; +#endif +} + +int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity *svc) +{ + CommonSvcId svcId; + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DM_OK) { + LOGE("get identity failed."); + return DM_FAILED; + } + CommonSvcToIdentity(&svcId, svc); + return DM_OK; +} + +int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + std::string pkgName = req->GetPkgName(); + SvcIdentity svc; + if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { + LOGE("OnDeviceFound callback get listener failed."); + return DM_FAILED; + } + + IpcIo io; + uint8_t data[MAX_DM_IPC_LEN] = {0}; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) { + LOGD("SetRequest failed cmdCode:%d", cmdCode); + return DM_FAILED; + } + + if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { + LOGD("SendRequest failed cmdCode:%d", cmdCode); + } + return DM_OK; +} + +int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); + for (auto &kv : listenerMap) { + SvcIdentity svc; + IpcIo io; + uint8_t data[MAX_DM_IPC_LEN] = {0}; + std::string pkgName = kv.first; + + req->SetPkgName(pkgName); + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) { + LOGD("SetRequest failed cmdCode:%d", cmdCode); + continue; + } + CommonSvcId svcId = kv.second; + CommonSvcToIdentity(&svcId, &svc); + if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { + LOGD("SendRequest failed cmdCode:%d", cmdCode); + } + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp new file mode 100644 index 000000000..c223a0104 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.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 "ipc_server_listenermgr.h" + +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcServerListenermgr); + +int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const CommonSvcId *svcId) +{ + if (pkgName == "" || svcId == nullptr) { + LOGE("invalid param"); + return DM_FAILED; + } + LOGI("new listener register:%s", pkgName.c_str()); + std::lock_guard autoLock(lock_); + dmListenerMap_[pkgName] = *svcId; + return DM_OK; +} + +int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId) +{ + if (pkgName == "" || svcId == nullptr) { + LOGE("invalid param"); + return DM_FAILED; + } + std::lock_guard autoLock(lock_); + std::map::iterator iter = dmListenerMap_.find(pkgName); + if (iter == dmListenerMap_.end()) { + LOGE("listener not found for pkg:%s", pkgName.c_str()); + return DM_FAILED; + } + *svcId = iter->second; + return DM_OK; +} + +int32_t IpcServerListenermgr::UnregisterListener(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + dmListenerMap_.erase(pkgName); + return DM_OK; +} + +const std::map &IpcServerListenermgr::GetAllListeners() +{ + return dmListenerMap_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp new file mode 100644 index 000000000..03dd6c3ac --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include "device_manager_service.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_server_stub.h" + +using namespace OHOS::DistributedHardware; + +static void InitAll() +{ + const int32_t DM_SERVICE_INIT_DELAY = 2; + sleep(DM_SERVICE_INIT_DELAY); + if (IpcServerStubInit() != DM_OK) { + LOGE("IpcServerStubInit failed"); + return; + } + if (DeviceManagerService::GetInstance().Init() != DM_OK) { + LOGE("module init failed"); + return; + } + LOGI("DM ipc server Init success"); +} + +int32_t main(int32_t argc, char *argv[]) +{ + (void)argc; + (void)argv; + InitAll(); + while (1) { + pause(); + } + return 0; +} \ No newline at end of file diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp new file mode 100644 index 000000000..b6af2d8c8 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_stub.h" + +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_subscribe_info.h" +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_server_listenermgr.h" +#include "iproxy_server.h" +#include "liteipc_adapter.h" +#include "ohos_init.h" +#include "samgr_lite.h" +#include "securec.h" + +namespace { +const int32_t WAIT_FOR_SERVER = 2; +const int32_t STACK_SIZE = 0x1000; +const int32_t QUEUE_SIZE = 32; +} // namespace + +using namespace OHOS::DistributedHardware; + +struct DefaultFeatureApi { + INHERIT_SERVER_IPROXY; +}; + +struct DeviceManagerSamgrService { + INHERIT_SERVICE; + INHERIT_IUNKNOWNENTRY(DefaultFeatureApi); + Identity identity; +}; + +static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, void *arg) +{ + (void)context; + (void)ipcMsg; + (void)data; + if (arg == NULL) { + LOGE("package name is NULL."); + return DM_INVALID_VALUE; + } + CommonSvcId svcId = {0}; + std::string pkgName = (const char *)arg; + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_OK) { + LOGE("not found client by package name."); + free(arg); + arg = NULL; + return DM_FAILED; + } + IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); + free(arg); + arg = NULL; +#ifdef __LINUX__ + BinderRelease(svcId.ipcCtx, svcId.handle); +#endif + SvcIdentity sid = {0}; + sid.handle = svcId.handle; + sid.token = svcId.token; + sid.cookie = svcId.cookie; + UnregisterDeathCallback(sid, svcId.cbId); + return DM_OK; +} + +int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) +{ + LOGI("register service listener."); + size_t len = 0; + uint8_t *name = IpcIoPopString(req, &len); + SvcIdentity *svc = IpcIoPopSvc(req); + if (name == NULL || svc == NULL || len == 0) { + LOGE("get para failed"); + return DM_INVALID_VALUE; + } + + CommonSvcId svcId = {0}; + svcId.handle = svc->handle; + svcId.token = svc->token; + svcId.cookie = svc->cookie; + + SvcIdentity sid = *svc; +#ifdef __LINUX__ + svcId.ipcCtx = svc->ipcContext; + BinderAcquire(svcId.ipcCtx, svcId.handle); + free(svc); + svc = NULL; +#endif + char *pkgName = (char *)malloc(len + 1); + if (pkgName == NULL) { + LOGE("malloc failed!"); + return DM_MALLOC_ERROR; + } + if (strcpy_s(pkgName, len + 1, (const char *)name) != DM_OK) { + LOGE("strcpy_s failed!"); + free(pkgName); + return DM_COPY_FAILED; + } + uint32_t cbId = 0; + RegisterDeathCallback(NULL, sid, DeathCb, pkgName, &cbId); + svcId.cbId = cbId; + std::string strPkgName = (const char *)name; + return IpcServerListenermgr::GetInstance().RegisterListener(strPkgName, &svcId); +} + +int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) +{ + LOGI("unregister service listener."); + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(req, &len); + if (pkgName == "" || len == 0) { + LOGE("get para failed"); + return DM_FAILED; + } + CommonSvcId svcId; + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_OK) { + LOGE("not found listener by package name."); + return DM_FAILED; + } + int32_t ret = IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); + if (ret == DM_OK) { +#ifdef __LINUX__ + BinderRelease(svcId.ipcCtx, svcId.handle); +#endif + SvcIdentity sid; + sid.handle = svcId.handle; + sid.token = svcId.token; + sid.cookie = svcId.cookie; + ret = UnregisterDeathCallback(sid, svcId.cbId); + } + return ret; +} + +static const char *GetName(Service *service) +{ + (void)service; + return DEVICE_MANAGER_SERVICE_NAME; +} + +static BOOL Initialize(Service *service, Identity identity) +{ + if (service == NULL) { + LOGW("invalid param"); + return FALSE; + } + + DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; + mgrService->identity = identity; + return TRUE; +} + +static BOOL MessageHandle(Service *service, Request *request) +{ + if ((service == NULL) || (request == NULL)) { + LOGW("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 int32_t OnRemoteRequest(IServerProxy *iProxy, int32_t funcId, void *origin, IpcIo *req, IpcIo *reply) +{ + LOGI("Receive funcId:%d", funcId); + (void)origin; + return IpcCmdRegister::GetInstance().OnIpcServerCmd(funcId, *req, *reply); +} + +static void HOS_SystemInit(void) +{ + SAMGR_Bootstrap(); + return; +} + +int32_t IpcServerStubInit(void) +{ + HOS_SystemInit(); + return DM_OK; +} + +static void DevMgrSvcInit(void) +{ + sleep(WAIT_FOR_SERVER); + static DeviceManagerSamgrService service = { + .GetName = GetName, + .Initialize = Initialize, + .MessageHandle = MessageHandle, + .GetTaskConfig = GetTaskConfig, + SERVER_IPROXY_IMPL_BEGIN, + .Invoke = OnRemoteRequest, + 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/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp new file mode 100644 index 000000000..2a61266b5 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -0,0 +1,435 @@ +/* + * 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 "device_manager_service.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "dm_subscribe_info.h" +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_discover_result_req.h" +#include "ipc_notify_verify_auth_result_req.h" +#include "ipc_server_stub.h" + +namespace OHOS { +namespace DistributedHardware { +ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t deviceState = pReq->GetDeviceState(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt32(deviceState)) { + LOGE("write state failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { + LOGE("write deviceInfo failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt16(subscribeId)) { + LOGE("write subscribeId failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { + LOGE("write deviceInfo failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + int32_t result = pReq->GetResult(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt16(subscribeId)) { + LOGE("write subscribeId failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt32(result)) { + LOGE("write result failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + std::string token = pReq->GetPinToken(); + int32_t status = pReq->GetStatus(); + int32_t reason = pReq->GetReason(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteString(deviceId)) { + LOGE("write deviceId failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteString(token)) { + LOGE("write token failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt32(status)) { + LOGE("write status failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt32(reason)) { + LOGE("write reason failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_VERIFY_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + int32_t result = pReq->GetResult(); + int32_t flag = pReq->GetFlag(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteString(deviceId)) { + LOGE("write deviceId failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt32(result)) { + LOGE("write result failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteInt32(flag)) { + LOGE("write flag failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagname = pReq->GetPkgName(); + std::string paramJson = pReq->GetJsonParam(); + if (!data.WriteString(packagname)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + if (!data.WriteString(paramJson)) { + LOGE("write paramJson failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string extra = data.ReadString(); + LOGI("pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str()); + std::vector deviceList; + int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + int32_t infoNum = deviceList.size(); + DmDeviceInfo deviceInfo; + if (!reply.WriteInt32(infoNum)) { + LOGE("write infoNum failed"); + return DM_WRITE_FAILED; + } + if (!deviceList.empty()) { + for (; !deviceList.empty();) { + deviceInfo = deviceList.back(); + deviceList.pop_back(); + + if (!reply.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { + LOGE("write subscribeInfo failed"); + return DM_WRITE_FAILED; + } + } + } + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + LOGI("GET_TRUST_DEVICE_LIST ok pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str()); + return DM_OK; +} + +ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + sptr listener = data.ReadRemoteObject(); + int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string extra = data.ReadString(); + DmSubscribeInfo *subscribeInfo = (DmSubscribeInfo *)data.ReadRawData(sizeof(DmSubscribeInfo)); + int32_t result = DM_POINT_NULL; + + if (subscribeInfo != nullptr) { + LOGI("pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); + result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo, extra); + } + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + uint16_t subscribeId = data.ReadInt32(); + LOGI("pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeId); + int32_t result = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string extra = data.ReadString(); + std::string deviceId = data.ReadString(); + int32_t authType = data.ReadInt32(); + int32_t result = DM_OK; + result = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + LOGE("AuthenticateDevice"); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + LOGE("AuthenticateDevice %d", result); + return DM_OK; +} + +ON_IPC_CMD(UNAUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string deviceId = data.ReadString(); + int32_t result = DM_OK; + LOGI("pkgName:%s, trustedDeviceInfo: %d", pkgName.c_str(), deviceId.c_str()); + result = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) +{ + LOGI("ON_IPC_CMD VERIFY_AUTHENTICATION start"); + std::string authPara = data.ReadString(); + int32_t result = DeviceManagerService::GetInstance().VerifyAuthentication(authPara); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) +{ + DmDeviceInfo localDeviceInfo; + int32_t result = 0; + result = DeviceManagerService::GetInstance().GetLocalDeviceInfo(localDeviceInfo); + + if (!reply.WriteRawData(&localDeviceInfo, sizeof(DmDeviceInfo))) { + LOGE("write subscribeInfo failed"); + } + + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + LOGI("localDeviceInfo: %s", localDeviceInfo.deviceId); + return DM_OK; +} + +ON_IPC_CMD(GET_UDID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string netWorkId = data.ReadString(); + std::string udid; + int32_t result = DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, netWorkId, udid); + + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + if (!reply.WriteString(udid)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(GET_UUID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string netWorkId = data.ReadString(); + std::string uuid; + int32_t result = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); + + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + if (!reply.WriteString(uuid)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) +{ + std::string packName = data.ReadString(); + DmAuthParam authParam; + int32_t ret = DM_OK; + ret = DeviceManagerService::GetInstance().GetFaParam(packName, authParam); + int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); + int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); + + if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + !reply.WriteString(authParam.authToken) || !reply.WriteString(authParam.packageName) || + !reply.WriteString(authParam.appName) || !reply.WriteString(authParam.appDescription) || + !reply.WriteInt32(authParam.business) || !reply.WriteInt32(authParam.pincode) || + !reply.WriteInt32(appIconLen) || !reply.WriteInt32(appThumbnailLen)) { + LOGE("write reply failed"); + return DM_IPC_FLATTEN_OBJECT; + } + + if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { + if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { + LOGE("write appIcon failed"); + return DM_IPC_FLATTEN_OBJECT; + } + } + if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { + if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { + LOGE("write appThumbnail failed"); + return DM_IPC_FLATTEN_OBJECT; + } + } + return DM_OK; +} + +ON_IPC_CMD(SERVER_USER_AUTH_OPERATION, MessageParcel &data, MessageParcel &reply) +{ + std::string packageName = data.ReadString(); + int32_t action = data.ReadInt32(); + int result = DeviceManagerService::GetInstance().SetUserOperation(packageName, action); + if (!reply.WriteInt32(action)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return result; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp new file mode 100644 index 000000000..28dbc5a5f --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_client_proxy.h" + +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_types.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + sptr remote = Remote(); + if (remote == nullptr) { + LOGE("remote service null"); + return DM_POINT_NULL; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) { + return DM_IPC_FAILED; + } + if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { + LOGE("SendRequest fail, cmd:%d", cmdCode); + return DM_IPC_FAILED; + } + return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp new file mode 100644 index 000000000..a77e3dbbb --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_listener.h" + +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_server_stub.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + std::string pkgName = req->GetPkgName(); + sptr listener = IpcServerStub::GetInstance().GetDmListener(pkgName); + if (listener == nullptr) { + LOGI("cannot get listener for package:%s.", pkgName.c_str()); + return DM_POINT_NULL; + } + return listener->SendCmd(cmdCode, req, rsp); +} + +int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + std::map> listeners = IpcServerStub::GetInstance().GetDmListener(); + for (auto iter : listeners) { + auto pkgName = iter.first; + auto remote = iter.second; + req->SetPkgName(pkgName); + sptr listener = iface_cast(remote); + listener->SendCmd(cmdCode, req, rsp); + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp new file mode 100644 index 000000000..3d3268212 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_stub.h" + +#include +#include + +#include "device_manager_impl.h" +#include "device_manager_service.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "if_system_ability_manager.h" +#include "ipc_cmd_register.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcServerStub); + +const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&IpcServerStub::GetInstance()); + +IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true) +{ + registerToService_ = false; + state_ = ServiceRunningState::STATE_NOT_START; +} + +void IpcServerStub::OnStart() +{ + LOGI("IpcServerStub::OnStart start"); + if (state_ == ServiceRunningState::STATE_RUNNING) { + LOGD("IpcServerStub has already started."); + return; + } + if (!Init()) { + LOGE("failed to init IpcServerStub"); + return; + } + state_ = ServiceRunningState::STATE_RUNNING; +} + +bool IpcServerStub::Init() +{ + LOGI("IpcServerStub::Init ready to init."); + if (!registerToService_) { + bool ret = Publish(this); + if (!ret) { + LOGE("IpcServerStub::Init Publish failed!"); + return false; + } + registerToService_ = true; + } + std::thread{[] { DeviceManagerService::GetInstance().Init(); }}.detach(); + return true; +} + +void IpcServerStub::OnStop() +{ + LOGI("IpcServerStub::OnStop ready to stop service."); + state_ = ServiceRunningState::STATE_NOT_START; + registerToService_ = false; +} + +int32_t IpcServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + LOGI("code = %d, flags= %d.", code, option.GetFlags()); + int32_t ret = DM_OK; + ret = IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply); + if (ret == DM_IPC_NOT_REGISTER_FUNC) { + LOGW("unsupport code: %d", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return ret; +} + +int32_t IpcServerStub::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + return DM_OK; +} + +ServiceRunningState IpcServerStub::QueryServiceState() const +{ + return state_; +} + +int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr listener) +{ + if (pkgName.empty() || listener == nullptr) { + LOGE("Error: parameter invalid"); + return DM_POINT_NULL; + } + LOGI("In, pkgName: %s", pkgName.c_str()); + std::lock_guard autoLock(listenerLock_); + auto iter = dmListener_.find(pkgName); + if (iter != dmListener_.end()) { + LOGI("RegisterDeviceManagerListener: listener already exists"); + return DM_OK; + } + sptr appRecipient = sptr(new AppDeathRecipient()); + if (!listener->AddDeathRecipient(appRecipient)) { + LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); + } + dmListener_[pkgName] = listener; + appRecipient_[pkgName] = appRecipient; + return DM_OK; +} + +int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Error: parameter invalid"); + return DM_POINT_NULL; + } + LOGI("In, pkgName: %s", pkgName.c_str()); + std::lock_guard autoLock(listenerLock_); + auto listenerIter = dmListener_.find(pkgName); + if (listenerIter == dmListener_.end()) { + LOGI("UnRegisterDeviceManagerListener: listener not exists"); + return DM_OK; + } + auto recipientIter = appRecipient_.find(pkgName); + if (recipientIter == appRecipient_.end()) { + LOGI("UnRegisterDeviceManagerListener: appRecipient not exists"); + dmListener_.erase(pkgName); + return DM_OK; + } + auto listener = listenerIter->second; + auto appRecipient = recipientIter->second; + listener->RemoveDeathRecipient(appRecipient); + appRecipient_.erase(pkgName); + dmListener_.erase(pkgName); + return DM_OK; +} + +const std::map> &IpcServerStub::GetDmListener() +{ + return dmListener_; +} + +const sptr IpcServerStub::GetDmListener(std::string pkgName) const +{ + auto iter = dmListener_.find(pkgName); + if (iter == dmListener_.end()) { + return nullptr; + } + auto remote = iter->second; + sptr dmListener = iface_cast(remote); + return dmListener; +} + +void AppDeathRecipient::OnRemoteDied(const wptr &remote) +{ + LOGW("AppDeathRecipient: OnRemoteDied"); + std::map> listeners = IpcServerStub::GetInstance().GetDmListener(); + std::string pkgName; + for (auto iter : listeners) { + if (iter.second == remote.promote()) { + pkgName = iter.first; + break; + } + } + if (pkgName.empty()) { + LOGE("AppDeathRecipient: OnRemoteDied, no pkgName matched"); + return; + } + LOGI("AppDeathRecipient: OnRemoteDied for %s", pkgName.c_str()); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From dfad8f8086cc53530edf7b5815589b47eb0b08eb Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Wed, 12 Jan 2022 22:11:55 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E6=96=B0device=20manager=E5=B7=A5=E7=A8=8B?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=B8=8A=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: cao_liu_chao --- common/include/dm_constants.h | 179 ++++++++++++++++++ .../include/ipc/model/ipc_get_dmfaparam_rsp.h | 43 +++++ .../ipc/model/ipc_get_info_by_network_req.h | 42 ++++ .../ipc/model/ipc_get_info_by_network_rsp.h | 54 ++++++ .../ipc/model/ipc_get_local_device_info_rsp.h | 43 +++++ .../model/ipc_notify_verify_auth_result_req.h | 66 +++++++ .../ipc/model/ipc_unauthenticate_device_req.h | 43 +++++ .../ipc/model/ipc_verify_authenticate_req.h | 42 ++++ ext/pin_auth/BUILD.gn | 67 +++++++ .../include/ability/dm_ability_manager.h | 55 ++++++ ext/pin_auth/include/pin_auth.h | 42 ++++ ext/pin_auth/include/pin_auth_ui.h | 36 ++++ .../src/ability/lite/dm_ability_manager.cpp | 47 +++++ .../ability/standard/dm_ability_manager.cpp | 74 ++++++++ ext/pin_auth/src/pin_auth.cpp | 74 ++++++++ ext/pin_auth/src/pin_auth_ui.cpp | 54 ++++++ ext/profile/BUILD.gn | 75 ++++++++ ext/profile/include/device_profile_adapter.h | 45 +++++ ext/profile/include/profile_connector.h | 56 ++++++ .../include/profile_connector_callback.h | 28 +++ ext/profile/src/device_profile_adapter.cpp | 77 ++++++++ ext/profile/src/profile_connector.cpp | 106 +++++++++++ utils/include/dm_anonymous.h | 28 +++ utils/include/dm_log.h | 44 +++++ utils/include/dm_random.h | 30 +++ utils/src/dm_anonymous.cpp | 61 ++++++ utils/src/dm_log.cpp | 87 +++++++++ utils/src/dm_random.cpp | 113 +++++++++++ 28 files changed, 1711 insertions(+) create mode 100644 common/include/dm_constants.h create mode 100644 common/include/ipc/model/ipc_get_dmfaparam_rsp.h create mode 100644 common/include/ipc/model/ipc_get_info_by_network_req.h create mode 100644 common/include/ipc/model/ipc_get_info_by_network_rsp.h create mode 100644 common/include/ipc/model/ipc_get_local_device_info_rsp.h create mode 100644 common/include/ipc/model/ipc_notify_verify_auth_result_req.h create mode 100644 common/include/ipc/model/ipc_unauthenticate_device_req.h create mode 100644 common/include/ipc/model/ipc_verify_authenticate_req.h create mode 100644 ext/pin_auth/BUILD.gn create mode 100644 ext/pin_auth/include/ability/dm_ability_manager.h create mode 100644 ext/pin_auth/include/pin_auth.h create mode 100644 ext/pin_auth/include/pin_auth_ui.h create mode 100644 ext/pin_auth/src/ability/lite/dm_ability_manager.cpp create mode 100644 ext/pin_auth/src/ability/standard/dm_ability_manager.cpp create mode 100644 ext/pin_auth/src/pin_auth.cpp create mode 100644 ext/pin_auth/src/pin_auth_ui.cpp create mode 100644 ext/profile/BUILD.gn create mode 100644 ext/profile/include/device_profile_adapter.h create mode 100644 ext/profile/include/profile_connector.h create mode 100644 ext/profile/include/profile_connector_callback.h create mode 100644 ext/profile/src/device_profile_adapter.cpp create mode 100644 ext/profile/src/profile_connector.cpp create mode 100644 utils/include/dm_anonymous.h create mode 100644 utils/include/dm_log.h create mode 100644 utils/include/dm_random.h create mode 100644 utils/src/dm_anonymous.cpp create mode 100644 utils/src/dm_log.cpp create mode 100644 utils/src/dm_random.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h new file mode 100644 index 000000000..cd7403f41 --- /dev/null +++ b/common/include/dm_constants.h @@ -0,0 +1,179 @@ +/* + * 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_CONSTANTS_H +#define OHOS_DM_CONSTANTS_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; +const std::string DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; + +const std::string DISCOVER_STATUS_KEY = "persist.distributed_hardware.device_manager.discover_status"; +const std::string DISCOVER_STATUS_ON = "1"; +const std::string DISCOVER_STATUS_OFF = "0"; +const std::string AUTH_LOAD_JSON_KEY = "devicemanager_auth_components"; +const std::string ADAPTER_LOAD_JSON_KEY = "devicemanager_adapter_components"; +const std::string AUTH_JSON_TYPE_KEY = "AUTHENTICATE"; +const std::string CPYPTO_JSON_TYPE_KEY = "CPYPTO"; +const std::string PROFILE_JSON_TYPE_KEY = "PROFILE"; +const std::string DECISION_JSON_TYPE_KEY = "DECISION"; + +const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0; +const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_OSD = 1; +const int32_t LOG_MAX_LEN = 512; +const int32_t MIN_PIN_TOKEN = 10000000; +const int32_t MAX_PIN_TOKEN = 90000000; +const int32_t MIN_PIN_CODE = 100000; +const int32_t MAX_PIN_CODE = 999999; +const int32_t DISCOVER_STATUS_LEN = 20; +const int32_t COMMON_CALLBACK_MAX_SIZE = 200; +// const int32_t TOKEN_LEN = 9; + +enum { + DM_OK = 0, + DM_FAILED = 1000, + DM_TIME_OUT, + DM_NOT_INIT, + DM_INT_MULTIPLE, + DM_INIT_FAILED, + DM_UNINIT_FAILED, + DM_POINT_NULL, + DM_INPUT_PARA_EMPTY, + DM_NOT_SYSTEM_APP, + DM_INVALID_VALUE, + DM_FLATTEN_OBJECT, + DM_MALLOC_ERROR, + DM_COPY_FAILED, + DM_WRITE_FAILED, + DM_DISCOVERY_FAILED, + DM_MAKE_SHARED_FAIL, + DM_SERVICE_NOT_READY, + DM_DEVICE_ALREADY_TRUSTED, + DM_IPC_FAILED = 2000, + DM_IPC_TRANSACTION_FAILED, + DM_IPC_FLATTEN_OBJECT, + DM_IPC_COPY_FAILED, + DM_IPC_SEND_REQUEST_FAILED, + DM_IPC_NOT_REGISTER_FUNC, + DM_IPC_RESPOND_ERROR, + DM_DISCOVERY_REPEATED, + DM_AUTH_NOT_SUPPORT, + DM_AUTH_BUSINESS_BUSY, + DM_AUTH_INPUT_FAILED, + DM_AUTH_STATE_FAILED, + DM_AUTH_DEVICE_AUTHED, + DM_AUTH_OPEN_SESSION_FAILED, + DM_AUTH_PEER_REJECT, + DM_AUTH_NOT_AUTH, + DM_SOFTBUS_FAILED = 3000, + DM_SOFTBUS_CREATE_SESSION_SERVER_FAILED, + DM_HICHAIN_FAILED = 4000, + DM_HICHAIN_GROUP_CREATE_FAILED, + DM_HICHAIN_MEMBER_ADD_FAILED, + DM_HICHAIN_CREATE_CHANNEL_FAILED, +}; +const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; +const std::string HOST_PKG_NAME_KEY = "hostPackageName"; +const std::string TAG_REQUESTER = "REQUESTER"; +const std::string TAG_TOKEN = "TOKEN"; +const std::string TAG_HOST = "HOST"; +const std::string TAG_TARGET = "TARGET"; +const std::string TAG_VISIBILITY = "VISIBILITY"; +const std::string TAG_GROUPIDS = "GROUPIDLIST"; +const std::string TAG_REPLY = "REPLY"; +const std::string TAG_NET_ID = "NETID"; +const std::string TAG_GROUP_ID = "groupId"; +const std::string TAG_GROUP_NAME = "GROUPNAME"; +const std::string TAG_REQUEST_ID = "REQUESTID"; +const std::string TAG_DEVICE_ID = "DEVICEID"; +const std::string TAG_LOCAL_DEVICE_ID = "LOCALDEVICEID"; +const std::string TAG_DEVICE_TYPE = "DEVICETYPE"; +const std::string TAG_APP_NAME = "APPNAME"; +const std::string TAG_APP_DESCRIPTION = "APPDESC"; +const std::string TAG_APP_ICON = "APPICON"; +const std::string TAG_APP_THUMBNAIL = "APPTHUM"; +const std::string TAG_INDEX = "INDEX"; +const std::string TAG_SLICE_NUM = "SLICE"; +const std::string TAG_THUMBNAIL_SIZE = "THUMSIZE"; +const std::string TAG_AUTH_TYPE = "AUTHTYPE"; +const std::string TAG_CRYPTO_SUPPORT = "CRYPTOSUPPORT"; +const std::string TAG_CRYPTO_NAME = "CRYPTONAME"; +const std::string TAG_CRYPTO_VERSION = "CRYPTOVERSION"; +const std::string TAG_VER = "ITF_VER"; +const std::string TAG_TYPE = "MSG_TYPE"; +const std::string DM_ITF_VER_1_0 = "1.0"; +const std::string DM_ITF_VER = "1.1"; +const std::string TAG = "DM_MSG_CODEC"; +const std::string APP_NAME_KEY = "appName"; +const std::string APP_DESCRIPTION_KEY = "appDescription"; +const std::string APP_ICON_KEY = "appIcon"; +const std::string APP_THUMBNAIL_KEY = "appThumbnailKey"; +const std::string APP_THUMBNAIL_LEN = "appThumbnailLen"; +const std::string APP_THUMBNAIL = "appThumbnail"; +const std::string CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; +const int32_t MSG_MAX_SIZE = 45 * 1024; +const int32_t AUTH_REPLY_ACCEPT = 0; +const int32_t ENCRYPT_TAG_LEN = 32; + +// pin +const int32_t DISPLAY_OWNER_SYSTEM = 0; +const int32_t DISPLAY_OWNER_OTHER = 1; +const int32_t BUSINESS_FA_MIRGRATION = 0; +const int32_t BUSINESS_RESOURCE_ACCESS = 1; + +// json +const std::string AUTH_TYPE = "authType"; +const std::string TOKEN = "token"; +const std::string PIN_TOKEN = "pinToken"; +const std::string PIN_CODE_KEY = "pinCode"; +const int32_t AUTH_TYPE_PIN = 1; +const int32_t AUTH_TYPE_SCAN = 2; +const int32_t AUTH_TYPE_TOUCH = 3; +const int32_t DEFAULT_PIN_CODE = 0; +const int32_t DEFAULT_PIN_TOKEN = 0; + +// Softbus +const int32_t SOFTBUS_CHECK_INTERVAL = 100000; // 100ms +const uint32_t SOFTBUS_SUBSCRIBE_ID_PREFIX_LEN = 16; +const int32_t SOFTBUS_SUBSCRIBE_ID_MASK = 0x0000FFFF; +const int32_t SOFTBUS_DISCOVER_DEVICE_INFO_MAX_SIZE = 20; +const int32_t AUTH_SESSION_SIDE_SERVER = 0; +const int32_t AUTH_SESSION_SIDE_CLIENT = 1; +const static char *DM_CAPABILITY_OSD = "osdCapability"; + +// HiChain +const int32_t DEVICE_UUID_LENGTH = 65; +const int32_t GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP = 1; +const int32_t GROUP_TYPE_PEER_TO_PEER_GROUP = 256; +const int32_t GROUP_VISIBILITY_PUBLIC = -1; +const int64_t MIN_REQUEST_ID = 1000000000; +const int64_t MAX_REQUEST_ID = 9999999999; +const int32_t FIELD_EXPIRE_TIME_VALUE = 7; +const int32_t GROUP_VISIBILITY_IS_PUBLIC = -1; +const int32_t GROUP_VISIBILITY_IS_PRIVATE = 0; +const std::string DEVICE_ID = "DEVICE_ID"; +const std::string WIFI_IP = "WIFI_IP"; +const std::string WIFI_PORT = "WIFI_PORT"; +const std::string BR_MAC = "BR_MAC"; +const std::string BLE_MAC = "BLE_MAC"; +const std::string ETH_IP = "ETH_IP"; +const std::string ETH_PORT = "ETH_PORT"; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h new file mode 100644 index 000000000..ed4b8958a --- /dev/null +++ b/common/include/ipc/model/ipc_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_IPC_GET_DM_FA_PARAM_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_GET_DM_FA_PARAM_RSP_H + +#include "dm_device_info.h" +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetDmFaParamRsp : public IpcRsp { + DECLARE_IPC_MODEL(IpcGetDmFaParamRsp); + +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_IPC_GET_DM_FA_PARAM_RSP_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_get_info_by_network_req.h b/common/include/ipc/model/ipc_get_info_by_network_req.h new file mode 100644 index 000000000..786b7d58f --- /dev/null +++ b/common/include/ipc/model/ipc_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_IPC_GET_INFO_BY_NETWORK_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_GET_INFO_BY_NETWORK_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetInfoByNetWorkReq : public IpcReq { + DECLARE_IPC_MODEL(IpcGetInfoByNetWorkReq); + +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_IPC_GET_INFO_BY_NETWORK_REQ_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_get_info_by_network_rsp.h b/common/include/ipc/model/ipc_get_info_by_network_rsp.h new file mode 100644 index 000000000..18dd12b4f --- /dev/null +++ b/common/include/ipc/model/ipc_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_IPC_GET_INFO_BY_NETWORK_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_GET_INFO_BY_NETWORK_RSP_H + +#include + +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetInfoByNetWorkRsp : public IpcRsp { + DECLARE_IPC_MODEL(IpcGetInfoByNetWorkRsp); + +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_IPC_GET_INFO_BY_NETWORK_RSP_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_get_local_device_info_rsp.h b/common/include/ipc/model/ipc_get_local_device_info_rsp.h new file mode 100644 index 000000000..7494da0fe --- /dev/null +++ b/common/include/ipc/model/ipc_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_DM_IPC_GET_LOCAL_DEVICE_INFO_RSP_H +#define OHOS_DM_IPC_GET_LOCAL_DEVICE_INFO_RSP_H + +#include "dm_device_info.h" +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetLocalDeviceInfoRsp : public IpcRsp { + DECLARE_IPC_MODEL(IpcGetLocalDeviceInfoRsp); + +public: + const DmDeviceInfo &GetLocalDeviceInfo() const + { + return localDeviceInfo_; + } + + void SetLocalDeviceInfo(const DmDeviceInfo &localDeviceInfo) + { + localDeviceInfo_ = localDeviceInfo; + } + +private: + DmDeviceInfo localDeviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_GET_LOCAL_DEVICE_INFO_RSP_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_notify_verify_auth_result_req.h b/common/include/ipc/model/ipc_notify_verify_auth_result_req.h new file mode 100644 index 000000000..df01942ff --- /dev/null +++ b/common/include/ipc/model/ipc_notify_verify_auth_result_req.h @@ -0,0 +1,66 @@ +/* + * 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_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H +#define OHOS_DM_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H + +#include + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyVerifyAuthResultReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyVerifyAuthResultReq); + +public: + std::string GetDeviceId() const + { + return deviceId_; + } + + void SetDeviceId(const std::string &deviceId) + { + deviceId_ = deviceId; + } + + int32_t GetResult() const + { + return result_; + } + + void SetResult(int32_t result) + { + result_ = result; + } + + int32_t GetFlag() const + { + return flag_; + } + + void SetFlag(int32_t flag) + { + flag_ = flag; + } + +private: + std::string deviceId_; + int32_t result_{0}; + int32_t flag_{0}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H diff --git a/common/include/ipc/model/ipc_unauthenticate_device_req.h b/common/include/ipc/model/ipc_unauthenticate_device_req.h new file mode 100644 index 000000000..78244377a --- /dev/null +++ b/common/include/ipc/model/ipc_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_DM_IPC_UNAUTHENTICATE_DEVICE_REQ_H +#define OHOS_DM_IPC_UNAUTHENTICATE_DEVICE_REQ_H + +#include "dm_device_info.h" +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcUnAuthenticateDeviceReq : public IpcReq { + DECLARE_IPC_MODEL(IpcUnAuthenticateDeviceReq); + +public: + const DmDeviceInfo &GetDeviceInfo() const + { + return deviceInfo_; + } + + void SetDeviceInfo(const DmDeviceInfo &deviceInfo) + { + deviceInfo_ = deviceInfo; + } + +private: + DmDeviceInfo deviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_UNAUTHENTICATE_DEVICE_REQ_H diff --git a/common/include/ipc/model/ipc_verify_authenticate_req.h b/common/include/ipc/model/ipc_verify_authenticate_req.h new file mode 100644 index 000000000..3c2df5547 --- /dev/null +++ b/common/include/ipc/model/ipc_verify_authenticate_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_IPC_VERIFY_AUTHENTICATE_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_VERIFY_AUTHENTICATE_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcVerifyAuthenticateReq : public IpcReq { + DECLARE_IPC_MODEL(IpcVerifyAuthenticateReq); + +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_IPC_VERIFY_AUTHENTICATE_REQ_H diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn new file mode 100644 index 000000000..cc8cfcefc --- /dev/null +++ b/ext/pin_auth/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} + +import("//foundation/distributedhardware/devicemanager/devicemanager.gni") + +if (defined(ohos_lite)) { +} else { + ohos_shared_library("devicemanagerext_pin_auth") { + include_dirs = [ + "include", + "${common_path}/include", + "${services_path}/include/adapter", + "${ext_path}/pin_auth/include/ability", + "${services_path}/include/authentication", + "${utils_path}/include", + ] + + sources = [ + "src/ability/standard/dm_ability_manager.cpp", + "src/pin_auth.cpp", + "src/pin_auth_ui.cpp", + ] + + deps = [ + "${utils_path}:devicemanagerutils", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//utils/native/base:utils", + ] + + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "startup_l2:syspara", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerext\"", + "LOG_DOMAIN=0xD004100", + ] + + subsystem_name = "distributedhardware" + + part_name = "device_manager_base" + } +} \ No newline at end of file diff --git a/ext/pin_auth/include/ability/dm_ability_manager.h b/ext/pin_auth/include/ability/dm_ability_manager.h new file mode 100644 index 000000000..225fefc62 --- /dev/null +++ b/ext/pin_auth/include/ability/dm_ability_manager.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_ABILITY_MANAGER_H +#define OHOS_DM_ABILITY_MANAGER_H + +#include + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +enum AbilityRole { ABILITY_ROLE_PASSIVE = 0, ABILITY_ROLE_INITIATIVE = 1, ABILITY_ROLE_UNKNOWN = 2 }; + +enum AbilityStatus { ABILITY_STATUS_FAILED = 0, ABILITY_STATUS_SUCCESS = 1, ABILITY_STATUS_START = 2 }; + +enum FaAction { + USER_OPERATION_TYPE_ALLOW_AUTH = 0, + USER_OPERATION_TYPE_CANCEL_AUTH = 1, + USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT = 2, + USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY = 3, + USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT = 4 +}; + +class DmAbilityManager { +public: + AbilityRole GetAbilityRole(); + AbilityStatus StartAbility(AbilityRole role); + void StartAbilityDone(); + +private: + void waitForTimeout(uint32_t timeout_s); + +private: + sem_t mSem_; + AbilityStatus mStatus_; + AbilityRole mAbilityStatus_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_ABILITY_MANAGER_H diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h new file mode 100644 index 000000000..2129c94a1 --- /dev/null +++ b/ext/pin_auth/include/pin_auth.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_DM_PIN_AUTH_H +#define OHOS_DM_PIN_AUTH_H + +#include +#include + +#include "authentication.h" +#include "dm_ability_manager.h" +#include "pin_auth_ui.h" + +namespace OHOS { +namespace DistributedHardware { +class PinAuth : public IAuthentication { +public: + PinAuth(); + ~PinAuth(); + int32_t ShowAuthInfo() override; + int32_t StartAuth(std::shared_ptr dmAbilityManager) override; + int32_t VerifyAuthentication(std::string pinToken, int32_t code, const std::string &authParam) override; + +private: + int32_t times_ = 0; + std::shared_ptr pinAuthUi_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PIN_AUTH_H diff --git a/ext/pin_auth/include/pin_auth_ui.h b/ext/pin_auth/include/pin_auth_ui.h new file mode 100644 index 000000000..f8910cba2 --- /dev/null +++ b/ext/pin_auth/include/pin_auth_ui.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PIN_AUTH_UI_H +#define OHOS_DM_PIN_AUTH_UI_H + +#include + +#include "dm_ability_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class PinAuthUi { +public: + PinAuthUi(); + int32_t ShowPinDialog(); + int32_t InputPinDialog(std::shared_ptr dmAbilityManager); + +private: + int32_t StartFaUiService(std::shared_ptr dmAbilityManager); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PIN_AUTH_UI_H diff --git a/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp new file mode 100644 index 000000000..451123305 --- /dev/null +++ b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_ability_manager.h" + +namespace OHOS { +namespace DistributedHardware { +AbilityRole DmAbilityManager::GetAbilityRole() +{ + return mAbilityStatus_; +} + +AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) +{ + // not support for L1 yet, do nothing. just save status and role + mAbilityStatus_ = role; + mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + return mStatus_; +} + +void DmAbilityManager::waitForTimeout(uint32_t timeout_s) +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout_s; + sem_timedwait(&mSem_, &ts); +} + +void DmAbilityManager::StartAbilityDone() +{ + mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + sem_post(&mSem_); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp new file mode 100644 index 000000000..e2b026f1c --- /dev/null +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_ability_manager.h" + +#include "ability_manager_client.h" +#include "ability_manager_service.h" +#include "ability_record.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "parameter.h" +#include "semaphore.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const int32_t ABILITY_START_TIMEOUT = 3; // 3 second +const std::string bundleUiName = "com.ohos.devicemanagerui"; +const std::string abilityUiName = "com.ohos.devicemanagerui.MainAbility"; +} // namespace + +AbilityRole DmAbilityManager::GetAbilityRole() +{ + return mAbilityStatus_; +} + +AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) +{ + mAbilityStatus_ = role; + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string deviceId = localDeviceId; + mStatus_ = ABILITY_STATUS_START; + AAFwk::Want want; + AppExecFwk::ElementName element(deviceId, bundleUiName, abilityUiName); + want.SetElement(element); + AAFwk::AbilityManagerClient::GetInstance()->Connect(); + ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); + if (result != OHOS::ERR_OK) { + LOGE("Start Ability faild"); + mStatus_ = ABILITY_STATUS_FAILED; + return mStatus_; + } + waitForTimeout(ABILITY_START_TIMEOUT); + return mStatus_; +} + +void DmAbilityManager::waitForTimeout(uint32_t timeout_s) +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout_s; + sem_timedwait(&mSem_, &ts); +} + +void DmAbilityManager::StartAbilityDone() +{ + mStatus_ = ABILITY_STATUS_SUCCESS; + sem_post(&mSem_); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp new file mode 100644 index 000000000..781a375fb --- /dev/null +++ b/ext/pin_auth/src/pin_auth.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pin_auth.h" + +#include + +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +PinAuth::PinAuth() +{ + LOGI("PinAuth constructor"); +} + +PinAuth::~PinAuth() +{ +} + +int32_t PinAuth::ShowAuthInfo() +{ + return pinAuthUi_->ShowPinDialog(); +} + +int32_t PinAuth::StartAuth(std::shared_ptr dmAbilityManager) +{ + times_ = 0; + return pinAuthUi_->InputPinDialog(dmAbilityManager); +} + +int32_t PinAuth::VerifyAuthentication(std::string pinToken, int32_t code, const std::string &authParam) +{ + times_ += 1; + nlohmann::json jsonObject = nlohmann::json::parse(authParam, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + if (!jsonObject.contains(PIN_CODE_KEY) && !jsonObject.contains(PIN_TOKEN)) { + LOGE("err json string, first time"); + return DM_FAILED; + } + int32_t inputPinCode = jsonObject[PIN_CODE_KEY]; + int32_t inputPinToken = jsonObject[PIN_TOKEN]; + if (code == inputPinCode && stoi(pinToken) == inputPinToken) { + return DM_OK; + } else if (code != inputPinCode && times_ < 3) { + return DM_AUTH_INPUT_FAILED; + } else { + return DM_FAILED; + } +} + +extern "C" IAuthentication *CreatePinAuthObject(void) +{ + return new PinAuth; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp new file mode 100644 index 000000000..15dd767ab --- /dev/null +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pin_auth_ui.h" + +#include "dm_ability_manager.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +PinAuthUi::PinAuthUi() +{ + LOGI("AuthUi constructor"); +} + +int32_t PinAuthUi::ShowPinDialog() +{ + return DM_OK; +} + +int32_t PinAuthUi::InputPinDialog(std::shared_ptr dmAbilityManager) +{ + if (dmAbilityManager == nullptr) { + LOGE("PinAuthUi::dmAbilityManager is null"); + return DM_FAILED; + } + return StartFaUiService(dmAbilityManager); +} + +int32_t PinAuthUi::StartFaUiService(std::shared_ptr dmAbilityManager) +{ + AbilityStatus status = dmAbilityManager->StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); + if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { + LOGE("PinAuthUi::StartFaService timeout"); + return DM_FAILED; + } + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn new file mode 100644 index 000000000..4ac238c37 --- /dev/null +++ b/ext/profile/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} + +import("//foundation/distributedhardware/devicemanager/devicemanager.gni") + +if (defined(ohos_lite)) { +} else { + ohos_shared_library("devicemanagerext_profile") { + include_dirs = [ + "include", + "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${ext_path}/profile/include", + "${services_path}/include", + "${services_path}/include/adapter", + "${services_path}/include/dependency/softbus", + "${services_path}/include/ipc/standard", + "${services_path}/include/devicestate", + "${utils_path}/include", + "${utils_path}/include/ipc/standard", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc", + "${innerkits_path}/native_cpp/include/ipc/standard", + "//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", + ] + + sources = [ + "src/device_profile_adapter.cpp", + "src/profile_connector.cpp", + ] + + deps = [ + "${services_path}:devicemanagerservice", + "${utils_path}:devicemanagerutils", + "//utils/native/base:utils", + ] + + external_deps = [ + "device_profile_core:distributed_device_profile_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerext\"", + "LOG_DOMAIN=0xD004100", + ] + + subsystem_name = "distributedhardware" + + part_name = "device_manager_base" + } +} \ No newline at end of file diff --git a/ext/profile/include/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h new file mode 100644 index 000000000..d27b71fd0 --- /dev/null +++ b/ext/profile/include/device_profile_adapter.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_ADAPTER_DEVICE_PROFILE_H +#define OHOS_DM_ADAPTER_DEVICE_PROFILE_H + +#include +#include + +#include "profile_adapter.h" +#include "profile_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceProfileAdapter : public IProfileAdapter, public IProfileConnectorCallback { + +public: + DeviceProfileAdapter(); + ~DeviceProfileAdapter(); + int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback); + int32_t UnRegisterProfileListener(const std::string &pkgName); + int32_t OnProfileClientDeviceReady(const std::string &pkgName, const std::string &deviceId); + void OnProfileChanged(const std::string &pkgName, const std::string &deviceId); + void OnProfileComplete(const std::string &pkgName, const std::string &deviceId); + +private: + std::shared_ptr deviceProfileAdapterCallback_; + static std::shared_ptr profileConnector_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_ADAPTER_DEVICE_PROFILE_H diff --git a/ext/profile/include/profile_connector.h b/ext/profile/include/profile_connector.h new file mode 100644 index 000000000..d83f90749 --- /dev/null +++ b/ext/profile/include/profile_connector.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PROFILE_CONNECTOR_H +#define OHOS_DM_PROFILE_CONNECTOR_H + +#include +#include +#include +#include +#include + +#include "distributed_device_profile_client.h" +#include "profile_connector_callback.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::DeviceProfile; + +class ProfileEventCallback : public IProfileEventCallback { +public: + void OnSyncCompleted(const SyncResult &syncResults); + int32_t RegisterProfileCallback(const std::string &pkgName, std::shared_ptr callback); + int32_t UnRegisterProfileCallback(const std::string &pkgName); + +public: + static std::map> profileConnectorCallback_; +}; + +class ProfileConnector : public IProfileEventCallback { +public: + int32_t RegisterProfileCallback(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback); + int32_t UnRegisterProfileCallback(const std::string &pkgName); + int32_t SubscribeProfileEvents(const std::list &serviceIds, const std::string &deviceId); + int32_t UnSubscribeProfileEvents(); + +private: + static std::shared_ptr profileEventCallback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PROFILE_CONNECTOR_H \ No newline at end of file diff --git a/ext/profile/include/profile_connector_callback.h b/ext/profile/include/profile_connector_callback.h new file mode 100644 index 000000000..70738fbfe --- /dev/null +++ b/ext/profile/include/profile_connector_callback.h @@ -0,0 +1,28 @@ +/* + * 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_PROFILE_CONNECTOR_CALLBACK_H +#define OHOS_DM_PROFILE_CONNECTOR_CALLBACK_H + +namespace OHOS { +namespace DistributedHardware { +class IProfileConnectorCallback { +public: + virtual void OnProfileChanged(const std::string &pkgName, const std::string &deviceId) = 0; + virtual void OnProfileComplete(const std::string &pkgName, const std::string &deviceId) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PROFILE_CONNECTOR_CALLBACK_H \ No newline at end of file diff --git a/ext/profile/src/device_profile_adapter.cpp b/ext/profile/src/device_profile_adapter.cpp new file mode 100644 index 000000000..61d82e492 --- /dev/null +++ b/ext/profile/src/device_profile_adapter.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_profile_adapter.h" + +#include "dm_constants.h" +#include "dm_device_state_manager.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +std::shared_ptr DeviceProfileAdapter::profileConnector_ = std::make_shared(); + +DeviceProfileAdapter::DeviceProfileAdapter() +{ +} + +DeviceProfileAdapter::~DeviceProfileAdapter() +{ +} + +int32_t DeviceProfileAdapter::RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback) +{ + LOGI("DeviceProfileAdapter::RegisterProfileListener"); + deviceProfileAdapterCallback_ = callback; + profileConnector_->RegisterProfileCallback(pkgName, deviceId, std::shared_ptr(this)); + return DM_OK; +} + +int32_t DeviceProfileAdapter::UnRegisterProfileListener(const std::string &pkgName) +{ + LOGI("DeviceProfileAdapter::RegisterProfileListener"); + deviceProfileAdapterCallback_ = nullptr; + profileConnector_->UnRegisterProfileCallback(pkgName); + return DM_OK; +} + +int32_t DeviceProfileAdapter::OnProfileClientDeviceReady(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("DeviceProfileAdapter::OnProfileClientDeviceReady"); + if (nullptr != deviceProfileAdapterCallback_) { + deviceProfileAdapterCallback_->OnProfileReady(pkgName, deviceId); + } else { + LOGI("deviceProfileAdapterCallback_ is nullptr"); + } + return DM_OK; +} + +void DeviceProfileAdapter::OnProfileChanged(const std::string &pkgName, const std::string &deviceId) +{ + OnProfileClientDeviceReady(pkgName, deviceId); +} + +void DeviceProfileAdapter::OnProfileComplete(const std::string &pkgName, const std::string &deviceId) +{ + OnProfileClientDeviceReady(pkgName, deviceId); +} + +extern "C" IProfileAdapter *CreateDeviceProfileObject(void) +{ + return new DeviceProfileAdapter; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/ext/profile/src/profile_connector.cpp b/ext/profile/src/profile_connector.cpp new file mode 100644 index 000000000..a1a271064 --- /dev/null +++ b/ext/profile/src/profile_connector.cpp @@ -0,0 +1,106 @@ +/* + * 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 "profile_connector.h" + +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + +std::map> ProfileEventCallback::profileConnectorCallback_ = {}; +std::shared_ptr ProfileConnector::profileEventCallback_ = + std::make_shared(); + +int32_t ProfileConnector::RegisterProfileCallback(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback) +{ + LOGI("ProfileConnector::RegisterProfileCallback"); + profileEventCallback_->RegisterProfileCallback(pkgName, callback); + SubscribeProfileEvents({"system", "device", "fakeStorage", "fakeSystem"}, deviceId); + return DM_OK; +} + +int32_t ProfileConnector::UnRegisterProfileCallback(const std::string &pkgName) +{ + LOGI("ProfileConnector::UnRegisterProfileCallback"); + profileEventCallback_->UnRegisterProfileCallback(pkgName); + return DM_OK; +} + +int32_t ProfileConnector::SubscribeProfileEvents(const std::list &serviceIds, const std::string &deviceId) +{ + ExtraInfo extraInfo; + extraInfo["deviceId"] = deviceId; + extraInfo["serviceIds"] = serviceIds; + + std::list subscribeInfos; + + SubscribeInfo eventSync; + eventSync.profileEvent = ProfileEvent::EVENT_SYNC_COMPLETED; + subscribeInfos.emplace_back(eventSync); + + std::list failedEvents; + u_int32_t errCode; + errCode = DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents(subscribeInfos, + profileEventCallback_, failedEvents); + LOGI("ProfileConnector::SubscribeProfileEvents result=%d", errCode); + return DM_OK; +} + +int32_t ProfileConnector::UnSubscribeProfileEvents() +{ + std::list profileEvents; + profileEvents.emplace_back(ProfileEvent::EVENT_PROFILE_CHANGED); + profileEvents.emplace_back(ProfileEvent::EVENT_SYNC_COMPLETED); + std::list failedEvents; + u_int32_t errCode; + errCode = DistributedDeviceProfileClient::GetInstance().UnsubscribeProfileEvents( + profileEvents, profileEventCallback_, failedEvents); + LOGI("ProfileConnector::UnSubscribeProfileEvents result=%d", errCode); + return DM_OK; +} + +int32_t ProfileEventCallback::RegisterProfileCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + LOGI("ProfileEventCallback::RegisterProfileCallback"); + profileConnectorCallback_.emplace(pkgName, callback); + return DM_OK; +} + +int32_t ProfileEventCallback::UnRegisterProfileCallback(const std::string &pkgName) +{ + LOGI("ProfileEventCallback::UnRegisterProfileCallback"); + profileConnectorCallback_.erase(pkgName); + return DM_OK; +} + +void ProfileEventCallback::OnSyncCompleted(const SyncResult &syncResults) +{ + std::string deviceId; + u_int32_t SyncStatus; + for (auto &iterResult : syncResults) { + deviceId = iterResult.first; + SyncStatus = iterResult.second; + } + LOGI("ProfileEventCallback::OnSyncCompleted, deviceId = %s", deviceId.c_str()); + for (auto &iter : profileConnectorCallback_) { + iter.second->OnProfileComplete(iter.first, deviceId); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/utils/include/dm_anonymous.h b/utils/include/dm_anonymous.h new file mode 100644 index 000000000..d8059e0b1 --- /dev/null +++ b/utils/include/dm_anonymous.h @@ -0,0 +1,28 @@ +/* + * 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_ANONYMOUS_H +#define OHOS_DM_ANONYMOUS_H + +#include + +namespace OHOS { +namespace DistributedHardware { +std::string GetAnonyString(const std::string &value); +std::string GetAnonyInt32(const int32_t value); +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_ANONYMOUS_H \ No newline at end of file diff --git a/utils/include/dm_log.h b/utils/include/dm_log.h new file mode 100644 index 000000000..cd0415926 --- /dev/null +++ b/utils/include/dm_log.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_DM_LOG_H +#define OHOS_DM_LOG_H + +namespace OHOS { +namespace DistributedHardware { + +typedef enum { + DM_LOG_DEBUG, + DM_LOG_INFO, + DM_LOG_WARN, + DM_LOG_ERROR, +} DMLogLevel; + +void DMLog(DMLogLevel logLevel, const char *fmt, ...); + +#define LOGD(fmt, ...) \ + DMLog(DM_LOG_DEBUG, (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define LOGI(fmt, ...) \ + DMLog(DM_LOG_INFO, (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define LOGW(fmt, ...) \ + DMLog(DM_LOG_WARN, (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#define LOGE(fmt, ...) \ + DMLog(DM_LOG_ERROR, (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_LOG_H diff --git a/utils/include/dm_random.h b/utils/include/dm_random.h new file mode 100644 index 000000000..dcbe1ef1e --- /dev/null +++ b/utils/include/dm_random.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_RANDOM_H +#define OHOS_DM_RANDOM_H + +#include + +namespace OHOS { +namespace DistributedHardware { +int32_t GenRandInt(int32_t randMin, int32_t randMax); +int64_t GenRandLongLong(int64_t randMin, int64_t randMax); +int32_t GetRandomData(uint8_t *randStr, uint32_t len); +bool MbedtlsGenRandomStr(char *szOut, int32_t szOutLen, bool numberOnly); +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_RANDOM_H diff --git a/utils/src/dm_anonymous.cpp b/utils/src/dm_anonymous.cpp new file mode 100644 index 000000000..8d9a7be38 --- /dev/null +++ b/utils/src/dm_anonymous.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_anonymous.h" + +namespace OHOS { +namespace DistributedHardware { +std::string GetAnonyString(const std::string &value) +{ + const int32_t INT32_SHORT_ID_LENGTH = 20; + const int32_t INT32_PLAINTEXT_LENGTH = 4; + const int32_t INT32_MIN_ID_LENGTH = 3; + + std::string tmpStr("******"); + int32_t strLen = value.length(); + if (strLen < INT32_MIN_ID_LENGTH) { + return tmpStr; + } + + std::string res; + if (strLen <= INT32_SHORT_ID_LENGTH) { + res += value[0]; + res += tmpStr; + res += value[strLen - 1]; + } else { + res.append(value, 0, INT32_PLAINTEXT_LENGTH); + res += tmpStr; + res.append(value, strLen - INT32_PLAINTEXT_LENGTH, INT32_PLAINTEXT_LENGTH); + } + + return res; +} + +std::string GetAnonyInt32(const int32_t value) +{ + std::string tempString = std::to_string(value); + int32_t length = tempString.length(); + if (length == 0x01) { + tempString[0] = '*'; + return tempString; + } + + for (int32_t i = 1; i < length - 1; i++) { + tempString[i] = '*'; + } + return tempString; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/utils/src/dm_log.cpp b/utils/src/dm_log.cpp new file mode 100644 index 000000000..2284eabda --- /dev/null +++ b/utils/src/dm_log.cpp @@ -0,0 +1,87 @@ +/* + * 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_log.h" + +#include "dm_constants.h" +#include "securec.h" + +#ifdef HI_LOG_ENABLE +#include "hilog/log.h" +#else +#include +#endif + +namespace OHOS { +namespace DistributedHardware { +static void DMLogOut(DMLogLevel logLevel, const char *logBuf) +{ +#ifdef HI_LOG_ENABLE + LogLevel hiLogLevel = LOG_INFO; + switch (logLevel) { + case DM_LOG_DEBUG: + hiLogLevel = LOG_DEBUG; + break; + case DM_LOG_INFO: + hiLogLevel = LOG_INFO; + break; + case DM_LOG_WARN: + hiLogLevel = LOG_WARN; + break; + case DM_LOG_ERROR: + hiLogLevel = LOG_ERROR; + break; + default: + break; + } + (void)HiLogPrint(LOG_CORE, hiLogLevel, LOG_DOMAIN, "", "%{public}s", logBuf); +#else + switch (logLevel) { + case DM_LOG_DEBUG: + printf("[D]%s\n", logBuf); + break; + case DM_LOG_INFO: + printf("[I]%s\n", logBuf); + break; + case DM_LOG_WARN: + printf("[W]%s\n", logBuf); + break; + case DM_LOG_ERROR: + printf("[E]%s\n", logBuf); + break; + default: + break; + } +#endif +} + +void DMLog(DMLogLevel logLevel, const char *fmt, ...) +{ + char logBuf[LOG_MAX_LEN] = {0}; + va_list arg; + int32_t ret = 0; + + (void)memset_s(&arg, sizeof(va_list), 0, sizeof(va_list)); + va_start(arg, fmt); + ret = vsprintf_s(logBuf, sizeof(logBuf), fmt, arg); + va_end(arg); + if (ret < 0) { + DMLogOut(logLevel, "DM log length error."); + return; + } + DMLogOut(logLevel, logBuf); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/src/dm_random.cpp b/utils/src/dm_random.cpp new file mode 100644 index 000000000..129b0792e --- /dev/null +++ b/utils/src/dm_random.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_random.h" + +#include + +#include "dm_constants.h" +#include "mbedtls/base64.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" +#include "mbedtls/gcm.h" +#include "mbedtls/md.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t GenRandInt(int32_t randMin, int32_t randMax) +{ + std::random_device randDevice; + std::mt19937 genRand(randDevice()); + std::uniform_int_distribution disRand(randMin, randMax); + return disRand(genRand); +} + +int64_t GenRandLongLong(int64_t randMin, int64_t randMax) +{ + std::random_device randDevice; + std::mt19937 genRand(randDevice()); + std::uniform_int_distribution disRand(randMin, randMax); + return disRand(genRand); +} + +int32_t GetRandomData(uint8_t *randStr, uint32_t len) +{ + mbedtls_entropy_context *entropy = nullptr; + mbedtls_ctr_drbg_context *ctrDrbg = nullptr; + int32_t ret = DM_FAILED; + do { + if (randStr == nullptr || len == 0) { + break; + } + entropy = (mbedtls_entropy_context *)malloc(sizeof(mbedtls_entropy_context)); + if (entropy == nullptr) { + break; + } + ctrDrbg = (mbedtls_ctr_drbg_context *)malloc(sizeof(mbedtls_ctr_drbg_context)); + if (ctrDrbg == nullptr) { + break; + } + mbedtls_ctr_drbg_init(ctrDrbg); + mbedtls_entropy_init(entropy); + ret = mbedtls_ctr_drbg_seed(ctrDrbg, mbedtls_entropy_func, entropy, nullptr, 0); + if (ret != 0) { + break; + } + ret = mbedtls_ctr_drbg_random(ctrDrbg, randStr, len); + if (ret != 0) { + break; + } + ret = DM_OK; + } while (0); + if (entropy != nullptr) { + free(entropy); + } + if (ctrDrbg != nullptr) { + free(ctrDrbg); + } + return ret; +} + +bool MbedtlsGenRandomStr(char *szOut, int32_t szOutLen, bool numberOnly) +{ + const int32_t MIN_OUT_LENGTH = 2; + if (szOut == nullptr || szOutLen <= MIN_OUT_LENGTH) { + return false; + } + szOut[--szOutLen] = 0; + GetRandomData((uint8_t *)szOut, szOutLen); + const int32_t NUMBER_COUNT = 10; + const int32_t ALPHA_COUNT = 26; + const int32_t ALPHA_BYTE_COUNT = 2; + int32_t M = numberOnly ? NUMBER_COUNT : (NUMBER_COUNT + ALPHA_BYTE_COUNT * ALPHA_COUNT); + for (int32_t i = 0; i < szOutLen; i++) { + // 0~9,A~Z,a~z + uint32_t idx = ((uint32_t)szOut[i] % M); + char base; + if (idx < NUMBER_COUNT) { + base = '0'; + } else if (idx >= NUMBER_COUNT && idx < (NUMBER_COUNT + ALPHA_COUNT)) { + base = 'A'; + idx -= NUMBER_COUNT; + } else { + base = 'a'; + idx -= (NUMBER_COUNT + ALPHA_COUNT); + } + szOut[i] = base + idx; + } + return true; +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From a7c0e655e37337d669053bfe9faaf700d07af7cd Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Thu, 13 Jan 2022 09:19:34 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E6=B6=88=E9=99=A4L1=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E6=8A=A5=E9=94=99=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: cao_liu_chao --- BUILD.gn | 3 - interfaces/inner_kits/native_cpp/BUILD.gn | 46 ----------- services/devicemanagerservice/BUILD.gn | 79 ------------------- .../src/ipc/lite/ipc_server_main.cpp | 26 +----- utils/BUILD.gn | 47 +---------- 5 files changed, 2 insertions(+), 199 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index cb9b6a6fa..4dc0f09e4 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -18,9 +18,6 @@ if (defined(ohos_lite)) { if (ohos_kernel_type == "liteos_m") { } else { features = [ - "utils:devicemanagerutils", - "services/devicemanagerservice:devicemanagerservice", - "interfaces/inner_kits/native_cpp:devicemanagersdk", ] } } diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 2dbc348fd..16d7100cd 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -20,52 +20,6 @@ import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { shared_library("devicemanagersdk") { - include_dirs = [ - "include", - "include/ipc", - "include/ipc/lite", - "include/notify", - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "${utils_path}/include", - "${utils_path}/include/ipc/lite", - ] - include_dirs += [ - "//utils/native/lite/include", - "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", - "//third_party/bounds_checking_function/include", - "//foundation/communication/ipc_lite/interfaces/kits", - "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", - "//third_party/json/include", - ] - - sources = [ - "src/device_manager.cpp", - "src/device_manager_impl.cpp", - "src/ipc/ipc_client_proxy.cpp", - "src/ipc/lite/ipc_client_manager.cpp", - "src/ipc/lite/ipc_client_server_proxy.cpp", - "src/ipc/lite/ipc_client_stub.cpp", - "src/ipc/lite/ipc_cmd_parser.cpp", - "src/notify/device_manager_notify.cpp", - ] - - defines = [ - "LITE_DEVICE", - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004100", - ] - - deps = [ - "${utils_path}:devicemanagerutils", - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//foundation/communication/ipc_lite:liteipc_adapter", - "//foundation/distributedschedule/samgr_lite/samgr:samgr", - "//third_party/bounds_checking_function:libsec_shared", - "//utils/native/lite:utils", - ] } } else { ohos_shared_library("devicemanagersdk") { diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 799bb65ad..c2f71d5e9 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -21,87 +21,8 @@ import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { executable("devicemanagerservice") { - include_dirs = [ - "include", - "include/adapter", - "include/authentication", - "include/ability", - "include/deviceinfo", - "include/devicestate", - "include/discovery", - "include/dependency/hichain", - "include/dependency/softbus", - "include/dependency/timer", - "include/ipc", - "include/ipc/lite", - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "${utils_path}/include", - "${utils_path}/include/ipc/lite", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/ipc", - "${innerkits_path}/native_cpp/include/ipc/lite", - ] - - 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/distributedschedule/samgr_lite/interfaces/kits/samgr", - ] - sources = [ - "src/ability/lite/dm_ability_manager.cpp", - "src/adapter/lite/dm_adapter_manager.cpp", - "src/authentication/auth_message_processor.cpp", - "src/authentication/auth_request_state.cpp", - "src/authentication/auth_response_state.cpp", - "src/authentication/auth_ui.cpp", - "src/authentication/dm_auth_manager.cpp", - "src/dependency/hichain/hichain_connector.cpp", - "src/dependency/softbus/softbus_connector.cpp", - "src/dependency/softbus/softbus_session.cpp", - "src/dependency/timer/dm_timer.cpp", - "src/device_manager_service.cpp", - "src/device_manager_service_listener.cpp", - "src/deviceinfo/dm_device_info_manager.cpp", - "src/devicestate/dm_device_state_manager.cpp", - "src/discovery/dm_discovery_manager.cpp", - "src/ipc/lite/ipc_cmd_parser.cpp", - "src/ipc/lite/ipc_server_listener.cpp", - "src/ipc/lite/ipc_server_listenermgr.cpp", "src/ipc/lite/ipc_server_main.cpp", - "src/ipc/lite/ipc_server_stub.cpp", - ] - - defines = [ - "LITE_DEVICE", - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerservice\"", - "LOG_DOMAIN=0xD004100", - ] - - deps = [ - "${innerkits_path}/native_cpp:devicemanagersdk", - "${utils_path}:devicemanagerutils", - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//base/security/deviceauth/services:deviceauth_sdk", - "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", - "//foundation/communication/dsoftbus/sdk:softbus_client", - "//foundation/communication/ipc_lite:liteipc_adapter", - "//foundation/distributedschedule/samgr_lite/samgr:samgr", - "//utils/native/lite:utils", ] } } else { diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp index 03dd6c3ac..e4373c2ad 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp @@ -13,37 +13,13 @@ * limitations under the License. */ -#include - #include - -#include "device_manager_service.h" -#include "dm_constants.h" -#include "dm_log.h" -#include "ipc_server_stub.h" - -using namespace OHOS::DistributedHardware; - -static void InitAll() -{ - const int32_t DM_SERVICE_INIT_DELAY = 2; - sleep(DM_SERVICE_INIT_DELAY); - if (IpcServerStubInit() != DM_OK) { - LOGE("IpcServerStubInit failed"); - return; - } - if (DeviceManagerService::GetInstance().Init() != DM_OK) { - LOGE("module init failed"); - return; - } - LOGI("DM ipc server Init success"); -} +#include int32_t main(int32_t argc, char *argv[]) { (void)argc; (void)argv; - InitAll(); while (1) { pause(); } diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 888ae7f79..6fb1469cc 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -21,51 +21,6 @@ import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { shared_library("devicemanagerutils") { - include_dirs = [ - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "include", - "include/ipc/lite", - ] - - 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/distributedschedule/samgr_lite/interfaces/kits/samgr", - ] - - sources = [ - "src/dm_anonymous.cpp", - "src/dm_log.cpp", - "src/dm_random.cpp", - "src/ipc/lite/ipc_cmd_register.cpp", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerutils\"", - "LOG_DOMAIN=0xD004100", - ] - - deps = [ - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//foundation/communication/ipc_lite:liteipc_adapter", - "//third_party/bounds_checking_function:libsec_shared", - "//third_party/mbedtls:mbedtls_shared", - "//utils/native/lite:utils", - ] } } else { ohos_shared_library("devicemanagerutils") { @@ -109,4 +64,4 @@ if (defined(ohos_lite)) { part_name = "device_manager_base" } -} \ No newline at end of file +} -- Gitee From 1849219727c85b65839cd0491b078a30b83db325 Mon Sep 17 00:00:00 2001 From: puhui Date: Thu, 13 Jan 2022 11:12:29 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E4=BF=AE=E6=94=B9format=20check=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- ext/pin_auth/BUILD.gn | 2 +- ext/profile/BUILD.gn | 2 +- interfaces/inner_kits/native_cpp/BUILD.gn | 2 +- interfaces/kits/js/BUILD.gn | 2 +- services/devicemanagerservice/BUILD.gn | 2 +- test/BUILD.gn | 2 +- utils/BUILD.gn | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index cc8cfcefc..333c13403 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -64,4 +64,4 @@ if (defined(ohos_lite)) { part_name = "device_manager_base" } -} \ No newline at end of file +} diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn index 4ac238c37..552653a03 100644 --- a/ext/profile/BUILD.gn +++ b/ext/profile/BUILD.gn @@ -72,4 +72,4 @@ if (defined(ohos_lite)) { part_name = "device_manager_base" } -} \ No newline at end of file +} diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 2dbc348fd..1814cd812 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -122,4 +122,4 @@ if (defined(ohos_lite)) { part_name = "device_manager_base" } -} \ No newline at end of file +} diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 9bbe372f6..ca930a219 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -64,4 +64,4 @@ ohos_shared_library("devicemanager") { group("devicemanager_native_js") { deps = [ ":devicemanager" ] -} \ No newline at end of file +} diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 799bb65ad..fd5b0366c 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -199,4 +199,4 @@ if (defined(ohos_lite)) { part_name = "device_manager_base" } -} \ No newline at end of file +} diff --git a/test/BUILD.gn b/test/BUILD.gn index ece194320..d29faeb19 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -15,4 +15,4 @@ group("test") { testonly = true deps = [ "unittest:unittest" ] -} \ No newline at end of file +} diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 888ae7f79..13ab7c3fb 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -109,4 +109,4 @@ if (defined(ohos_lite)) { part_name = "device_manager_base" } -} \ No newline at end of file +} -- Gitee