From 9c4ddf07b9dbe5df7f312df81eff5b595622b6d3 Mon Sep 17 00:00:00 2001 From: puhui Date: Tue, 23 Nov 2021 11:43:43 +0800 Subject: [PATCH 001/110] =?UTF-8?q?=E6=9E=B6=E6=9E=84=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BUILD.gn | 2 +- {utils => common}/BUILD.gn | 7 +- .../include/{constants.h => dm_constants.h} | 0 ...device_manager_errno.h => dm_error_code.h} | 0 .../include/log => common/include}/dm_log.h | 12 +- .../include/utils/dm_anonymous.h | 0 {utils/src/log => common/src}/dm_log.cpp | 3 +- .../src/utils/dm_anonymous.cpp | 2 +- devicemanager.gni | 4 +- ...hos.distributedHardware.deviceManager.d.ts | 476 ---------------- display/build.gradle | 57 -- display/entry/build.gradle | 42 -- display/entry/src/main/config.json | 61 -- .../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 - .../native_cpp/include/device_manager.h | 23 +- .../include/device_manager_callback.h | 16 +- .../native_cpp/include/dm_device_info.h | 10 +- ohos.build | 2 +- services/devicemanagerservice/BUILD.gn | 101 ++-- .../include/adapter/crypto_adapter.h | 34 ++ .../decision_adapter.h} | 33 +- .../include/adapter/dm_adapter_manager.h | 37 ++ .../profile/device_profile_adapter.h} | 32 +- .../include/adapter/profile_adapter.h | 30 + .../include/authentication/authentication.h | 30 + .../include/authentication/dm_auth_manager.h | 48 ++ .../authentication/pin_auth/pin_auth.h | 21 +- .../authentication/pin_auth/pin_auth_ui.h | 32 ++ .../hichain}/hichain_connector.h | 1 - .../softbus/softbus_connector.h} | 156 +++--- .../softbus/softbus_session.h | 4 +- .../softbus/softbus_session_callback.h | 33 ++ .../include/device_manager_impl.h | 54 +- ...ty_manager.h => device_manager_listener.h} | 54 +- .../deviceinfo/dm_device_info_manager.h | 40 ++ .../devicestate/dm_device_state_manager.h | 38 ++ .../include/discovery/dm_discovery_manager.h | 38 ++ .../include/message/msg_codec.h | 46 -- .../include/message/msg_request_auth.h | 79 --- .../include/message/msg_response_auth.h | 60 -- .../include/requestauth/auth_manager.h | 65 --- .../include/requestauth/request_session.h | 86 --- .../include/requestauth/response_session.h | 81 --- .../include/timer/dm_timer.h | 71 --- .../ability/standard/dm_ability_manager.cpp | 97 ---- .../src/adapter/dm_adapter_manager.cpp | 17 +- .../profile/device_profile_adapter.cpp | 24 + .../src/authentication/dm_auth_manager.cpp | 24 + .../hichain}/hichain_connector.cpp | 0 .../dependency/softbus/softbus_connector.cpp | 41 ++ .../softbus/softbus_session.cpp} | 45 +- .../src/device_manager_impl.cpp | 23 + .../src/deviceinfo/dm_device_info_manager.cpp | 24 + .../devicestate/dm_device_state_manager.cpp | 24 + .../src/discovery/dm_discovery_manager.cpp | 24 + .../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 ----- utils/include/ipc/lite/ipc_cmd_register.h | 114 ---- utils/include/ipc/standard/ipc_cmd_register.h | 94 ---- utils/src/cipher/encrypt_utils.cpp | 152 ----- utils/src/ipc/lite/ipc_cmd_register.cpp | 68 --- utils/src/ipc/standard/ipc_cmd_register.cpp | 55 -- 78 files changed, 803 insertions(+), 5230 deletions(-) rename {utils => common}/BUILD.gn (95%) rename common/include/{constants.h => dm_constants.h} (100%) rename common/include/{device_manager_errno.h => dm_error_code.h} (100%) rename {utils/include/log => common/include}/dm_log.h (76%) rename utils/include/anonymous_string.h => common/include/utils/dm_anonymous.h (100%) rename {utils/src/log => common/src}/dm_log.cpp (98%) rename utils/src/anonymous_string.cpp => common/src/utils/dm_anonymous.cpp (98%) 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/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 create mode 100644 services/devicemanagerservice/include/adapter/crypto_adapter.h rename services/devicemanagerservice/include/{message/msg_sync_group.h => adapter/decision_adapter.h} (56%) create mode 100644 services/devicemanagerservice/include/adapter/dm_adapter_manager.h rename services/devicemanagerservice/include/{message/msg_head.h => adapter/profile/device_profile_adapter.h} (49%) create mode 100644 services/devicemanagerservice/include/adapter/profile_adapter.h create mode 100644 services/devicemanagerservice/include/authentication/authentication.h create mode 100644 services/devicemanagerservice/include/authentication/dm_auth_manager.h rename common/include/device_manager_log.h => services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h (71%) create mode 100644 services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h rename services/devicemanagerservice/include/{auth => dependency/hichain}/hichain_connector.h (99%) rename services/devicemanagerservice/include/{softbus/softbus_adapter.h => dependency/softbus/softbus_connector.h} (94%) rename services/devicemanagerservice/include/{ => dependency}/softbus/softbus_session.h (95%) create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h rename utils/include/cipher/encrypt_utils.h => services/devicemanagerservice/include/device_manager_impl.h (32%) rename services/devicemanagerservice/include/{ability/dm_ability_manager.h => device_manager_listener.h} (43%) 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 delete mode 100644 services/devicemanagerservice/include/message/msg_codec.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/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/timer/dm_timer.h delete mode 100644 services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp rename display/entry/src/main/js/default/app.js => services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp (78%) create mode 100644 services/devicemanagerservice/src/adapter/profile/device_profile_adapter.cpp create mode 100644 services/devicemanagerservice/src/authentication/dm_auth_manager.cpp rename services/devicemanagerservice/src/{auth => dependency/hichain}/hichain_connector.cpp (100%) create mode 100644 services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp rename services/devicemanagerservice/src/{ability/lite/dm_ability_manager.cpp => dependency/softbus/softbus_session.cpp} (49%) create mode 100644 services/devicemanagerservice/src/device_manager_impl.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 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 utils/include/ipc/lite/ipc_cmd_register.h delete mode 100644 utils/include/ipc/standard/ipc_cmd_register.h delete mode 100644 utils/src/cipher/encrypt_utils.cpp delete mode 100644 utils/src/ipc/lite/ipc_cmd_register.cpp delete mode 100644 utils/src/ipc/standard/ipc_cmd_register.cpp diff --git a/BUILD.gn b/BUILD.gn index 103ee5a70..073e23cdd 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -15,7 +15,7 @@ if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") lite_component("devicemanager_lite") { features = [ - "utils:devicemanagerutils", + "utils:devicemanagercommon", "services/devicemanagerservice:devicemanagerservice", "interfaces/inner_kits/native_cpp:devicemanagersdk", ] diff --git a/utils/BUILD.gn b/common/BUILD.gn similarity index 95% rename from utils/BUILD.gn rename to common/BUILD.gn index b84acfffa..cb34d5061 100644 --- a/utils/BUILD.gn +++ b/common/BUILD.gn @@ -20,7 +20,7 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - shared_library("devicemanagerutils") { + shared_library("devicemanagercommon") { include_dirs = [ "${common_path}/include", "${common_path}/include/ipc", @@ -50,14 +50,13 @@ if (defined(ohos_lite)) { sources = [ "src/anonymous_string.cpp", - "src/cipher/encrypt_utils.cpp", "src/ipc/lite/ipc_cmd_register.cpp", "src/log/dm_log.cpp", ] defines = [ "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerutils\"", + "DH_LOG_TAG=\"devicemanagercommon\"", "LOG_DOMAIN=0xD004100", ] @@ -73,7 +72,7 @@ if (defined(ohos_lite)) { ] } } else { - ohos_shared_library("devicemanagerutils") { + ohos_shared_library("devicemanagercommon") { include_dirs = [ "//utils/native/base/include", "//utils/system/safwk/native/include", diff --git a/common/include/constants.h b/common/include/dm_constants.h similarity index 100% rename from common/include/constants.h rename to common/include/dm_constants.h diff --git a/common/include/device_manager_errno.h b/common/include/dm_error_code.h similarity index 100% rename from common/include/device_manager_errno.h rename to common/include/dm_error_code.h diff --git a/utils/include/log/dm_log.h b/common/include/dm_log.h similarity index 76% rename from utils/include/log/dm_log.h rename to common/include/dm_log.h index 1db27040a..b8ea389a3 100644 --- a/utils/include/log/dm_log.h +++ b/common/include/dm_log.h @@ -13,11 +13,14 @@ * limitations under the License. */ -#ifndef OHOS_DM_LOG_H -#define OHOS_DM_LOG_H +#ifndef OHOS_DEVICE_MANAGER_LOG_H +#define OHOS_DEVICE_MANAGER_LOG_H + +#include namespace OHOS { namespace DistributedHardware { + typedef enum { DM_LOG_DEBUG, DM_LOG_INFO, @@ -26,6 +29,9 @@ typedef enum { } DMLogLevel; void DMLog(DMLogLevel logLevel, const char *fmt, ...); + +#define DMLOG(level, fmt, ...) DMLog(level, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_LOG_H +#endif // OHOS_DEVICE_MANAGER_LOG_H diff --git a/utils/include/anonymous_string.h b/common/include/utils/dm_anonymous.h similarity index 100% rename from utils/include/anonymous_string.h rename to common/include/utils/dm_anonymous.h diff --git a/utils/src/log/dm_log.cpp b/common/src/dm_log.cpp similarity index 98% rename from utils/src/log/dm_log.cpp rename to common/src/dm_log.cpp index 538594b15..0875627ee 100644 --- a/utils/src/log/dm_log.cpp +++ b/common/src/dm_log.cpp @@ -15,10 +15,9 @@ #include "dm_log.h" +#include "dm_constants.h" #include "securec.h" -#include "constants.h" - #ifdef HI_LOG_ENABLE #include "hilog/log.h" #else diff --git a/utils/src/anonymous_string.cpp b/common/src/utils/dm_anonymous.cpp similarity index 98% rename from utils/src/anonymous_string.cpp rename to common/src/utils/dm_anonymous.cpp index f5834ee37..1b6263eeb 100644 --- a/utils/src/anonymous_string.cpp +++ b/common/src/utils/dm_anonymous.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "anonymous_string.h" +#include "dm_anonymous.h" #include "securec.h" diff --git a/devicemanager.gni b/devicemanager.gni index e8576d35d..9fbc9b19d 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -15,10 +15,10 @@ devicemanager_path = "//foundation/distributedhardware/devicemanager" common_path = "${devicemanager_path}/common" -utils_path = "${devicemanager_path}/utils" - services_path = "${devicemanager_path}/services" innerkits_path = "${devicemanager_path}/interfaces/inner_kits" +ext_path = "${devicemanager_path}/ext" + 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/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 dmInitCallback) = 0; - virtual int32_t UnInitDeviceManager(std::string &pkgName) = 0; - virtual int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, + 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, std::string &extra, std::vector &deviceList) = 0; - virtual int32_t RegisterDevStateCallback(std::string &pkgName, std::string &extra, + virtual int32_t RegisterDevStateCallback(const 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, + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) = 0; + virtual int32_t StartDeviceDiscovery(const 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, + virtual int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) = 0; + virtual int32_t AuthenticateDevice(const 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, + virtual int32_t VerifyAuthentication(const 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; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 786e8ca85..ff9f3d246 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -41,7 +41,7 @@ public: class DiscoverCallback { public: virtual ~DiscoverCallback() {} - virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; + // virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; virtual void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) = 0; virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) = 0; }; @@ -49,19 +49,13 @@ public: class AuthenticateCallback { public: virtual ~AuthenticateCallback() {} - virtual void OnAuthResult(std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) = 0; + virtual void OnAuthResult(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; -}; - -class DeviceManagerFaCallback { -public: - virtual ~DeviceManagerFaCallback() {} - virtual void OnCall(std::string ¶mJson) = 0; + virtual ~VerifyAuthCallback() {} + virtual void OnVerifyAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) = 0; }; } // namespace DistributedHardware } // namespace OHOS 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 076a2c007..8e0a6727e 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -25,7 +25,7 @@ namespace OHOS { namespace DistributedHardware { -typedef enum DMDeviceType { +typedef enum DmDeviceType { DEVICE_TYPE_UNKNOWN = 0x00, DEVICE_TYPE_WIFI_CAMERA = 0x08, DEVICE_TYPE_AUDIO = 0x0A, @@ -35,7 +35,7 @@ typedef enum DMDeviceType { DEVICE_TYPE_WATCH = 0x6D, DEVICE_TYPE_CAR = 0x83, DEVICE_TYPE_TV = 0x9C, -} DMDeviceType; +} DmDeviceType; typedef enum DmDeviceState { DEVICE_STATE_UNKNOWN = 0, @@ -52,13 +52,11 @@ typedef struct DmDeviceInfo { typedef struct DmAuthParam { std::string packageName; + int32_t authType; + std::string authToken; std::string appName; std::string appDescription; - int32_t authType; - int32_t business; - int32_t pincode; int32_t direction; - int32_t pinToken; DmAppImageInfo imageinfo; } DmAuthParam; } // namespace DistributedHardware diff --git a/ohos.build b/ohos.build index f544c0dcc..8630c9844 100644 --- a/ohos.build +++ b/ohos.build @@ -19,7 +19,7 @@ } ], "module_list": [ - "//foundation/distributedhardware/devicemanager/utils:devicemanagerutils", + "//foundation/distributedhardware/devicemanager/utils:devicemanagercommon", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager_native_js", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice:devicemanagerservice", diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 85b8e5774..c9cc8db07 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -23,21 +23,20 @@ if (defined(ohos_lite)) { executable("devicemanagerservice") { include_dirs = [ "include", - "include/ability", - "include/softbus", - "include/requestauth", - "include/auth", + "include/adapter", + "include/adapter/profile", + "include/authentication", + "include/deviceinfo", + "include/devicestate", + "include/discovery", + "include/dependency/hichain", + "include/dependency/softbus", "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", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include", + "${common_path}/include/utils", "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/ipc/lite", ] @@ -60,8 +59,15 @@ if (defined(ohos_lite)) { ] sources = [ - "src/ability/lite/dm_ability_manager.cpp", - "src/auth/hichain_connector.cpp", + "src/adapter/profile/device_profile_adapter.cpp", + "src/adapter/dm_adapter_manager.cpp", + "src/deviceinfo/dm_device_info_manager.cpp", + "src/devicestate/dm_device_state_manager.cpp", + "src/discovery/dm_discovery_manager.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/ipc/ipc_server_adapter.cpp", "src/ipc/ipc_server_listener_adapter.cpp", "src/ipc/lite/ipc_cmd_parser.cpp", @@ -69,17 +75,6 @@ if (defined(ohos_lite)) { "src/ipc/lite/ipc_server_listenermgr.cpp", "src/ipc/lite/ipc_server_main.cpp", "src/ipc/lite/ipc_server_stub.cpp", - "src/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 = [ @@ -100,68 +95,62 @@ if (defined(ohos_lite)) { "//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", + # "//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/adapter", + "include/adapter/profile", + "include/authentication", + "include/deviceinfo", + "include/devicestate", + "include/discovery", + "include/dependency/hichain", + "include/dependency/softbus", "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", + "${common_path}/include/ipc/standard", "${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", + "//utils/native/base/include", + "//utils/system/safwk/native/include", ] sources = [ - "src/ability/standard/dm_ability_manager.cpp", - "src/auth/hichain_connector.cpp", + "src/adapter/profile/device_profile_adapter.cpp", + "src/adapter/dm_adapter_manager.cpp", + "src/deviceinfo/dm_device_info_manager.cpp", + "src/devicestate/dm_device_state_manager.cpp", + "src/discovery/dm_discovery_manager.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/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", + "${common_path}:devicemanagercommon", "//base/security/deviceauth/services:deviceauth_sdk", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + # "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/aafwk/standard/services/abilitymgr:abilityms", + # "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//utils/native/base:utils", ] @@ -178,7 +167,7 @@ if (defined(ohos_lite)) { "dsoftbus_standard:softbus_client", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "safwk:system_ability_fwk", + # "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "startup_l2:syspara", ] diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h new file mode 100644 index 000000000..22ffb547e --- /dev/null +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.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_CRYPTO_ADAPTER_H +#define OHOS_DM_CRYPTO_ADAPTER_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class CryptoAdapter { +public: + virtual ~CryptoAdapter() = default; + 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; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_CRYPTO_ADAPTER_H diff --git a/services/devicemanagerservice/include/message/msg_sync_group.h b/services/devicemanagerservice/include/adapter/decision_adapter.h similarity index 56% rename from services/devicemanagerservice/include/message/msg_sync_group.h rename to services/devicemanagerservice/include/adapter/decision_adapter.h index a19d8ff54..bbc4905c9 100644 --- a/services/devicemanagerservice/include/message/msg_sync_group.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.h @@ -13,33 +13,20 @@ * limitations under the License. */ -#ifndef OHOS_MSG_SYNC_GROUP_H -#define OHOS_MSG_SYNC_GROUP_H +#ifndef OHOS_DM_DECISION_ADAPTER_H +#define OHOS_DM_DECISION_ADAPTER_H -#include #include - -#include "nlohmann/json.hpp" - -#include "msg_head.h" +#include namespace OHOS { namespace DistributedHardware { -class MsgSyncGroup { +class DecisionAdapter { 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_; + virtual ~DecisionAdapter() = default; + virtual int32_t FilterDeviceList(std::vector &infoList, const string &filterOptions) = 0; + virtual int32_t SortDeviceList(std::vector &infoList, const string &sortOptions) = 0; }; -} -} -#endif \ No newline at end of file +} // 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..7edae2856 --- /dev/null +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.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_ADAPTER_MANAGER_H +#define OHOS_DM_ADAPTER_MANAGER_H + + +namespace OHOS { +namespace DistributedHardware { +class DmAdapterManager { +public: + DmAdapterManager(); + std::shared_ptr GetDecisionAdapter(); + std::shared_ptr GetProfileAdapter(); + std::shared_ptr GetCryptoAdapter(); + +private: + std::shared_ptr decisionAdapterPtr_; + std::shared_ptr profileAdapterPtr_; + std::shared_ptr cryptoAdapterPtr_; + +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DEVICE_STATE_MAGANGER_H diff --git a/services/devicemanagerservice/include/message/msg_head.h b/services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h similarity index 49% rename from services/devicemanagerservice/include/message/msg_head.h rename to services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h index b79b99f3e..f2ba658cd 100644 --- a/services/devicemanagerservice/include/message/msg_head.h +++ b/services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h @@ -13,36 +13,20 @@ * limitations under the License. */ -#ifndef OHOS_MSG_HEAD_H -#define OHOS_MSG_HEAD_H +#ifndef OHOS_DM_ADAPTER_MANAGER_H +#define OHOS_DM_ADAPTER_MANAGER_H -#include "nlohmann/json.hpp" +#include "profile_adapter.h" 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 { +class DeviceProfileAdapter : ProfileAdapter { 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(); + DeviceProfileAdapter(); + private: - int32_t mMsgType_; - std::string mItfVer_; + }; } } -#endif \ No newline at end of file +#endif diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h new file mode 100644 index 000000000..dc492bb89 --- /dev/null +++ b/services/devicemanagerservice/include/adapter/profile_adapter.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_PROFILE_ADAPTER_H +#define OHOS_DM_PROFILE_ADAPTER_H + + +namespace OHOS { +namespace DistributedHardware { +class ProfileAdapter { +public: + virtual ~ProfileAdapter() = default; + virtual int32_t RegisterProfileListener() = 0; + virtual int32_t UnRegisterProfileListener() = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PROFILE_ADAPTER_H diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h new file mode 100644 index 000000000..0524dfbd2 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/authentication.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_AUTHENTICATION_H +#define OHOS_DM_AUTHENTICATION_H + + +namespace OHOS { +namespace DistributedHardware { +class Authentication { +public: + virtual ~Authentication() = default; + virtual int32_t ShowAuthInfo() = 0; + virtual int32_t StartAuth() = 0; +}; +} // 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..68412b322 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/dm_auth_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_AUTH_MANAGER_H +#define OHOS_DM_AUTH_MANAGER_H + +#include +#include + +#include "nlohmann/json.hpp" +#include "softbus_session.h" +#include "device_manager_listener.h" +#include "adapter_manager.h" +#include "authentication.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManager { +public: + DmAuthManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + ~DmAuthManager(); + int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); + int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam); + +private: + std::shared_ptr softbusSession_; + std::shared_ptr hichainConnector_; + std::shared_ptr listenerPtr_; + std::shared_ptr adapterMgr_; + std::map authenticationMap_; + +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_H diff --git a/common/include/device_manager_log.h b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h similarity index 71% rename from common/include/device_manager_log.h rename to services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h index fa0f776a3..e5b680491 100644 --- a/common/include/device_manager_log.h +++ b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h @@ -13,17 +13,22 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_LOG_H -#define OHOS_DEVICE_MANAGER_LOG_H +#ifndef OHOS_DM_PIN_AUTH_H +#define OHOS_DM_PIN_AUTH_H -#include - -#include "dm_log.h" +#include "authentication.h" namespace OHOS { namespace DistributedHardware { -#define DMLOG(level, fmt, ...) DMLog(level, \ - (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) +class PinAuth : Authentication { +public: + PinAuth(); + int32_t ShowAuthInfo(); + int32_t StartAuth(); + +private: + std::shared_ptr pinAuthUiPtr_; +}; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LOG_H +#endif // OHOS_DM_PIN_AUTH_H diff --git a/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h new file mode 100644 index 000000000..4219abf08 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PIN_AUTH_UI_H +#define OHOS_DM_PIN_AUTH_UI_H + + +namespace OHOS { +namespace DistributedHardware { +class PinAuthUI { +public: + PinAuthUI(); + int32_t ShowPinDialog(); + int32_t InputPinDialog(); + +private: +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PIN_AUTH_UI_H diff --git a/services/devicemanagerservice/include/auth/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h similarity index 99% rename from services/devicemanagerservice/include/auth/hichain_connector.h rename to services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index e49700c97..bfee927e8 100644 --- a/services/devicemanagerservice/include/auth/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -25,7 +25,6 @@ #include "device_auth.h" #include "single_instance.h" -#include "msg_response_auth.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/softbus/softbus_adapter.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h similarity index 94% rename from services/devicemanagerservice/include/softbus/softbus_adapter.h rename to services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index 25f472ff3..db1f5cc77 100644 --- a/services/devicemanagerservice/include/softbus/softbus_adapter.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -1,78 +1,78 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "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 SoftbusConnector { +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/dependency/softbus/softbus_session.h similarity index 95% rename from services/devicemanagerservice/include/softbus/softbus_session.h rename to services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 03610be2c..2e3d1ee52 100644 --- a/services/devicemanagerservice/include/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H -#define OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H +#ifndef OHOS_DM_SOFTBUS_SESSION_H +#define OHOS_DM_SOFTBUS_SESSION_H #include #include 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..03f400acb --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.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_DM_SOFTBUS_SESSION_CALLBACK_H +#define OHOS_DM_SOFTBUS_SESSION_CALLBACK_H + + +namespace OHOS { +namespace DistributedHardware { +class DmAdapterManager { +public: + DmAdapterManager(); + + +private: + + +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_SESSION_CALLBACK_H diff --git a/utils/include/cipher/encrypt_utils.h b/services/devicemanagerservice/include/device_manager_impl.h similarity index 32% rename from utils/include/cipher/encrypt_utils.h rename to services/devicemanagerservice/include/device_manager_impl.h index db19b2364..824b00695 100644 --- a/utils/include/cipher/encrypt_utils.h +++ b/services/devicemanagerservice/include/device_manager_impl.h @@ -13,34 +13,42 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H -#define OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H +#ifndef OHOS_DEVICE_MANAGER_IMPL_H +#define OHOS_DEVICE_MANAGER_IMPL_H + +#include +#include + +#include "single_instance.h" +#include "dm_auth_manager.h" +#include "dm_device_info_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "dm_device_info.h" +#include "softbus_connector.h" -#include -#include namespace OHOS { namespace DistributedHardware { -class EncryptUtils { +class DeviceManagerImpl { + DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); 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); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &info); + 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 string &deviceId, const std::string extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); + int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam); +private: + DeviceManagerImpl(); + virtual ~DeviceManagerImpl() = default; + std::shared_ptr authMgrPtr_; + std::shared_ptr deviceInfoMgrPtr_; + std::shared_ptr deviceStateMgrPtr_; + std::shared_ptr discoveryMgrPtr_; + std::shared_ptr softbusConnectorPtr_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H \ No newline at end of file +#endif // OHOS_DEVICE_MANAGER_IMPL_H diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/device_manager_listener.h similarity index 43% rename from services/devicemanagerservice/include/ability/dm_ability_manager.h rename to services/devicemanagerservice/include/device_manager_listener.h index 17a9337d5..5501c66d5 100644 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ b/services/devicemanagerservice/include/device_manager_listener.h @@ -13,53 +13,31 @@ * limitations under the License. */ -#ifndef OHOS_DM_ABILITY_MANAGER_H -#define OHOS_DM_ABILITY_MANAGER_H +#ifndef OHOS_DEVICE_MANAGER_LISTENER_H +#define OHOS_DEVICE_MANAGER_LISTENER_H #include -#include -#include -#include -#include "single_instance.h" +#include "dm_device_info.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); +class DeviceManagerListener { public: - AbilityRole GetAbilityRole(); - AbilityStatus StartAbility(AbilityRole role); - void StartAbilityDone(); - + DeviceManagerListener(); + ~DeviceManagerListener(); + int32_t OnDeviceOnline(const DmDeviceInfo &info); + int32_t OnDeviceOffline(const DmDeviceInfo &info); + int32_t OnDeviceReady(const DmDeviceInfo &info); + int32_t OnDeviceStateChange(const DmDeviceInfo &info); + int32_t OnDeviceFound(uint16_t sbuscribeId, const DmDeviceInfo &info); + int32_t OnDeviceLost(uint16_t subscribeId, const DmDeviceInfo &info); + int32_t OnDiscoveryFailed(uint16_t subscribeId, const std::string &failedReason); + int32_t OnAuthenticateResult(const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason); + int32_t OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string &flag); private: - void waitForTimeout(uint32_t timeout_s); -private: - sem_t mSem_; - AbilityStatus mStatus_; - AbilityRole mAbilityStatus_; }; } // namespace DistributedHardware } // namespace OHOS -#endif +#endif // OHOS_DEVICE_MANAGER_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..7e7385928 --- /dev/null +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.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_DEVICEINFO_MANAGER_H +#define OHOS_DM_DEVICEINFO_MANAGER_H + +#include +#include + +#include "dm_device_info.h" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceInfoManager { +public: + DmDeviceInfoManager(std::shared_ptr softbusConnectorPtr); + ~DmDeviceInfoManager(); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &info); + +private: + std::shared_ptr softbusConnectorPtr_; + std::shared_ptr adapterMgrPtr_; +}; +} // 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..f09cf0ff4 --- /dev/null +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.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_DEVICE_STATE_MAGANGER_H +#define OHOS_DM_DEVICE_STATE_MAGANGER_H + + +#include "softbus_connector.h" +#include "adapter_manager.h" +#include "device_manager_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceStateManager { +public: + DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + ~DmDeviceStateManager(); + +private: + std::shared_ptr softbusConnectorPtr_; + std::shared_ptr adapterMgrPtr_; + std::shared_ptr listenerPtr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DEVICE_STATE_MAGANGER_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..371c914bc --- /dev/null +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.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_DISCOVERY_MANAGER_H +#define OHOS_DM_DISCOVERY_MANAGER_H + + +#include "softbus_connector.h" +#include "device_manager_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDiscoveryManager { +public: + DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + ~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); + +private: + std::shared_ptr softbusConnectorPtr_; + std::shared_ptr listenerPtr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DISCOVERY_MANAGER_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_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/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/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/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/display/entry/src/main/js/default/app.js b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp similarity index 78% rename from display/entry/src/main/js/default/app.js rename to services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp index 8e47afff1..16ab0391c 100644 --- a/display/entry/src/main/js/default/app.js +++ b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp @@ -13,11 +13,12 @@ * limitations under the License. */ -export default { - onCreate() { - console.info('AceApplication onCreate'); - }, - onDestroy() { - console.info('AceApplication onDestroy'); - } -}; +#include "dm_adapter_manager.h" +#include "constants.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} diff --git a/services/devicemanagerservice/src/adapter/profile/device_profile_adapter.cpp b/services/devicemanagerservice/src/adapter/profile/device_profile_adapter.cpp new file mode 100644 index 000000000..94a86ea59 --- /dev/null +++ b/services/devicemanagerservice/src/adapter/profile/device_profile_adapter.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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" + +namespace OHOS { +namespace DistributedHardware { + + +} +} 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..e5ac3ecbb --- /dev/null +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} diff --git a/services/devicemanagerservice/src/auth/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp similarity index 100% rename from services/devicemanagerservice/src/auth/hichain_connector.cpp rename to services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp 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..0b14e3cee --- /dev/null +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_connector.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 DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp similarity index 49% rename from services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp rename to services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 3b5885159..0641cc493 100644 --- a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -13,42 +13,19 @@ * limitations under the License. */ -#include "dm_ability_manager.h" - -#include "semaphore.h" - -#include "constants.h" +#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 { -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_); -} -} -} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_impl.cpp b/services/devicemanagerservice/src/device_manager_impl.cpp new file mode 100644 index 000000000..9f7e43304 --- /dev/null +++ b/services/devicemanagerservice/src/device_manager_impl.cpp @@ -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. + */ + +#include "device_manager_impl.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} 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..3d777ed42 --- /dev/null +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "constants.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} 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..7bbe23b4f --- /dev/null +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "constants.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} 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..14f718ec3 --- /dev/null +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "constants.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} 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/utils/include/ipc/lite/ipc_cmd_register.h b/utils/include/ipc/lite/ipc_cmd_register.h deleted file mode 100644 index 0144df0d6..000000000 --- a/utils/include/ipc/lite/ipc_cmd_register.h +++ /dev/null @@ -1,114 +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_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H - -#include -#include -#include - -#include "liteipc_adapter.h" -#include "single_instance.h" - -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) - { - onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); - }; - 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_; - std::unordered_map onIpcCmdFuncMap_; - std::unordered_map onIpcServerCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_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 deleted file mode 100644 index c2c5d585d..000000000 --- a/utils/include/ipc/standard/ipc_cmd_register.h +++ /dev/null @@ -1,94 +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_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H - -#include -#include -#include - -#include "iremote_broker.h" -#include "single_instance.h" - -#include "ipc_types.h" -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ - static int32_t IpcCmdProcess##cmdCode(paraA, paraB) - -using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); -using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); -using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); - -class IpcCmdRegister { -DECLARE_SINGLE_INSTANCE(IpcCmdRegister); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - int32_t SetRequest(int32_t cmdCode, 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_; - std::unordered_map onIpcCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ 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 deleted file mode 100644 index 4fbab5a16..000000000 --- a/utils/src/ipc/lite/ipc_cmd_register.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 "ipc_cmd_register.h" - -#include "device_manager_errno.h" -#include "device_manager_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) -{ - 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; - } - return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); -} - -int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - 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; - } - return (readResponseMapIter->second)(reply, pBaseRsp); -} - -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; - } - (onIpcCmdMapIter->second)(reply); - return DEVICEMANAGER_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; - } - (onIpcServerCmdMapIter->second)(req, reply); - return DEVICEMANAGER_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 deleted file mode 100644 index e958dfd04..000000000 --- a/utils/src/ipc/standard/ipc_cmd_register.cpp +++ /dev/null @@ -1,55 +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_cmd_register.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); - -int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) -{ - 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; - } - return (setRequestMapIter->second)(pBaseReq, data); -} - -int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - 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; - } - return (readResponseMapIter->second)(reply, pBaseRsp); -} - -int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &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; - } - return (onIpcCmdMapIter->second)(data, reply); -} -} // namespace DistributedHardware -} // namespace OHOS -- Gitee From 61238aa7c122f5630cef1d0920325ff58e027fb4 Mon Sep 17 00:00:00 2001 From: puhui Date: Tue, 23 Nov 2021 11:43:43 +0800 Subject: [PATCH 002/110] =?UTF-8?q?=E6=9E=B6=E6=9E=84=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- BUILD.gn | 2 +- {utils => common}/BUILD.gn | 7 +- .../include/{constants.h => dm_constants.h} | 179 ++-- ...device_manager_errno.h => dm_error_code.h} | 0 .../include/log => common/include}/dm_log.h | 12 +- .../include/utils/dm_anonymous.h | 0 {utils/src/log => common/src}/dm_log.cpp | 3 +- .../src/utils/dm_anonymous.cpp | 2 +- devicemanager.gni | 4 +- ...hos.distributedHardware.deviceManager.d.ts | 476 ---------- display/build.gradle | 57 -- display/entry/build.gradle | 42 - display/entry/src/main/config.json | 61 -- .../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 - ext/crypto/BUILD.gn | 69 ++ ext/ds/BUILD.gn | 69 ++ .../native_cpp/include/device_manager.h | 24 +- .../include/device_manager_callback.h | 16 +- .../native_cpp/include/device_manager_impl.h | 2 - .../native_cpp/include/dm_device_info.h | 17 +- ohos.build | 2 +- services/devicemanagerservice/BUILD.gn | 105 +-- .../include/adapter/crypto_adapter.h | 34 + .../decision_adapter.h} | 33 +- .../dm_adapter_manager.h} | 41 +- .../adapter/profile/device_profile_adapter.h | 23 +- .../include/adapter/profile_adapter.h | 30 + .../include/authentication/authentication.h | 30 + .../include/authentication/dm_auth_manager.h | 48 + .../authentication/pin_auth/pin_auth.h | 21 +- .../authentication/pin_auth/pin_auth_ui.h | 32 + .../hichain}/hichain_connector.h | 34 +- .../hichain/hichain_connector_callback.h | 29 + .../softbus/softbus_connector.h} | 157 ++-- .../softbus/softbus_discovery_callback.h | 30 + .../softbus/softbus_session.h | 36 +- .../softbus/softbus_session_callback.h | 30 + .../softbus/softbus_state_callback.h | 31 + .../include/device_manager_impl.h | 54 +- ...ty_manager.h => device_manager_listener.h} | 54 +- .../deviceinfo/dm_device_info_manager.h | 40 + .../devicestate/dm_device_state_manager.h | 38 + .../include/discovery/dm_discovery_manager.h | 38 + .../include/eventbus/event.h | 48 + .../include/eventbus/event_bus.h | 83 +- .../include/eventbus/event_registration.h | 49 ++ .../include/eventbus/event_sender.h | 29 + .../include/eventbus/eventbus_handler.h | 37 + .../include/message/msg_codec.h | 46 - .../include/message/msg_request_auth.h | 79 -- .../include/message/msg_response_auth.h | 60 -- .../include/requestauth/auth_manager.h | 65 -- .../include/requestauth/request_session.h | 86 -- .../include/requestauth/response_session.h | 81 -- .../include/timer/dm_timer.h | 71 -- .../ability/standard/dm_ability_manager.cpp | 97 -- .../src/adapter/dm_adapter_manager.cpp | 44 + .../src/authentication/dm_auth_manager.cpp | 50 ++ .../hichain}/hichain_connector.cpp | 243 ++--- .../softbus/softbus_connector.cpp} | 833 +++++++----------- .../softbus/softbus_session.cpp | 202 +---- .../src/device_manager_impl.cpp | 127 +++ .../dm_device_info_manager.cpp} | 40 +- .../devicestate/dm_device_state_manager.cpp | 35 + .../dm_discovery_manager.cpp} | 35 +- .../src/message/msg_codec.cpp | 113 --- .../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/timer/dm_timer.cpp | 153 ---- utils/include/ipc/lite/ipc_cmd_register.h | 114 --- utils/include/ipc/standard/ipc_cmd_register.h | 94 -- utils/src/cipher/encrypt_utils.cpp | 152 ---- utils/src/ipc/lite/ipc_cmd_register.cpp | 68 -- 84 files changed, 1910 insertions(+), 5352 deletions(-) rename {utils => common}/BUILD.gn (95%) rename common/include/{constants.h => dm_constants.h} (36%) rename common/include/{device_manager_errno.h => dm_error_code.h} (100%) rename {utils/include/log => common/include}/dm_log.h (76%) rename utils/include/anonymous_string.h => common/include/utils/dm_anonymous.h (100%) rename {utils/src/log => common/src}/dm_log.cpp (98%) rename utils/src/anonymous_string.cpp => common/src/utils/dm_anonymous.cpp (98%) 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/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 create mode 100644 ext/crypto/BUILD.gn create mode 100644 ext/ds/BUILD.gn create mode 100644 services/devicemanagerservice/include/adapter/crypto_adapter.h rename services/devicemanagerservice/include/{message/msg_sync_group.h => adapter/decision_adapter.h} (56%) rename services/devicemanagerservice/include/{message/msg_head.h => adapter/dm_adapter_manager.h} (49%) rename display/entry/src/main/js/default/app.js => services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h (70%) create mode 100644 services/devicemanagerservice/include/adapter/profile_adapter.h create mode 100644 services/devicemanagerservice/include/authentication/authentication.h create mode 100644 services/devicemanagerservice/include/authentication/dm_auth_manager.h rename common/include/device_manager_log.h => services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h (71%) create mode 100644 services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h rename services/devicemanagerservice/include/{auth => dependency/hichain}/hichain_connector.h (78%) create mode 100644 services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h rename services/devicemanagerservice/include/{softbus/softbus_adapter.h => dependency/softbus/softbus_connector.h} (30%) create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h rename services/devicemanagerservice/include/{ => dependency}/softbus/softbus_session.h (54%) create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h create mode 100644 services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h rename utils/include/cipher/encrypt_utils.h => services/devicemanagerservice/include/device_manager_impl.h (32%) rename services/devicemanagerservice/include/{ability/dm_ability_manager.h => device_manager_listener.h} (43%) 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/eventbus/event.h rename utils/src/ipc/standard/ipc_cmd_register.cpp => services/devicemanagerservice/include/eventbus/event_bus.h (31%) create mode 100644 services/devicemanagerservice/include/eventbus/event_registration.h create mode 100644 services/devicemanagerservice/include/eventbus/event_sender.h create mode 100644 services/devicemanagerservice/include/eventbus/eventbus_handler.h delete mode 100644 services/devicemanagerservice/include/message/msg_codec.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/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/timer/dm_timer.h delete mode 100644 services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp create mode 100644 services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp create mode 100644 services/devicemanagerservice/src/authentication/dm_auth_manager.cpp rename services/devicemanagerservice/src/{auth => dependency/hichain}/hichain_connector.cpp (68%) rename services/devicemanagerservice/src/{softbus/softbus_adapter.cpp => dependency/softbus/softbus_connector.cpp} (50%) rename services/devicemanagerservice/src/{ => dependency}/softbus/softbus_session.cpp (41%) create mode 100644 services/devicemanagerservice/src/device_manager_impl.cpp rename services/devicemanagerservice/src/{message/msg_head.cpp => deviceinfo/dm_device_info_manager.cpp} (45%) create mode 100644 services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp rename services/devicemanagerservice/src/{ability/lite/dm_ability_manager.cpp => discovery/dm_discovery_manager.cpp} (47%) delete mode 100644 services/devicemanagerservice/src/message/msg_codec.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/timer/dm_timer.cpp delete mode 100644 utils/include/ipc/lite/ipc_cmd_register.h delete mode 100644 utils/include/ipc/standard/ipc_cmd_register.h delete mode 100644 utils/src/cipher/encrypt_utils.cpp delete mode 100644 utils/src/ipc/lite/ipc_cmd_register.cpp diff --git a/BUILD.gn b/BUILD.gn index 103ee5a70..073e23cdd 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -15,7 +15,7 @@ if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") lite_component("devicemanager_lite") { features = [ - "utils:devicemanagerutils", + "utils:devicemanagercommon", "services/devicemanagerservice:devicemanagerservice", "interfaces/inner_kits/native_cpp:devicemanagersdk", ] diff --git a/utils/BUILD.gn b/common/BUILD.gn similarity index 95% rename from utils/BUILD.gn rename to common/BUILD.gn index b84acfffa..cb34d5061 100644 --- a/utils/BUILD.gn +++ b/common/BUILD.gn @@ -20,7 +20,7 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - shared_library("devicemanagerutils") { + shared_library("devicemanagercommon") { include_dirs = [ "${common_path}/include", "${common_path}/include/ipc", @@ -50,14 +50,13 @@ if (defined(ohos_lite)) { sources = [ "src/anonymous_string.cpp", - "src/cipher/encrypt_utils.cpp", "src/ipc/lite/ipc_cmd_register.cpp", "src/log/dm_log.cpp", ] defines = [ "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerutils\"", + "DH_LOG_TAG=\"devicemanagercommon\"", "LOG_DOMAIN=0xD004100", ] @@ -73,7 +72,7 @@ if (defined(ohos_lite)) { ] } } else { - ohos_shared_library("devicemanagerutils") { + ohos_shared_library("devicemanagercommon") { include_dirs = [ "//utils/native/base/include", "//utils/system/safwk/native/include", diff --git a/common/include/constants.h b/common/include/dm_constants.h similarity index 36% rename from common/include/constants.h rename to common/include/dm_constants.h index f8cf91ac7..acf995d8e 100644 --- a/common/include/constants.h +++ b/common/include/dm_constants.h @@ -21,14 +21,17 @@ namespace OHOS { namespace DistributedHardware { - const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; - const std::string HOST_PKG_NAME_KEY = "hostPackageName"; + // const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; + // const std::string HOST_PKG_NAME_KEY = "hostPackageName"; + + const std::string PKG_NAME = "ohos.distributedhardware.devicemanager"; + const std::string SESSION_NAME = "distributedhardware.devicemanager.resident"; 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 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; @@ -54,47 +57,40 @@ namespace DistributedHardware { 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_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"; + // 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; + // 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; @@ -105,63 +101,60 @@ namespace DistributedHardware { 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 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 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; - 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; + // // 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 GROUP_VISIBILITY_PUBLIC = -1; + // 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 BUSINESS_FA_MIRGRATION = 0; - const int32_t BUSINESS_RESOURCE_ACCESS = 1; + // const int32_t GROUP_VISIBILITY_PUBLIC = -1; - // Base64 Constants - const int32_t BASE64_BYTE_LEN_3 = 3; - const int32_t BASE64_BYTE_LEN_4 = 4; + // // 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/dm_error_code.h similarity index 100% rename from common/include/device_manager_errno.h rename to common/include/dm_error_code.h diff --git a/utils/include/log/dm_log.h b/common/include/dm_log.h similarity index 76% rename from utils/include/log/dm_log.h rename to common/include/dm_log.h index 1db27040a..b8ea389a3 100644 --- a/utils/include/log/dm_log.h +++ b/common/include/dm_log.h @@ -13,11 +13,14 @@ * limitations under the License. */ -#ifndef OHOS_DM_LOG_H -#define OHOS_DM_LOG_H +#ifndef OHOS_DEVICE_MANAGER_LOG_H +#define OHOS_DEVICE_MANAGER_LOG_H + +#include namespace OHOS { namespace DistributedHardware { + typedef enum { DM_LOG_DEBUG, DM_LOG_INFO, @@ -26,6 +29,9 @@ typedef enum { } DMLogLevel; void DMLog(DMLogLevel logLevel, const char *fmt, ...); + +#define DMLOG(level, fmt, ...) DMLog(level, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_LOG_H +#endif // OHOS_DEVICE_MANAGER_LOG_H diff --git a/utils/include/anonymous_string.h b/common/include/utils/dm_anonymous.h similarity index 100% rename from utils/include/anonymous_string.h rename to common/include/utils/dm_anonymous.h diff --git a/utils/src/log/dm_log.cpp b/common/src/dm_log.cpp similarity index 98% rename from utils/src/log/dm_log.cpp rename to common/src/dm_log.cpp index 538594b15..0875627ee 100644 --- a/utils/src/log/dm_log.cpp +++ b/common/src/dm_log.cpp @@ -15,10 +15,9 @@ #include "dm_log.h" +#include "dm_constants.h" #include "securec.h" -#include "constants.h" - #ifdef HI_LOG_ENABLE #include "hilog/log.h" #else diff --git a/utils/src/anonymous_string.cpp b/common/src/utils/dm_anonymous.cpp similarity index 98% rename from utils/src/anonymous_string.cpp rename to common/src/utils/dm_anonymous.cpp index f5834ee37..1b6263eeb 100644 --- a/utils/src/anonymous_string.cpp +++ b/common/src/utils/dm_anonymous.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "anonymous_string.h" +#include "dm_anonymous.h" #include "securec.h" diff --git a/devicemanager.gni b/devicemanager.gni index e8576d35d..9fbc9b19d 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -15,10 +15,10 @@ devicemanager_path = "//foundation/distributedhardware/devicemanager" common_path = "${devicemanager_path}/common" -utils_path = "${devicemanager_path}/utils" - services_path = "${devicemanager_path}/services" innerkits_path = "${devicemanager_path}/interfaces/inner_kits" +ext_path = "${devicemanager_path}/ext" + 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/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 dmInitCallback) = 0; - virtual int32_t UnInitDeviceManager(std::string &pkgName) = 0; - virtual int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, + 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, std::string &extra, std::vector &deviceList) = 0; - virtual int32_t RegisterDevStateCallback(std::string &pkgName, std::string &extra, + virtual int32_t RegisterDevStateCallback(const 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, + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) = 0; + virtual int32_t StartDeviceDiscovery(const 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, + virtual int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) = 0; + virtual int32_t AuthenticateDevice(const 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, + virtual int32_t VerifyAuthentication(const 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; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 786e8ca85..ff9f3d246 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -41,7 +41,7 @@ public: class DiscoverCallback { public: virtual ~DiscoverCallback() {} - virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; + // virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; virtual void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) = 0; virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) = 0; }; @@ -49,19 +49,13 @@ public: class AuthenticateCallback { public: virtual ~AuthenticateCallback() {} - virtual void OnAuthResult(std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) = 0; + virtual void OnAuthResult(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; -}; - -class DeviceManagerFaCallback { -public: - virtual ~DeviceManagerFaCallback() {} - virtual void OnCall(std::string ¶mJson) = 0; + virtual ~VerifyAuthCallback() {} + virtual void OnVerifyAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) = 0; }; } // namespace DistributedHardware } // namespace OHOS 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..664b52f15 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -16,8 +16,6 @@ #ifndef OHOS_DEVICE_MANAGER_IMPL_H #define OHOS_DEVICE_MANAGER_IMPL_H -#include - #include "device_manager.h" #include "ipc_client_proxy.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 076a2c007..4adc83e11 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -18,14 +18,12 @@ #include -#include "dm_app_image_info.h" - #define DM_MAX_DEVICE_ID_LEN (96) #define DM_MAX_DEVICE_NAME_LEN (128) namespace OHOS { namespace DistributedHardware { -typedef enum DMDeviceType { +typedef enum DmDeviceType { DEVICE_TYPE_UNKNOWN = 0x00, DEVICE_TYPE_WIFI_CAMERA = 0x08, DEVICE_TYPE_AUDIO = 0x0A, @@ -35,31 +33,26 @@ typedef enum DMDeviceType { 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; + int32_t deviceTypeId; } DmDeviceInfo; typedef struct DmAuthParam { - std::string packageName; - std::string appName; - std::string appDescription; int32_t authType; - int32_t business; - int32_t pincode; + std::string authToken; int32_t direction; - int32_t pinToken; - DmAppImageInfo imageinfo; } DmAuthParam; } // namespace DistributedHardware } // namespace OHOS diff --git a/ohos.build b/ohos.build index f544c0dcc..8630c9844 100644 --- a/ohos.build +++ b/ohos.build @@ -19,7 +19,7 @@ } ], "module_list": [ - "//foundation/distributedhardware/devicemanager/utils:devicemanagerutils", + "//foundation/distributedhardware/devicemanager/utils:devicemanagercommon", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager_native_js", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice:devicemanagerservice", diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 85b8e5774..94f436df1 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -23,23 +23,22 @@ if (defined(ohos_lite)) { executable("devicemanagerservice") { include_dirs = [ "include", - "include/ability", - "include/softbus", - "include/requestauth", - "include/auth", + "include/adapter", + "include/adapter/profile", + "include/authentication", + "include/deviceinfo", + "include/devicestate", + "include/discovery", + "include/dependency/hichain", + "include/dependency/softbus", "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", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/ipc/lite", + "${common_path}/include/utils", + # "${innerkits_path}/native_cpp/include", + # "${innerkits_path}/native_cpp/include/ipc/lite", ] include_dirs += [ @@ -60,8 +59,15 @@ if (defined(ohos_lite)) { ] sources = [ - "src/ability/lite/dm_ability_manager.cpp", - "src/auth/hichain_connector.cpp", + "src/adapter/profile/device_profile_adapter.cpp", + "src/adapter/dm_adapter_manager.cpp", + "src/deviceinfo/dm_device_info_manager.cpp", + "src/devicestate/dm_device_state_manager.cpp", + "src/discovery/dm_discovery_manager.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/ipc/ipc_server_adapter.cpp", "src/ipc/ipc_server_listener_adapter.cpp", "src/ipc/lite/ipc_cmd_parser.cpp", @@ -69,17 +75,6 @@ if (defined(ohos_lite)) { "src/ipc/lite/ipc_server_listenermgr.cpp", "src/ipc/lite/ipc_server_main.cpp", "src/ipc/lite/ipc_server_stub.cpp", - "src/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 = [ @@ -100,68 +95,62 @@ if (defined(ohos_lite)) { "//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", + # "//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/adapter", + "include/adapter/profile", + "include/authentication", + "include/deviceinfo", + "include/devicestate", + "include/discovery", + "include/dependency/hichain", + "include/dependency/softbus", "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", + "${common_path}/include/ipc/standard", "${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", + "//utils/native/base/include", + "//utils/system/safwk/native/include", ] sources = [ - "src/ability/standard/dm_ability_manager.cpp", - "src/auth/hichain_connector.cpp", + "src/adapter/profile/device_profile_adapter.cpp", + "src/adapter/dm_adapter_manager.cpp", + "src/deviceinfo/dm_device_info_manager.cpp", + "src/devicestate/dm_device_state_manager.cpp", + "src/discovery/dm_discovery_manager.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/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", + "${common_path}:devicemanagercommon", "//base/security/deviceauth/services:deviceauth_sdk", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + # "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/aafwk/standard/services/abilitymgr:abilityms", + # "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//utils/native/base:utils", ] @@ -178,7 +167,7 @@ if (defined(ohos_lite)) { "dsoftbus_standard:softbus_client", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "safwk:system_ability_fwk", + # "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "startup_l2:syspara", ] diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h new file mode 100644 index 000000000..9292c787f --- /dev/null +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.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_CRYPTO_ADAPTER_H +#define OHOS_DM_CRYPTO_ADAPTER_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class ICryptoAdapter { +public: + virtual ~ICryptoAdapter() = default; + 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; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_CRYPTO_ADAPTER_H diff --git a/services/devicemanagerservice/include/message/msg_sync_group.h b/services/devicemanagerservice/include/adapter/decision_adapter.h similarity index 56% rename from services/devicemanagerservice/include/message/msg_sync_group.h rename to services/devicemanagerservice/include/adapter/decision_adapter.h index a19d8ff54..8356758c3 100644 --- a/services/devicemanagerservice/include/message/msg_sync_group.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.h @@ -13,33 +13,20 @@ * limitations under the License. */ -#ifndef OHOS_MSG_SYNC_GROUP_H -#define OHOS_MSG_SYNC_GROUP_H +#ifndef OHOS_DM_DECISION_ADAPTER_H +#define OHOS_DM_DECISION_ADAPTER_H -#include #include - -#include "nlohmann/json.hpp" - -#include "msg_head.h" +#include namespace OHOS { namespace DistributedHardware { -class MsgSyncGroup { +class IDecisionAdapter { 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_; + virtual ~IDecisionAdapter() = default; + virtual int32_t FilterDeviceList(std::vector &infoList, const string &filterOptions) = 0; + virtual int32_t SortDeviceList(std::vector &infoList, const string &sortOptions) = 0; }; -} -} -#endif \ No newline at end of file +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DECISION_ADAPTER_H diff --git a/services/devicemanagerservice/include/message/msg_head.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h similarity index 49% rename from services/devicemanagerservice/include/message/msg_head.h rename to services/devicemanagerservice/include/adapter/dm_adapter_manager.h index b79b99f3e..7edae2856 100644 --- a/services/devicemanagerservice/include/message/msg_head.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -13,36 +13,25 @@ * limitations under the License. */ -#ifndef OHOS_MSG_HEAD_H -#define OHOS_MSG_HEAD_H +#ifndef OHOS_DM_ADAPTER_MANAGER_H +#define OHOS_DM_ADAPTER_MANAGER_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 { +class DmAdapterManager { 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(); + DmAdapterManager(); + std::shared_ptr GetDecisionAdapter(); + std::shared_ptr GetProfileAdapter(); + std::shared_ptr GetCryptoAdapter(); + private: - int32_t mMsgType_; - std::string mItfVer_; + std::shared_ptr decisionAdapterPtr_; + std::shared_ptr profileAdapterPtr_; + std::shared_ptr cryptoAdapterPtr_; + }; -} -} -#endif \ No newline at end of file +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DEVICE_STATE_MAGANGER_H diff --git a/display/entry/src/main/js/default/app.js b/services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h similarity index 70% rename from display/entry/src/main/js/default/app.js rename to services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h index 8e47afff1..f2ba658cd 100644 --- a/display/entry/src/main/js/default/app.js +++ b/services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h @@ -13,11 +13,20 @@ * limitations under the License. */ -export default { - onCreate() { - console.info('AceApplication onCreate'); - }, - onDestroy() { - console.info('AceApplication onDestroy'); - } +#ifndef OHOS_DM_ADAPTER_MANAGER_H +#define OHOS_DM_ADAPTER_MANAGER_H + +#include "profile_adapter.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceProfileAdapter : ProfileAdapter { +public: + DeviceProfileAdapter(); + +private: + }; +} +} +#endif diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h new file mode 100644 index 000000000..f63d8f842 --- /dev/null +++ b/services/devicemanagerservice/include/adapter/profile_adapter.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_PROFILE_ADAPTER_H +#define OHOS_DM_PROFILE_ADAPTER_H + + +namespace OHOS { +namespace DistributedHardware { +class IProfileAdapter { +public: + virtual ~IProfileAdapter() = default; + virtual int32_t RegisterProfileListener() = 0; + virtual int32_t UnRegisterProfileListener() = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PROFILE_ADAPTER_H diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h new file mode 100644 index 000000000..09a496f9e --- /dev/null +++ b/services/devicemanagerservice/include/authentication/authentication.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_AUTHENTICATION_H +#define OHOS_DM_AUTHENTICATION_H + + +namespace OHOS { +namespace DistributedHardware { +class IAuthentication { +public: + virtual ~IAuthentication() = default; + virtual int32_t ShowAuthInfo() = 0; + virtual int32_t StartAuth() = 0; +}; +} // 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..68412b322 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/dm_auth_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_AUTH_MANAGER_H +#define OHOS_DM_AUTH_MANAGER_H + +#include +#include + +#include "nlohmann/json.hpp" +#include "softbus_session.h" +#include "device_manager_listener.h" +#include "adapter_manager.h" +#include "authentication.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManager { +public: + DmAuthManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + ~DmAuthManager(); + int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); + int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam); + +private: + std::shared_ptr softbusSession_; + std::shared_ptr hichainConnector_; + std::shared_ptr listenerPtr_; + std::shared_ptr adapterMgr_; + std::map authenticationMap_; + +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_H diff --git a/common/include/device_manager_log.h b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h similarity index 71% rename from common/include/device_manager_log.h rename to services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h index fa0f776a3..13d672f6a 100644 --- a/common/include/device_manager_log.h +++ b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h @@ -13,17 +13,22 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_LOG_H -#define OHOS_DEVICE_MANAGER_LOG_H +#ifndef OHOS_DM_PIN_AUTH_H +#define OHOS_DM_PIN_AUTH_H -#include - -#include "dm_log.h" +#include "authentication.h" namespace OHOS { namespace DistributedHardware { -#define DMLOG(level, fmt, ...) DMLog(level, \ - (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) +class PinAuth : IAuthentication { +public: + PinAuth(); + int32_t ShowAuthInfo(); + int32_t StartAuth(); + +private: + std::shared_ptr pinAuthUiPtr_; +}; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LOG_H +#endif // OHOS_DM_PIN_AUTH_H diff --git a/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h new file mode 100644 index 000000000..4219abf08 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PIN_AUTH_UI_H +#define OHOS_DM_PIN_AUTH_UI_H + + +namespace OHOS { +namespace DistributedHardware { +class PinAuthUI { +public: + PinAuthUI(); + int32_t ShowPinDialog(); + int32_t InputPinDialog(); + +private: +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PIN_AUTH_UI_H diff --git a/services/devicemanagerservice/include/auth/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h similarity index 78% rename from services/devicemanagerservice/include/auth/hichain_connector.h rename to services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index e49700c97..83bef0943 100644 --- a/services/devicemanagerservice/include/auth/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -25,16 +25,15 @@ #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, -}; +// enum { +// HICHAIN_SUCCESS = 0, +// GROUP_CREATE_FAILED = 1, +// MEMBER_ADD_FAILED = 2, +// CREATE_CHANNEL_FAILED = 3, +// }; //move to constant or error code struct GroupInfo { std::string groupName; @@ -48,11 +47,6 @@ struct GroupInfo { 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: @@ -63,22 +57,23 @@ public: static char *onRequest(int64_t requestId, int32_t operationCode, const char *reqParams); }; -class HichainConnector { -DECLARE_SINGLE_INSTANCE(HichainConnector); +class HiChainConnector { public: - int32_t Init(); + HiChainConnector(); + ~HiChainConnector(); + void Init(); bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); int64_t GenRequestId(); - void RegisterConnectorCallback(std::shared_ptr callback); + void RegisterHiChainCallback(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 OnGroupCreated(int64_t requestId, const std::string &returnData); void GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList); - void OnMemberJoin(int64_t requestId, int32_t status); + // 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); @@ -87,10 +82,9 @@ private: 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 +#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..b3b7be6e9 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector_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_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; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H diff --git a/services/devicemanagerservice/include/softbus/softbus_adapter.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h similarity index 30% rename from services/devicemanagerservice/include/softbus/softbus_adapter.h rename to services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index 25f472ff3..02cdbdb07 100644 --- a/services/devicemanagerservice/include/softbus/softbus_adapter.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -1,78 +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_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 +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "softbus_bus_center.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 SoftbusConnector { +public: + SoftbusConnector(); + ~SoftbusConnector(); + void Init(); + int32_t GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum); + int32_t StartDiscovery(const std::string &pkgName, SubscribeInfo *info); + int32_t StopDiscovery(const std::string &pkgName, uint16_t subscribeId); + bool IsDeviceOnLine(const std::string &deviceId); + int32_t GetConnectionIpAddr(const std::string &deviceId, std::string &ipAddr); + ConnectionAddr *GetConnectAddr(const 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: + bool GetSubscribeIdAdapter(const std::string &pkgName, int16_t originId, int32_t &adapterId); + bool GetPkgNameBySubscribeId(int32_t adapterId, const std::string &pkgName); + void SaveDeviceInfoByDiscovery(const DeviceInfo *deviceInfo); + void RemoveDeviceInfoByDiscovery(const std::string &deviceId); + void CopyBasicInfoToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo); + void CopyDeviceInfo(const DmDeviceInfo &srcInfo, const DeviceInfo &dstInfo); + ConnectionAddr *GetConnectAddrByType(ConnectionAddrType type, DeviceInfo *deviceInfo); +private: + struct SubscribeInfoAdapter { + SubscribeInfo info; + uint16_t subscribeIdOrigin; + uint16_t subscribeIdPrefix; + }; + std::map>> subscribeInfos_; + std::map> discoveryDeviceInfoMap_; + std::vector> discoveryDeviceInfoVector_; + uint16_t subscribeIdPrefix_; + std::mutex lock_; + INodeStateCb softbusNodeStateCb_; + IDiscoveryCallback softbusDiscoveryCallback_; + IPublishCallback softbusPublishCallback_; +}; +} // 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..f3b76c9ae --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_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_DISCOVERY_CALLBACK_H +#define OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H + + +namespace OHOS { +namespace DistributedHardware { +class ISoftbusStateCallback { +public: + virtual int32_t OnDeviceFound(); + virtual int32_t OnDeviceLost(); + virtual int32_t OnDiscoveryFailed(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H diff --git a/services/devicemanagerservice/include/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h similarity index 54% rename from services/devicemanagerservice/include/softbus/softbus_session.h rename to services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 03610be2c..42b868a9a 100644 --- a/services/devicemanagerservice/include/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -13,38 +13,36 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H -#define OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H +#ifndef OHOS_DM_SOFTBUS_SESSION_H +#define OHOS_DM_SOFTBUS_SESSION_H #include #include #include -#include "session.h" -#include "single_instance.h" -#include "softbus_common.h" +#include "softbus_session_callback.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(); ~SoftbusSession(); + void Init(); + // 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); + int32_t OpenAuthSession(const char *deviceId); + int32_t RegisterSessionCallback(ISoftbusSessionCallback callback); + int32_t UnRegisterSessionCallback(); + void CloseAuthSession(int32_t sessionId); + // int32_t SendMessages(const char *deviceId, std::vector &messages); + int32_t SendData(int32_t sessionId, std::string &message); + void GetPeerDeviceId(int32_t sessionId, std::string &peerDevId); private: - int32_t SendData(int32_t sessionId, const void *data, int32_t len); + int32_t SendDataInternal(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_ {}; }; 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..5a964f48f --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_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_SESSION_CALLBACK_H +#define OHOS_DM_SOFTBUS_SESSION_CALLBACK_H + + +namespace OHOS { +namespace DistributedHardware { +class ISoftbusSessionCallback { +public: + virtual int32_t OnSessionOpened(); + virtual int32_t OnSessionClosed(); + virtual int32_t OnDataReceived(); +}; +} // 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..dd06e702f --- /dev/null +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_state_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_STATE_CALLBACK_H +#define OHOS_DM_SOFTBUS_STATE_CALLBACK_H + + +namespace OHOS { +namespace DistributedHardware { +class ISoftbusStateCallback { +public: + virtual int32_t OnDeviceOnline(); + virtual int32_t OnDeviceOfflie(); + virtual int32_t OnDeviceChanged(); + virtual int32_t OnDeviceReady(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SOFTBUS_STATE_CALLBACK_H diff --git a/utils/include/cipher/encrypt_utils.h b/services/devicemanagerservice/include/device_manager_impl.h similarity index 32% rename from utils/include/cipher/encrypt_utils.h rename to services/devicemanagerservice/include/device_manager_impl.h index db19b2364..824b00695 100644 --- a/utils/include/cipher/encrypt_utils.h +++ b/services/devicemanagerservice/include/device_manager_impl.h @@ -13,34 +13,42 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H -#define OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H +#ifndef OHOS_DEVICE_MANAGER_IMPL_H +#define OHOS_DEVICE_MANAGER_IMPL_H + +#include +#include + +#include "single_instance.h" +#include "dm_auth_manager.h" +#include "dm_device_info_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "dm_device_info.h" +#include "softbus_connector.h" -#include -#include namespace OHOS { namespace DistributedHardware { -class EncryptUtils { +class DeviceManagerImpl { + DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); 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); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &info); + 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 string &deviceId, const std::string extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); + int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam); +private: + DeviceManagerImpl(); + virtual ~DeviceManagerImpl() = default; + std::shared_ptr authMgrPtr_; + std::shared_ptr deviceInfoMgrPtr_; + std::shared_ptr deviceStateMgrPtr_; + std::shared_ptr discoveryMgrPtr_; + std::shared_ptr softbusConnectorPtr_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H \ No newline at end of file +#endif // OHOS_DEVICE_MANAGER_IMPL_H diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/device_manager_listener.h similarity index 43% rename from services/devicemanagerservice/include/ability/dm_ability_manager.h rename to services/devicemanagerservice/include/device_manager_listener.h index 17a9337d5..5501c66d5 100644 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ b/services/devicemanagerservice/include/device_manager_listener.h @@ -13,53 +13,31 @@ * limitations under the License. */ -#ifndef OHOS_DM_ABILITY_MANAGER_H -#define OHOS_DM_ABILITY_MANAGER_H +#ifndef OHOS_DEVICE_MANAGER_LISTENER_H +#define OHOS_DEVICE_MANAGER_LISTENER_H #include -#include -#include -#include -#include "single_instance.h" +#include "dm_device_info.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); +class DeviceManagerListener { public: - AbilityRole GetAbilityRole(); - AbilityStatus StartAbility(AbilityRole role); - void StartAbilityDone(); - + DeviceManagerListener(); + ~DeviceManagerListener(); + int32_t OnDeviceOnline(const DmDeviceInfo &info); + int32_t OnDeviceOffline(const DmDeviceInfo &info); + int32_t OnDeviceReady(const DmDeviceInfo &info); + int32_t OnDeviceStateChange(const DmDeviceInfo &info); + int32_t OnDeviceFound(uint16_t sbuscribeId, const DmDeviceInfo &info); + int32_t OnDeviceLost(uint16_t subscribeId, const DmDeviceInfo &info); + int32_t OnDiscoveryFailed(uint16_t subscribeId, const std::string &failedReason); + int32_t OnAuthenticateResult(const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason); + int32_t OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string &flag); private: - void waitForTimeout(uint32_t timeout_s); -private: - sem_t mSem_; - AbilityStatus mStatus_; - AbilityRole mAbilityStatus_; }; } // namespace DistributedHardware } // namespace OHOS -#endif +#endif // OHOS_DEVICE_MANAGER_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..7e7385928 --- /dev/null +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.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_DEVICEINFO_MANAGER_H +#define OHOS_DM_DEVICEINFO_MANAGER_H + +#include +#include + +#include "dm_device_info.h" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceInfoManager { +public: + DmDeviceInfoManager(std::shared_ptr softbusConnectorPtr); + ~DmDeviceInfoManager(); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &info); + +private: + std::shared_ptr softbusConnectorPtr_; + std::shared_ptr adapterMgrPtr_; +}; +} // 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..f09cf0ff4 --- /dev/null +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.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_DEVICE_STATE_MAGANGER_H +#define OHOS_DM_DEVICE_STATE_MAGANGER_H + + +#include "softbus_connector.h" +#include "adapter_manager.h" +#include "device_manager_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceStateManager { +public: + DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + ~DmDeviceStateManager(); + +private: + std::shared_ptr softbusConnectorPtr_; + std::shared_ptr adapterMgrPtr_; + std::shared_ptr listenerPtr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DEVICE_STATE_MAGANGER_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..371c914bc --- /dev/null +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.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_DISCOVERY_MANAGER_H +#define OHOS_DM_DISCOVERY_MANAGER_H + + +#include "softbus_connector.h" +#include "device_manager_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDiscoveryManager { +public: + DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + ~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); + +private: + std::shared_ptr softbusConnectorPtr_; + std::shared_ptr listenerPtr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DISCOVERY_MANAGER_H diff --git a/services/devicemanagerservice/include/eventbus/event.h b/services/devicemanagerservice/include/eventbus/event.h new file mode 100644 index 000000000..8d9019cdc --- /dev/null +++ b/services/devicemanagerservice/include/eventbus/event.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_EVENTBUS_EVENT_H +#define OHOS_DM_EVENTBUS_EVENT_H + +#include + +#include "event_sender.h" + +namespace OHOS { +namespace DistributedHardware { +#define TYPEINDENT(className) public: \ + virtual std::string GetType() const \ + { \ + return #className; \ + } + +class Event { +TYPEINDENT(Event) + +public: + Event(EventSender &sender) :sender_(sender) {} + + virtual ~Event() = default; + + const EventSender &GetSender() const + { + return sender_; + } +private: + EventSender &sender_; +} +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_EVENTBUS_EVENT_H diff --git a/utils/src/ipc/standard/ipc_cmd_register.cpp b/services/devicemanagerservice/include/eventbus/event_bus.h similarity index 31% rename from utils/src/ipc/standard/ipc_cmd_register.cpp rename to services/devicemanagerservice/include/eventbus/event_bus.h index e958dfd04..110e6c994 100644 --- a/utils/src/ipc/standard/ipc_cmd_register.cpp +++ b/services/devicemanagerservice/include/eventbus/event_bus.h @@ -13,43 +13,62 @@ * limitations under the License. */ -#include "ipc_cmd_register.h" +#ifndef OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H +#define OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include +#include +#include + +#include "event_handler.h" +#include "event.h" +#include "eventbus_handler.h" +#include "event_registeration.h" namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); - -int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) -{ - 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; - } - return (setRequestMapIter->second)(pBaseReq, data); -} - -int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - 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; +class EventBus final { +public: + EventBus() = default; + ~EventBus() = default; + + static EventBus *GetInstance() + { + if (instance_ == nullptr) { + instance_ = new EventBus(); + } + if (!eventBusHandler_) { + auto eventBusRunner = AppExecFwk::EventRunner::Create("EventbusHandler"); + eventBusHandler_ = std::make_shared(eventBusRunner); + } + return instance_; } - return (readResponseMapIter->second)(reply, pBaseRsp); -} - -int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &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; + +private: + template + static void PostEventInner(T &e) + { + Eventbus *instance = GetInstace(); + Registrations *registerations = instance->handlers[e.GetType()]; + if (registerations == nullptr) { + return; + } + + for (auto ® : *Registrations) { + if ((reg->GetSender() == nullptr) || (reg->GetSender() == &e.GetSender())) { + static_cast *>(const_cast(reg->GetHandler()))->Dispatch(e); + } + } } - return (onIpcCmdMapIter->second)(data, reply); -} + +private: + static EventBus *instance_; + static std::share_ptr eventBusHandler_; + using Registrations = std::set>; + using TypeMap = std::unordered_map> *>; + TypeMap handlers_; + +}; } // namespace DistributedHardware } // namespace OHOS +#endif // OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H diff --git a/services/devicemanagerservice/include/eventbus/event_registration.h b/services/devicemanagerservice/include/eventbus/event_registration.h new file mode 100644 index 000000000..321d90024 --- /dev/null +++ b/services/devicemanagerservice/include/eventbus/event_registration.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H +#define OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H + +#include +#include + +#include "event_sender.h" + +namespace OHOS { +namespace DistributedHardware { +class EventRegistration { +public: + using Registrations = std::set>; + EventRegistration(void * const handler, EventSender * const sender) : handler_(handler), sender_(sender) {} + virtual ~EventRegistration() {} + + const void *GetHandler() + { + return handler_ + } + + const EventSender *GetSender() + { + return sender_; + } + +private: + void * const handler_; + EventSender * const sender_; + +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H diff --git a/services/devicemanagerservice/include/eventbus/event_sender.h b/services/devicemanagerservice/include/eventbus/event_sender.h new file mode 100644 index 000000000..a4c97c3fd --- /dev/null +++ b/services/devicemanagerservice/include/eventbus/event_sender.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_EVENTBUS_EVENT_SENDER_H +#define OHOS_DM_EVENTBUS_EVENT_SENDER_H + +namespace OHOS { +namespace DistributedHardware { +template +class EventSender { +public: + virtual ~EventSender() = default; + +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_EVENTBUS_EVENT_SENDER_H diff --git a/services/devicemanagerservice/include/eventbus/eventbus_handler.h b/services/devicemanagerservice/include/eventbus/eventbus_handler.h new file mode 100644 index 000000000..f443339e0 --- /dev/null +++ b/services/devicemanagerservice/include/eventbus/eventbus_handler.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_EVENTBUS_EVENT_HANDLE_H +#define OHOS_DM_EVENTBUS_EVENT_HANDLE_H + +namespace OHOS { +namespace DistributedHardware { +template +class EventBusHandler { +public: + EventBusHandler() {} + + virtual ~EventBusHandler() = default; + + virtual void OnEvent(T &e) = 0; + + void Dispatch(T &e) + { + OnEvent(e); + } +} +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_EVENTBUS_EVENT_HANDLE_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_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/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/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/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/adapter/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp new file mode 100644 index 000000000..dd2d04b1f --- /dev/null +++ b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_adapter_manager.h" +#include "dm_log.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +DmAdapterManager::DmAdapterManager() +{ + DMLOG(DM_LOG_INFO, "DmAdapterManager constructor"); +} + +std::shared_ptr DmAdapterManager::GetDecisionAdapter() +{ + return decisionAdapterPtr_; +} + +std::shared_ptr DmAdapterManager::GetProfileAdapter() +{ + return profileAdapterPtr_; +} + +std::shared_ptr DmAdapterManager::GetCryptoAdapter() +{ + return cryptoAdapterPtr_; +} + +} +} 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..b64213350 --- /dev/null +++ b/services/devicemanagerservice/src/authentication/dm_auth_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_auth_manager.h" +#include "dm_log.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +DmAuthManager::DmAuthManager(std::shared_ptr softbusConnectorPtr, + std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) +{ + DMLOG(DM_LOG_INFO, "DmAuthManager constructor"); +} + +DmAuthManager::~DmAuthManager() +{ + DMLOG(DM_LOG_INFO, "DmAuthManager destructor"); +} + +int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra) +{ + return SUCCESS; +} + +int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const string &deviceId) +{ + return SUCCESS; +} + +int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) +{ + return SUCCESS; +} + +} +} diff --git a/services/devicemanagerservice/src/auth/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp similarity index 68% rename from services/devicemanagerservice/src/auth/hichain_connector.cpp rename to services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 88516aebd..536064802 100644 --- a/services/devicemanagerservice/src/auth/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -21,40 +21,29 @@ #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" +#include "dm_anonymous.h" +#include "dm_log.h" +#include "dm_constants.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); +// 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; +// } void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) { @@ -79,15 +68,25 @@ void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) } } -int HichainConnector::Init() +HiChainConnector::HiChainConnector() +{ + Init(); +} + +HiChainConnector::~HiChainConnector() +{ + +} + +void HiChainConnector::Init() { - DMLOG(DM_LOG_INFO, "HichainConnector::init, init device auth service."); + 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; + DMLOG(DM_LOG_INFO, "HiChainConnector::init, failed to init group manager!"); + return; } deviceAuthCallback_.onTransmit = nullptr; @@ -96,19 +95,19 @@ int HichainConnector::Init() deviceAuthCallback_.onRequest = HichainAuthenCallBack::onRequest; deviceGroupManager_->regCallback(DEVICE_MANAGER_APP.c_str(), &deviceAuthCallback_); - DMLOG(DM_LOG_INFO, "HichainConnector::init, init hichain adapter success."); + DMLOG(DM_LOG_INFO, "HiChainConnector::init, init hichain adapter success."); return 0; } -int64_t HichainConnector::GenRequestId() +int64_t HiChainConnector::GenRequestId() { return EncryptUtils::GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); } -int32_t HichainConnector::CreateGroup(int64_t requestId, const std::string &groupName) +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); + DMLOG(DM_LOG_ERROR, "HiChainConnector::CreateGroup group manager is null, requestId %lld.", requestId); return FAIL; } @@ -117,7 +116,7 @@ int32_t HichainConnector::CreateGroup(int64_t requestId, const std::string &grou DeleteGroup(groupInfo.groupId); } - DMLOG(DM_LOG_INFO, "HichainConnector::CreateGroup requestId %lld", requestId); + DMLOG(DM_LOG_INFO, "HiChainConnector::CreateGroup requestId %lld", requestId); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; @@ -138,7 +137,7 @@ int32_t HichainConnector::CreateGroup(int64_t requestId, const std::string &grou return SUCCESS; } -int32_t HichainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInfo) +int32_t HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInfo) { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); @@ -153,28 +152,28 @@ int32_t HichainConnector::IsGroupCreated(std::string groupName, GroupInfo &group return false; } -int32_t HichainConnector::GetGroupInfo(std::string queryParams, std::vector &groupList) +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); + 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"); + 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."); + 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); + 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); @@ -185,7 +184,7 @@ int32_t HichainConnector::GetGroupInfo(std::string queryParams, std::vector groupInfos = jsonObject.get>(); if (groupInfos.size() == 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetGroupInfo group failed, groupInfos is empty."); + DMLOG(DM_LOG_ERROR, "HiChainConnector::GetGroupInfo group failed, groupInfos is empty."); return false; } @@ -193,58 +192,11 @@ int32_t HichainConnector::GetGroupInfo(std::string queryParams, std::vector 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) +int32_t HiChainConnector::AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth) { - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber"); + DMLOG(DM_LOG_INFO, "HiChainConnector::AddMemeber"); if (deviceGroupManager_ == nullptr) { - DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber group manager is null."); + DMLOG(DM_LOG_INFO, "HiChainConnector::AddMemeber group manager is null."); return -1; } @@ -262,62 +214,111 @@ int32_t HichainConnector::AddMemeber(std::string deviceId, std::shared_ptraddMemberToGroup(msgResponseAuth->GetRequestId(), DEVICE_MANAGER_APP.c_str(), tmpStr.c_str()); } -std::string HichainConnector::GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth) +// 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); +// } + + + +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"); + DMLOG(DM_LOG_ERROR, "HiChainConnector::GetConnectPara addrInfo error"); return ""; } - DMLOG(DM_LOG_ERROR, "HichainConnector::GetConnectPara get addrInfo"); + 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"); + 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"); + 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"); + 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"); + 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"); + DMLOG(DM_LOG_ERROR, "HiChainConnector::AddMemeber addrInfo not right"); return ""; } return jsonPara.dump(); } -void HichainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList) +void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList) { - DMLOG(DM_LOG_INFO, "HichainConnector::GetRelatedGroups Start to get local related groups."); + 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); + DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups faild , ret: %d.", ret); return; } if (returnGroups == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups faild , returnGroups is 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."); + DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups group failed, groupNum is 0."); return; } @@ -330,7 +331,7 @@ void HichainConnector::GetRelatedGroups(std::string deviceId, std::vector groupInfos = jsonObject.get>(); if (groupInfos.size() == 0) { - DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups group failed, groupInfos is empty."); + DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups group failed, groupInfos is empty."); return; } @@ -338,7 +339,7 @@ void HichainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList, std::vector &syncGroupList) +void HiChainConnector::GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList) { if (groupList.empty()) { DMLOG(DM_LOG_ERROR, "groupList is empty."); @@ -353,7 +354,7 @@ void HichainConnector::GetSyncGroupList(std::vector &groupList, std:: } } -bool HichainConnector::IsGroupInfoInvalid(GroupInfo &group) +bool HiChainConnector::IsGroupInfoInvalid(GroupInfo &group) { if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC || group.groupOwner != DEVICE_MANAGER_APP) { @@ -362,7 +363,7 @@ bool HichainConnector::IsGroupInfoInvalid(GroupInfo &group) return false; } -void HichainConnector::SyncGroups(std::string deviceId, std::vector &remoteGroupIdList) +void HiChainConnector::SyncGroups(std::string deviceId, std::vector &remoteGroupIdList) { std::vector groupInfoList; GetRelatedGroups(deviceId, groupInfoList); @@ -378,7 +379,7 @@ void HichainConnector::SyncGroups(std::string deviceId, std::vector } } -int32_t HichainConnector::DelMemberFromGroup(std::string groupId, std::string 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", @@ -391,13 +392,13 @@ int32_t HichainConnector::DelMemberFromGroup(std::string groupId, std::string de 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); + DMLOG(DM_LOG_ERROR, "HiChainConnector::DelMemberFromGroup faild , ret: %d.", ret); return ret; } return 0; } -void HichainConnector::DeleteGroup(std::string &groupId) +void HiChainConnector::DeleteGroup(std::string &groupId) { int64_t requestId = GenRequestId(); nlohmann::json jsonObj; @@ -406,7 +407,7 @@ void HichainConnector::DeleteGroup(std::string &groupId) 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); + DMLOG(DM_LOG_ERROR, "HiChainConnector::DeleteGroup faild , ret: %d.", ret); } } @@ -420,12 +421,12 @@ void HichainAuthenCallBack::onFinish(int64_t requestId, int32_t operationCode, c 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); + HiChainConnector::GetInstance().OnMemberJoin(requestId, SUCCESS); } if (operationCode == GroupOperationCode::GROUP_CREATE) { DMLOG(DM_LOG_INFO, "Create group success"); - HichainConnector::GetInstance().OnGroupCreated(requestId, data); + HiChainConnector::GetInstance().OnGroupCreated(requestId, data); } if (operationCode == GroupOperationCode::MEMBER_DELETE) { @@ -446,12 +447,12 @@ void HichainAuthenCallBack::onError(int64_t requestId, int32_t operationCode, in if (operationCode == GroupOperationCode::MEMBER_JOIN) { DMLOG(DM_LOG_ERROR, "Add Member To Group failed"); - HichainConnector::GetInstance().OnMemberJoin(requestId, FAIL); + HiChainConnector::GetInstance().OnMemberJoin(requestId, FAIL); } if (operationCode == GroupOperationCode::GROUP_CREATE) { DMLOG(DM_LOG_ERROR, "Create group failed"); - HichainConnector::GetInstance().OnGroupCreated(requestId, "{}"); + HiChainConnector::GetInstance().OnGroupCreated(requestId, "{}"); } if (operationCode == GroupOperationCode::MEMBER_DELETE) { diff --git a/services/devicemanagerservice/src/softbus/softbus_adapter.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp similarity index 50% rename from services/devicemanagerservice/src/softbus/softbus_adapter.cpp rename to services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index f5da3a1a3..dcf471e1b 100644 --- a/services/devicemanagerservice/src/softbus/softbus_adapter.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -1,522 +1,313 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_error_code.h" +#include "dm_log.h" +#include "dm_anonymous.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +SoftbusConnector::SoftbusConnector() { + DMLOG(DM_LOG_INFO,"SoftbusConnector constructor"); + Init(); +} + +SoftbusConnector::~SoftbusConnector() { + DMLOG(DM_LOG_INFO,"SoftbusConnector destructor"); +} + +SoftbusConnector::Init() +{ + //TODO:optimize implementation later + 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."); + //TODO:check system properties first + 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 SoftbusConnector::GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum) +{ + DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices 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_DEBUG, "SoftbusConnector::GetTrustDevices success, pkgName: %s, deviceCount %d", pkgName.c_str(), *infoNum); + return DEVICEMANAGER_OK; +} + +int32_t SoftbusConnector::StartDiscovery(const 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 SoftbusConnector::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 SoftbusConnector::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 SoftbusConnector::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; +} + +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(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 SoftbusConnector::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 SoftbusConnector::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; +} + + + + + +} // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp similarity index 41% rename from services/devicemanagerservice/src/softbus/softbus_session.cpp rename to services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 84bf739a2..c56d65375 100644 --- a/services/devicemanagerservice/src/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -14,67 +14,24 @@ */ #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" +#include "dm_constants.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) +SoftbusSession::SoftbusSession() { - (void)sessionId; - (void)data; - (void)ext; - (void)param; - DMLOG(DM_LOG_INFO, "sessionId:%d", sessionId); + Init(); } -IMPLEMENT_SINGLE_INSTANCE(SoftbusSession); - SoftbusSession::~SoftbusSession() { (void)RemoveSessionServer(PKG_NAME, SESSION_NAME); } -int32_t SoftbusSession::Start() +void SoftbusSession::Init() { - 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"); @@ -83,93 +40,49 @@ int32_t SoftbusSession::Start() 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) +int32_t SoftbusSession::OpenAuthSession(const char *deviceId) { - 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; + 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; } - 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; + sessionId = ::OpenAuthSession(SESSION_NAME, addrInfo, 1, nullptr); + if (sessionId < 0) { + DMLOG(DM_LOG_ERROR, "open session error, ret:%d", sessionId); + return sessionId; } - - std::string message = (char *)buf; - AuthManager::GetInstance().OnReceiveMsg(sessionId, message); - free(buf); - DMLOG(DM_LOG_INFO, "OnBytesReceived completed"); - return; + sessionIdSet_.insert(sessionId); + DMLOG(DM_LOG_INFO, "opened auth session is:%d", sessionId); + return sessionId; } -void SoftbusSession::CloseSession(int32_t sessionId) +void SoftbusSession::CloseAuthSession(int32_t sessionId) { DMLOG(DM_LOG_INFO, "CloseSession in"); ::CloseSession(sessionId); } -int32_t SoftbusSession::SendData(int32_t sessionId, const void *data, int32_t len) +void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) { - 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); + 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; } - return ret; + + DMLOG(DM_LOG_ERROR, "GetPeerDeviceId failed for session:%d", sessionId); + peerDevId = ""; } -// send message by sessionId (channel opened) -int32_t SoftbusSession::SendMsg(int32_t sessionId, std::string &message) +int32_t SoftbusSession::SendData(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)); @@ -190,41 +103,20 @@ int32_t SoftbusSession::SendMsg(int32_t sessionId, std::string &message) 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; - } +// 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; +// } - 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/device_manager_impl.cpp b/services/devicemanagerservice/src/device_manager_impl.cpp new file mode 100644 index 000000000..f0cbbb8d3 --- /dev/null +++ b/services/devicemanagerservice/src/device_manager_impl.cpp @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_impl.h" +#include "dm_log.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); + +int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) +{ + if (pkgName == nullptr || pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, pkgName is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + + if (deviceList == nullptr) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, deviceList is null"); + return ERROR_INPUT_PARA_EMPTY; + } + + //TODO:check permissions + + if (deviceInfoMgrPtr_ == nullptr) { + deviceInfoMgrPtr_ = std::make_shared(); + } + return deviceInfoMgrPtr_->GetTrustedDeviceList(pkgName, extra, deviceList); +} + +int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &info) +{ + if (deviceInfoMgrPtr_ == nullptr) { + deviceInfoMgrPtr_ = std::make_shared(); + } + return deviceInfoMgrPtr_->GetLocalDeviceInfo(info); +} + +int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) +{ + if (pkgName == nullptr || pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, pkgName is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + if (discoveryMgrPtr_ == nullptr) { + discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_); + } + return discoveryMgrPtr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); +} + +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + if (pkgName == nullptr || pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, pkgName is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + if (discoveryMgrPtr_ == nullptr) { + discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_); + } + return discoveryMgrPtr_->StopDeviceDiscovery(pkgName, subscribeId); +} + +int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra) +{ + if (pkgName == nullptr || pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, pkgName is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + + if (deviceId == nullptr || deviceId.empty()) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, deviceId is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + + if (authMgrPtr_ == nullptr) { + authMgrPtr_ = std::make_shared(softbusConnectorPtr_); + } + return authMgrPtr_->AuthenticateDevice(pkgName, authType, deviceId, extra); +} + +int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); +{ + if (pkgName == nullptr || pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, pkgName is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + + if (deviceId == nullptr || deviceId.empty()) { + DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, deviceId is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + + if (authMgrPtr_ == nullptr) { + authMgrPtr_ = std::make_shared(softbusConnectorPtr_); + } + return authMgrPtr_->UnAuthenticateDevice(pkgName, deviceId); +} + +int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam) +{ + if (pkgName == nullptr || pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, pkgName is empty"); + return ERROR_INPUT_PARA_EMPTY; + } + + if (authMgrPtr_ == nullptr) { + authMgrPtr_ = std::make_shared(softbusConnectorPtr_); + } + return authMgrPtr_->VerifyAuthentication(pkgName, authParam); +} + +} +} diff --git a/services/devicemanagerservice/src/message/msg_head.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp similarity index 45% rename from services/devicemanagerservice/src/message/msg_head.cpp rename to services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 77cc84416..cc7410052 100644 --- a/services/devicemanagerservice/src/message/msg_head.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -13,40 +13,34 @@ * limitations under the License. */ -#include "msg_head.h" -#include "device_manager_log.h" -#include "constants.h" +#include "dm_device_info_manager.h" +#include "dm_log.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { -void MsgHead::Encode(nlohmann::json &json) + +DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr softbusConnectorPtr) : softbusConnectorPtr_(softbusConnectorPtr) { - json[TAG_VER] = DM_ITF_VER; - json[TAG_TYPE] = mMsgType_; + DMLOG(DM_LOG_INFO,"DmDeviceInfoManager constructor"); } -std::shared_ptr MsgHead::Decode(nlohmann::json &json) +int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - if (json.contains(TAG_TYPE) == false || json.contains(TAG_VER) == false) { - DMLOG(DM_LOG_ERROR, "err json string"); - return nullptr; + //TODO: extra is not null then start adatper manager + if (extra != nullptr && !extra.empty()) { + adapterMgrPtr_ = std::make_shared(); } + //get trusted device list from softbus and copy to vector + return SUCCESS; - 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() +int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info) { - return mMsgType_; + //get device info from softbus and copy to vector + return SUCCESS; +} + } } -} \ No newline at end of file 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..1e5e6b883 --- /dev/null +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -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. + */ + +#include "dm_device_state_manager.h" +#include "dm_log.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, + std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) +{ + DMLOG(DM_LOG_INFO, "DmDeviceStateManager constructor"); +} + +DmDeviceStateManager::~DmDeviceStateManager() +{ + DMLOG(DM_LOG_INFO,"DmDeviceStateManager destructor"); +} + +} +} diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp similarity index 47% rename from services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp rename to services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 3b5885159..ecd76b4eb 100644 --- a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -13,42 +13,33 @@ * limitations under the License. */ -#include "dm_ability_manager.h" - -#include "semaphore.h" - -#include "constants.h" -#include "device_manager_log.h" +#include "dm_discovery_manager.h" +#include "dm_log.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(DmAbilityManager); -AbilityRole DmAbilityManager::GetAbilityRole() +DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, + std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) { - return mAbilityStatus_; + DMLOG(DM_LOG_INFO, "DmDiscoveryManager constructor"); } -AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) +DmDiscoveryManager::~DmDiscoveryManager() { - // not support for L1 yet, do nothing. jsut save status and role - mAbilityStatus_ = role; - mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; - return mStatus_; + DMLOG(DM_LOG_INFO, "DmDiscoveryManager destructor"); } -void DmAbilityManager::waitForTimeout(uint32_t timeout_s) +int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - ts.tv_sec += timeout_s; - sem_timedwait(&mSem_, &ts); + return SUCCESS; } -void DmAbilityManager::StartAbilityDone() +int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; - sem_post(&mSem_); + return SUCCESS; } + } } 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_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/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/utils/include/ipc/lite/ipc_cmd_register.h b/utils/include/ipc/lite/ipc_cmd_register.h deleted file mode 100644 index 0144df0d6..000000000 --- a/utils/include/ipc/lite/ipc_cmd_register.h +++ /dev/null @@ -1,114 +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_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H - -#include -#include -#include - -#include "liteipc_adapter.h" -#include "single_instance.h" - -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) - { - onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); - }; - 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_; - std::unordered_map onIpcCmdFuncMap_; - std::unordered_map onIpcServerCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_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 deleted file mode 100644 index c2c5d585d..000000000 --- a/utils/include/ipc/standard/ipc_cmd_register.h +++ /dev/null @@ -1,94 +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_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H - -#include -#include -#include - -#include "iremote_broker.h" -#include "single_instance.h" - -#include "ipc_types.h" -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ - static int32_t IpcCmdProcess##cmdCode(paraA, paraB) - -using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); -using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); -using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); - -class IpcCmdRegister { -DECLARE_SINGLE_INSTANCE(IpcCmdRegister); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - int32_t SetRequest(int32_t cmdCode, 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_; - std::unordered_map onIpcCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ 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 deleted file mode 100644 index 4fbab5a16..000000000 --- a/utils/src/ipc/lite/ipc_cmd_register.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 "ipc_cmd_register.h" - -#include "device_manager_errno.h" -#include "device_manager_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) -{ - 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; - } - return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); -} - -int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - 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; - } - return (readResponseMapIter->second)(reply, pBaseRsp); -} - -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; - } - (onIpcCmdMapIter->second)(reply); - return DEVICEMANAGER_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; - } - (onIpcServerCmdMapIter->second)(req, reply); - return DEVICEMANAGER_OK; -} -} // namespace DistributedHardware -} // namespace OHOS -- Gitee From 22096bf0a38bc56a9828e184b34d435d0e361326 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Wed, 24 Nov 2021 10:43:14 +0800 Subject: [PATCH 003/110] adjusted the structure of the common directory, deleted some files and modified some codes. --- common/include/{ => constants}/dm_constants.h | 36 +++++++++++ common/include/dm_error_code.h | 61 ------------------- common/include/utils/dm_anonymous.h | 11 ++-- common/include/{ => utils}/dm_log.h | 1 + common/src/utils/dm_anonymous.cpp | 33 ++++------ common/src/{ => utils}/dm_log.cpp | 1 - 6 files changed, 56 insertions(+), 87 deletions(-) rename common/include/{ => constants}/dm_constants.h (79%) delete mode 100644 common/include/dm_error_code.h rename common/include/{ => utils}/dm_log.h (99%) rename common/src/{ => utils}/dm_log.cpp (99%) diff --git a/common/include/dm_constants.h b/common/include/constants/dm_constants.h similarity index 79% rename from common/include/dm_constants.h rename to common/include/constants/dm_constants.h index f8cf91ac7..5b3403acb 100644 --- a/common/include/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -59,6 +59,42 @@ namespace DistributedHardware { 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 DEVICEMANAGER_FAILED = -10000; + const int32_t DEVICEMANAGER_SERVICE_NOT_READY; + const int32_t DEVICEMANAGER_DEVICE_ALREADY_TRUSTED; + const int32_t DEVICEMANAGER_GET_TRUSTED_DEVICE_FAILED; + const int32_t DEVICEMANAGER_ALREADY_INIT; + const int32_t DEVICEMANAGER_INIT_FAILED; + const int32_t DEVICEMANAGER_MALLOC_ERROR; + const int32_t DEVICEMANAGER_LOCK_ERROR; + const int32_t DEVICEMANAGER_INVALID_PARAM; + const int32_t DEVICEMANAGER_INVALID_VALUE; + const int32_t DEVICEMANAGER_COPY_FAILED; + const int32_t DEVICEMANAGER_NULLPTR; + const int32_t DEVICEMANAGER_DISCOVERY_FAILED; + const int32_t DEVICEMANAGER_FLATTEN_OBJECT; + const int32_t DEVICEMANAGER_WRITE_FAILED; + const int32_t DEVICEMANAGER_IPC_FAILED; + const int32_t DEVICEMANAGER_IPC_TRANSACTION_FAILED; + const int32_t DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + const int32_t HICHAIN_GROUP_CREATE_FAILED; + const int32_t HICHAIN_MEMBER_ADD_FAILED; + const int32_t HICHAIN_CREATE_CHANNEL_FAILED; + const int32_t MSG_DECODE_PARA_FAILED; + const int32_t ENCRYPT_UTILS_INVALID_PARAM; + const int32_t ENCRYPT_UTILS_GCM_SETKEY_FAILED; + const int32_t ENCRYPT_UTILS_GCM_CRYPT_FAILED; + const int32_t ENCRYPT_UTILS_GCM_AUTH_DECRYPT_FAILED; + const int32_t ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; + const int32_t ENCRYPT_UTILS_AES_GCM_DECRYPT_FAILED; + const int32_t ERR_GEN_RANDOM_PINTOKEN_FAILED; + const int32_t PIN_CODE_CHECK_FAILED; + const int32_t PIN_TOKEN_CHECK_FAILED; + const int32_t DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; + const int32_t DEVICEMANAGER_OPEN_SESSION_FAILED; + const int32_t AUTH_PARA_INVALID; + const int32_t ENCODE_DATA_ERROR; + const int32_t DEVICEMANAGER_OK = 0; const int32_t ENCRYPT_TAG_LEN = 32; diff --git a/common/include/dm_error_code.h b/common/include/dm_error_code.h deleted file mode 100644 index ab01276d9..000000000 --- a/common/include/dm_error_code.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/utils/dm_anonymous.h b/common/include/utils/dm_anonymous.h index 4144e517c..a31ad8a60 100644 --- a/common/include/utils/dm_anonymous.h +++ b/common/include/utils/dm_anonymous.h @@ -13,14 +13,15 @@ * limitations under the License. */ -#ifndef ANONYMOUS_STRING_H -#define ANONYMOUS_STRING_H +#ifndef OHOS_DEVICE_MANAGER_ANONYMOUS_H +#define OHOS_DEVICE_MANAGER_ANONYMOUS_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 +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DEVICE_MANAGER_ANONYMOUS_H \ No newline at end of file diff --git a/common/include/dm_log.h b/common/include/utils/dm_log.h similarity index 99% rename from common/include/dm_log.h rename to common/include/utils/dm_log.h index b8ea389a3..ba6a4b749 100644 --- a/common/include/dm_log.h +++ b/common/include/utils/dm_log.h @@ -34,4 +34,5 @@ void DMLog(DMLogLevel logLevel, const char *fmt, ...); (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/src/utils/dm_anonymous.cpp b/common/src/utils/dm_anonymous.cpp index 1b6263eeb..0b7369606 100644 --- a/common/src/utils/dm_anonymous.cpp +++ b/common/src/utils/dm_anonymous.cpp @@ -15,8 +15,6 @@ #include "dm_anonymous.h" -#include "securec.h" - namespace OHOS { namespace DistributedHardware { std::string GetAnonyString(const std::string &value) @@ -24,13 +22,14 @@ 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; } + std::string res; if (strLen <= INT32_SHORT_ID_LENGTH) { res += value[0]; res += tmpStr; @@ -46,23 +45,17 @@ std::string GetAnonyString(const std::string &value) 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] = '*'; - } + std::string tempString = std::to_string(value); + int32_t length = tempString.length(); if (length == 0x01) { - tempBuffer[0] = '*'; - } + tempString[0] = '*'; + return tempString; + } - std::string tempSting(tempBuffer); - return tempSting; -} + for (int32_t i = 1; i < length - 1; i++) { + tempString[i] = '*'; + } + return tempString; } -} \ No newline at end of file +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/common/src/dm_log.cpp b/common/src/utils/dm_log.cpp similarity index 99% rename from common/src/dm_log.cpp rename to common/src/utils/dm_log.cpp index 0875627ee..9887471b9 100644 --- a/common/src/dm_log.cpp +++ b/common/src/utils/dm_log.cpp @@ -22,7 +22,6 @@ #include "hilog/log.h" #else #include - #endif namespace OHOS { -- Gitee From 9c009ad0b97cc92b3671a4cc5a0b8a268aa28820 Mon Sep 17 00:00:00 2001 From: puhui Date: Wed, 24 Nov 2021 21:13:33 +0800 Subject: [PATCH 004/110] =?UTF-8?q?=E6=9E=B6=E6=9E=84=E8=B0=83=E6=95=B4?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/include/constants/dm_constants.h | 351 +++++++++--------- services/devicemanagerservice/BUILD.gn | 6 +- .../dependency/softbus/softbus_connector.h | 60 +-- .../dependency/softbus/softbus_session.h | 8 +- .../dependency/softbus/softbus_connector.cpp | 162 +++++++- .../dependency/softbus/softbus_session.cpp | 79 +++- .../src/deviceinfo/dm_device_info_manager.cpp | 3 +- 7 files changed, 446 insertions(+), 223 deletions(-) diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index 5b3403acb..12ee9cbab 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -21,183 +21,202 @@ 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 DEVICEMANAGER_FAILED = -10000; - const int32_t DEVICEMANAGER_SERVICE_NOT_READY; - const int32_t DEVICEMANAGER_DEVICE_ALREADY_TRUSTED; - const int32_t DEVICEMANAGER_GET_TRUSTED_DEVICE_FAILED; - const int32_t DEVICEMANAGER_ALREADY_INIT; - const int32_t DEVICEMANAGER_INIT_FAILED; - const int32_t DEVICEMANAGER_MALLOC_ERROR; - const int32_t DEVICEMANAGER_LOCK_ERROR; - const int32_t DEVICEMANAGER_INVALID_PARAM; - const int32_t DEVICEMANAGER_INVALID_VALUE; - const int32_t DEVICEMANAGER_COPY_FAILED; - const int32_t DEVICEMANAGER_NULLPTR; - const int32_t DEVICEMANAGER_DISCOVERY_FAILED; - const int32_t DEVICEMANAGER_FLATTEN_OBJECT; - const int32_t DEVICEMANAGER_WRITE_FAILED; - const int32_t DEVICEMANAGER_IPC_FAILED; - const int32_t DEVICEMANAGER_IPC_TRANSACTION_FAILED; - const int32_t DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; - const int32_t HICHAIN_GROUP_CREATE_FAILED; - const int32_t HICHAIN_MEMBER_ADD_FAILED; - const int32_t HICHAIN_CREATE_CHANNEL_FAILED; - const int32_t MSG_DECODE_PARA_FAILED; - const int32_t ENCRYPT_UTILS_INVALID_PARAM; - const int32_t ENCRYPT_UTILS_GCM_SETKEY_FAILED; - const int32_t ENCRYPT_UTILS_GCM_CRYPT_FAILED; - const int32_t ENCRYPT_UTILS_GCM_AUTH_DECRYPT_FAILED; - const int32_t ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; - const int32_t ENCRYPT_UTILS_AES_GCM_DECRYPT_FAILED; - const int32_t ERR_GEN_RANDOM_PINTOKEN_FAILED; - const int32_t PIN_CODE_CHECK_FAILED; - const int32_t PIN_TOKEN_CHECK_FAILED; - const int32_t DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; - const int32_t DEVICEMANAGER_OPEN_SESSION_FAILED; - const int32_t AUTH_PARA_INVALID; - const int32_t ENCODE_DATA_ERROR; - const int32_t DEVICEMANAGER_OK = 0; - - 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"; + const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; + const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; + + // 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; + + enum { + DM_FAILED = (-10000), + DM_INPUT_PARA_EMPTY, + DM_INPUT_PARA_INVALID, + DM_SERVICE_NOT_READY, + DM_DEVICE_ALREADY_TRUSTED, + DM_OK = 0; + }; + + //Softbus + const char *DM_CAPABILITY_OSD = "osdCapability"; + 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_DEVICEINFO_MAX_SIZE = 20; + + //HiChain + + // 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 DEVICEMANAGER_FAILED = -10000; + // const int32_t DEVICEMANAGER_SERVICE_NOT_READY; + // const int32_t DEVICEMANAGER_DEVICE_ALREADY_TRUSTED; + // const int32_t DEVICEMANAGER_GET_TRUSTED_DEVICE_FAILED; + // const int32_t DEVICEMANAGER_ALREADY_INIT; + // const int32_t DEVICEMANAGER_INIT_FAILED; + // const int32_t DEVICEMANAGER_MALLOC_ERROR; + // const int32_t DEVICEMANAGER_LOCK_ERROR; + // const int32_t DEVICEMANAGER_INVALID_PARAM; + // const int32_t DEVICEMANAGER_INVALID_VALUE; + // const int32_t DEVICEMANAGER_COPY_FAILED; + // const int32_t DEVICEMANAGER_NULLPTR; + // const int32_t DEVICEMANAGER_DISCOVERY_FAILED; + // const int32_t DEVICEMANAGER_FLATTEN_OBJECT; + // const int32_t DEVICEMANAGER_WRITE_FAILED; + // const int32_t DEVICEMANAGER_IPC_FAILED; + // const int32_t DEVICEMANAGER_IPC_TRANSACTION_FAILED; + // const int32_t DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; + // const int32_t HICHAIN_GROUP_CREATE_FAILED; + // const int32_t HICHAIN_MEMBER_ADD_FAILED; + // const int32_t HICHAIN_CREATE_CHANNEL_FAILED; + // const int32_t MSG_DECODE_PARA_FAILED; + // const int32_t ENCRYPT_UTILS_INVALID_PARAM; + // const int32_t ENCRYPT_UTILS_GCM_SETKEY_FAILED; + // const int32_t ENCRYPT_UTILS_GCM_CRYPT_FAILED; + // const int32_t ENCRYPT_UTILS_GCM_AUTH_DECRYPT_FAILED; + // const int32_t ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; + // const int32_t ENCRYPT_UTILS_AES_GCM_DECRYPT_FAILED; + // const int32_t ERR_GEN_RANDOM_PINTOKEN_FAILED; + // const int32_t PIN_CODE_CHECK_FAILED; + // const int32_t PIN_TOKEN_CHECK_FAILED; + // const int32_t DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; + // const int32_t DEVICEMANAGER_OPEN_SESSION_FAILED; + // const int32_t AUTH_PARA_INVALID; + // const int32_t ENCODE_DATA_ERROR; + // const int32_t DEVICEMANAGER_OK = 0; + + + // 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; + // 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; + // 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 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 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 GROUP_VISIBILITY_PUBLIC = -1; - const int32_t BUSINESS_FA_MIRGRATION = 0; - const int32_t BUSINESS_RESOURCE_ACCESS = 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; + // const int32_t BASE64_BYTE_LEN_3 = 3; + // const int32_t BASE64_BYTE_LEN_4 = 4; } } #endif diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 94f436df1..e9a8782c4 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -34,9 +34,10 @@ if (defined(ohos_lite)) { "include/ipc", "include/ipc/lite", "${common_path}/include", + "${common_path}/include/constants", + "${common_path}/include/utils", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include/utils", # "${innerkits_path}/native_cpp/include", # "${innerkits_path}/native_cpp/include/ipc/lite", ] @@ -114,9 +115,10 @@ if (defined(ohos_lite)) { "include/dependency/softbus", "include/ipc/standard", "${common_path}/include", + "${common_path}/include/constants", + "${common_path}/include/utils", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include/ipc/standard", "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/ipc/standard", "//base/security/deviceauth/interfaces/innerkits", diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index db1f5cc77..f1c93df8d 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -28,51 +28,53 @@ namespace OHOS { namespace DistributedHardware { -class PublishServiceCallBack { +class SoftbusConnector { public: static void OnPublishSuccess(int32_t publishId); static void OnPublishFail(int32_t publishId, PublishFailReason reason); -}; - -class SoftbusConnector { -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); +public: + SoftbusConnector(); + ~SoftbusConnector(); + int32_t Init(); + int32_t RegisterSoftbusStateCallback(); + int32_t RegisterSoftbusDiscoveryCallback(); + int32_t GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum); + int32_t GetLocalDeviceInfo(const std::string &pkgName, NodeBasicInfo *info); + int32_t StartDiscovery(const std::string &pkgName, SubscribeInfo *info); + int32_t StopDiscovery(const std::string &pkgName, uint16_t subscribeId); + bool IsDeviceOnLine(const std::string &deviceId); + int32_t GetConnectionIpAddr(const std::string &deviceId, std::string &ipAddr); + ConnectionAddr *GetConnectAddr(const std::string &deviceId); + 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); + bool GetSubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId); + bool GetPkgNameBySubscribeId(int32_t adapterId, std::string &pkgName); + void SaveDiscoveryDeviceInfo(const DeviceInfo *deviceInfo); + void RemoveDiscoveryDeviceInfo(const std::string deviceId); + void NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo); + void DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo); + 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_; + std::map>> subscribeInfos_; + std::map> discoveryDeviceInfoMap_; + std::vector> discoveryDeviceInfoVector_; + uint16_t subscribeIdPrefix_; + std::mutex lock_; + INodeStateCb softbusNodeStateCb_; + IDiscoveryCallback softbusDiscoveryCallback_; + IPublishCallback softbusPublishCallback_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_SOFTBUS_ADAPTER_H +#endif // OHOS_DM_SOFTBUS_CONNECTOR_H diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 42b868a9a..03020c907 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -25,14 +25,14 @@ namespace OHOS { namespace DistributedHardware { class SoftbusSession { - +public: + static int32_t OnSessionOpened(int32_t sessionId, int32_t result); + static int32_t OnSessionClosed(int32_t sessionId); + static int32_t OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); public: SoftbusSession(); ~SoftbusSession(); void Init(); - // 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); int32_t OpenAuthSession(const char *deviceId); int32_t RegisterSessionCallback(ISoftbusSessionCallback callback); int32_t UnRegisterSessionCallback(); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index dcf471e1b..cebbc7811 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -20,7 +20,8 @@ #include #include -#include "dm_error_code.h" +#include "softbus_bus_center.h" + #include "dm_log.h" #include "dm_anonymous.h" #include "dm_constants.h" @@ -28,8 +29,24 @@ namespace OHOS { namespace DistributedHardware { -SoftbusConnector::SoftbusConnector() { +SoftbusConnector::SoftbusConnector() : subscribeInfos_(), discoveryDeviceInfoMap_(), discoveryDeviceInfoVector_() +{ DMLOG(DM_LOG_INFO,"SoftbusConnector constructor"); + softbusPublishCallback_ = = { + .OnPublishSuccess = SoftbusConnector::OnPublishSuccess, + .OnPublishFail = SoftbusConnector::OnPublishFail + }; + softbusDiscoveryCallback_ = { + .OnDeviceFound = SoftbusConnector::OnSoftbusDeviceFound, + .OnDiscoverFailed = SoftbusConnector::OnSoftbusDiscoverFailed, + .OnDiscoverySuccess = SoftbusConnector::OnSoftbusDiscoverySuccess + }; + softbusNodeStateCb_ = { + .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED, + .onNodeOnline = SoftbusConnector::OnSoftBusDeviceOnline, + .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, + .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged + }; Init(); } @@ -39,17 +56,17 @@ SoftbusConnector::~SoftbusConnector() { SoftbusConnector::Init() { - //TODO:optimize implementation later + //TODO:optimize implementation later use semaphore instead int32_t ret; int32_t retryTimes = 0; do { - ret = RegNodeDeviceStateCb(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &softbusNodeStateCb_); - if (ret != DEVICEMANAGER_OK) { + ret = RegNodeDeviceStateCb(DM_PKG_NAME.c_str(), &softbusNodeStateCb_); + if (ret != DM_OK) { ++retryTimes; DMLOG(DM_LOG_ERROR, "RegNodeDeviceStateCb failed with ret %d, retryTimes %d", ret, retryTimes); - usleep(CHECK_INTERVAL); + usleep(SOFTBUS_CHECK_INTERVAL); } - } while (ret != DEVICEMANAGER_OK); + } while (ret != DM_OK); DMLOG(DM_LOG_INFO, "RegNodeDeviceStateCb success."); //TODO:check system properties first PublishInfo dmPublishInfo; @@ -60,7 +77,7 @@ SoftbusConnector::Init() dmPublishInfo.capability = DM_CAPABILITY_OSD; dmPublishInfo.capabilityData = nullptr; dmPublishInfo.dataLen = 0; - ret = PublishService(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &dmPublishInfo, &servicePublishCallback_); + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &servicePublishCallback_); DMLOG(DM_LOG_INFO, "service publish result is : %d", ret); return ret; } @@ -68,13 +85,25 @@ SoftbusConnector::Init() int32_t SoftbusConnector::GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum) { DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices start, pkgName: %s", pkgName.c_str()); - int32_t ret = GetAllNodeDeviceInfo(DEVICE_MANAGER_PACKAGE_NAME.c_str(), info, infoNum); + int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), info, infoNum); if (ret != 0) { DMLOG(DM_LOG_ERROR, "GetAllNodeDeviceInfo failed with ret %d", ret); return ret; } DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices success, pkgName: %s, deviceCount %d", pkgName.c_str(), *infoNum); - return DEVICEMANAGER_OK; + return DM_OK; +} + +int32_t SoftbusConnector::GetLocalDeviceInfo(const std::string &pkgName, NodeBasicInfo *info) +{ + DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo start, pkgName: %s", pkgName.c_str()); + int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), info); + if (ret != 0) { + DMLOG(DM_LOG_ERROR, "GetLocalNodeDeviceInfo failed with ret %d", ret); + return ret; + } + DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo success, pkgName: %s", pkgName.c_str()); + return DM_OK; } int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, SubscribeInfo *info) @@ -87,7 +116,7 @@ int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, SubscribeIn auto iter = subscribeInfos_.find(pkgName); std::vector> &subinfoVector = iter->second; auto vectorIter = subinfoVector.begin(); - for (; vectorIter != subinfoVector.end(); ++vectorIter) { + for (; vectorIter != subinfoVector.end(); ++ vectorIter) { if (vectorIter->get()->subscribeIdOrigin == info->subscribeId) { subinfo = *vectorIter; break; @@ -107,10 +136,10 @@ int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, SubscribeIn if (vectorIter == subinfoVector.end()) { subinfoVector.push_back(subinfo); } - DMLOG(DM_LOG_INFO, "StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", + DMLOG(DM_LOG_DEBUG, "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_); + DMLOG(DM_LOG_DEBUG, "Capability: %s", subinfo->info.capability); + int32_t ret = ::StartDiscovery(DM_PKG_NAME.c_str(), &subinfo->info, &softbusDiscoveryCallback_); if (ret != 0) { DMLOG(DM_LOG_ERROR, "StartDiscovery failed with ret %d.", ret); return DEVICEMANAGER_DISCOVERY_FAILED; @@ -128,7 +157,7 @@ int32_t SoftbusConnector::StopDiscovery(std::string &pkgName, uint16_t subscribe 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); + int32_t ret = ::StopDiscovery(DM_PKG_NAME.c_str(), subscribeIdAdapter); if (ret != 0) { DMLOG(DM_LOG_ERROR, "StopDiscovery failed with ret %d", ret); return ret; @@ -157,7 +186,7 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) NodeBasicInfo *info = nullptr; int32_t infoNum = 0; - if (GetTrustDevices(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &info, &infoNum) != DEVICEMANAGER_OK) { + if (GetTrustDevices(DM_PKG_NAME.c_str(), &info, &infoNum) != DEVICEMANAGER_OK) { DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine DM_GetSoftbusTrustDevices failed"); return false; } @@ -176,7 +205,7 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) break; } uint8_t udid[UDID_BUF_LEN] = {0}; - int32_t ret = GetNodeKeyInfo(DEVICE_MANAGER_PACKAGE_NAME.c_str(), networkId.c_str(), + int32_t ret = GetNodeKeyInfo(DM_PKG_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"); @@ -305,9 +334,108 @@ void SoftbusConnector::DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, cons dmDeviceInfo.deviceTypeId = (DMDeviceType)deviceInfo.devType; } +void SoftbusConnector::OnPublishSuccess(int32_t publishId) +{ + DMLOG(DM_LOG_INFO, "SoftbusConnector::OnPublishSuccess, publishId: %d", publishId); +} + +void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason) +{ + DMLOG(DM_LOG_INFO, "SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason); +} + +void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) +{ + if (info == nullptr) { + DMLOG(DM_LOG_ERROR, "SoftbusConnector::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()); + RemoveDiscoveryDeviceInfo(deviceId); +} + +void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) +{ + if (info == nullptr) { + DMLOG(DM_LOG_ERROR, "SoftbusConnector::OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); + return; + } + DmDeviceInfo dmDeviceInfo; + NodeBasicInfoCopyToDmDevice(dmDeviceInfo, *info); + // IpcServerListenerAdapter::GetInstance().OnDeviceStateChange(DmDeviceState::DEVICE_STATE_OFFLINE, dmDeviceInfo); +} + +void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) +{ + DMLOG(DM_LOG_INFO, "SoftbusConnector::OnSoftbusDeviceInfoChanged."); + //TODO: +} + +void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) +{ + if (device == nullptr) { + DMLOG(DM_LOG_ERROR, "deviceinfo is null"); + return; + } + std::string deviceId = device->devId; + DMLOG(DM_LOG_INFO, "SoftbusConnector::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); + } + } +} +void SoftbusConnector::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, "SoftbusConnector::OnSoftbusDiscoverFailed: pkgName not found"); + return; + } + uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); + // IpcServerListenerAdapter::GetInstance().OnDiscoverFailed(pkgName, originId, failReason); +} +void SoftbusConnector::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); +} } // 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 index c56d65375..4f92b0be7 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -20,24 +20,31 @@ namespace OHOS { namespace DistributedHardware { -SoftbusSession::SoftbusSession() +SoftbusSession::SoftbusSession() : sessionIdSet_(), messages_() { Init(); } SoftbusSession::~SoftbusSession() { - (void)RemoveSessionServer(PKG_NAME, SESSION_NAME); + (void)RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME); } void SoftbusSession::Init() { - int32_t ret = CreateSessionServer(PKG_NAME, SESSION_NAME, &iSessionListener); + ISessionListener sessionListener = { + .OnSessionOpened = SoftbusSession::OnSessionOpened, + .OnSessionClosed = SoftbusSession::OnSessionClosed, + .OnBytesReceived = SoftbusSession::OnBytesReceived, + .OnMessageReceived = nullptr, + .OnStreamReceived = nullptr + }; + int32_t ret = CreateSessionServer(DM_PKG_NAME, DM_SESSION_NAME, &sessionListener); if (ret != DEVICEMANAGER_OK) { DMLOG(DM_LOG_DEBUG, "CreateSessionServer failed"); return DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } int32_t SoftbusSession::OpenAuthSession(const char *deviceId) @@ -118,5 +125,69 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) // return ret; // } +int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) +{ + if (result != DM_OK) { + DMLOG(DM_LOG_INFO, "session open failed, sessionId %d", sessionId); + if (sessionIdSet_.count(sessionId) > 0) { + sessionIdSet_.erase(sessionId); + messages_.clear(); + } + return DM_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 DM_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; +} + } // 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 index cc7410052..9b0c3e732 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -31,7 +31,8 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co if (extra != nullptr && !extra.empty()) { adapterMgrPtr_ = std::make_shared(); } - //get trusted device list from softbus and copy to vector + + // softbusConnectorPtr->GetTru return SUCCESS; } -- Gitee From af1b3ffb7076ac452c15ec1aa3148f51dc902262 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Thu, 25 Nov 2021 10:48:45 +0800 Subject: [PATCH 005/110] =?UTF-8?q?=E6=B7=BB=E5=8A=A0ipc=E7=9A=84=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E8=A7=A3=E6=9E=90=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/ipc/lite/ipc_cmd_register.cpp | 68 +++++++++++++++++++ .../src/ipc/standard/ipc_cmd_register.cpp | 55 +++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp new file mode 100644 index 000000000..4fbab5a16 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_cmd_register.h" + +#include "device_manager_errno.h" +#include "device_manager_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) +{ + 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; + } + return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); +} + +int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + 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; + } + return (readResponseMapIter->second)(reply, pBaseRsp); +} + +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; + } + (onIpcCmdMapIter->second)(reply); + return DEVICEMANAGER_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; + } + (onIpcServerCmdMapIter->second)(req, reply); + return DEVICEMANAGER_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp new file mode 100644 index 000000000..e958dfd04 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp @@ -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. + */ + +#include "ipc_cmd_register.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); + +int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) +{ + 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; + } + return (setRequestMapIter->second)(pBaseReq, data); +} + +int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + 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; + } + return (readResponseMapIter->second)(reply, pBaseRsp); +} + +int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &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; + } + return (onIpcCmdMapIter->second)(data, reply); +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From f9558e26fe269e19df2e9bee521b5903df5c695f Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Thu, 25 Nov 2021 11:08:39 +0800 Subject: [PATCH 006/110] =?UTF-8?q?=E6=B7=BB=E5=8A=A0ipc=E7=9A=84=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E8=A7=A3=E6=9E=90=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/ipc/lite/ipc_cmd_register.h | 114 ++++++++++++++++++ .../include/ipc/standard/ipc_cmd_register.h | 94 +++++++++++++++ 2 files changed, 208 insertions(+) create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h b/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h new file mode 100644 index 000000000..0144df0d6 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_CMD_PARSER_H +#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H + +#include +#include +#include + +#include "liteipc_adapter.h" +#include "single_instance.h" + +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) + { + onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); + }; + 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_; + std::unordered_map onIpcCmdFuncMap_; + std::unordered_map onIpcServerCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h b/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h new file mode 100644 index 000000000..c2c5d585d --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H +#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H + +#include +#include +#include + +#include "iremote_broker.h" +#include "single_instance.h" + +#include "ipc_types.h" +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ + static int32_t IpcCmdProcess##cmdCode(paraA, paraB) + +using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); +using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); +using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); + +class IpcCmdRegister { +DECLARE_SINGLE_INSTANCE(IpcCmdRegister); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + int32_t SetRequest(int32_t cmdCode, 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_; + std::unordered_map onIpcCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file -- Gitee From 9e0f7c37dc4816f051ba98810e0c2d1ff1cc8c1f Mon Sep 17 00:00:00 2001 From: puhui Date: Thu, 25 Nov 2021 23:25:26 +0800 Subject: [PATCH 007/110] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/include/constants/dm_constants.h | 7 +- .../ipc/model/ipc_authenticate_device_req.h | 6 +- .../ipc/model/ipc_check_authenticate_req.h | 6 +- .../model/ipc_get_authenticationparam_rsp.h | 6 +- .../ipc/model/ipc_get_trustdevice_req.h | 6 +- .../ipc/model/ipc_get_trustdevice_rsp.h | 6 +- .../ipc/model/ipc_notify_auth_result_req.h | 6 +- .../model/ipc_notify_check_auth_result_req.h | 6 +- .../ipc/model/ipc_notify_device_found_req.h | 6 +- .../ipc/model/ipc_notify_device_state_req.h | 6 +- .../model/ipc_notify_discover_result_req.h | 6 +- .../ipc/model/ipc_notify_dmfa_result_req.h | 6 +- .../ipc/model/ipc_register_listener_req.h | 6 +- common/include/ipc/model/ipc_req.h | 6 +- common/include/ipc/model/ipc_rsp.h | 6 +- .../ipc/model/ipc_set_useroperation_req.h | 6 +- .../ipc/model/ipc_start_discovery_req.h | 6 +- .../ipc/model/ipc_stop_discovery_req.h | 6 +- common/include/single_instance.h | 6 +- common/include/utils/dm_anonymous.h | 6 +- common/include/utils/dm_log.h | 6 +- .../include/utils/dm_random.h | 34 +-- .../src/utils/dm_random.cpp | 39 ++- ext/profile/BUILD.gn | 69 ++++++ .../profile/include}/device_profile_adapter.h | 2 +- .../profile/src}/device_profile_adapter.cpp | 0 .../native_cpp/include/device_manager.h | 2 +- .../include/device_manager_callback.h | 6 +- .../native_cpp/include/device_manager_impl.h | 6 +- .../native_cpp/include/dm_app_image_info.h | 6 +- .../native_cpp/include/dm_device_info.h | 6 +- .../native_cpp/include/dm_subscribe_info.h | 6 +- .../native_cpp/include/ipc/ipc_client.h | 6 +- .../native_cpp/include/ipc/ipc_client_proxy.h | 6 +- .../include/ipc/lite/ipc_client_manager.h | 6 +- .../ipc/lite/ipc_client_server_proxy.h | 6 +- .../include/ipc/lite/ipc_client_stub.h | 6 +- .../include/ipc/standard/ipc_client_manager.h | 6 +- .../ipc/standard/ipc_client_server_proxy.h | 6 +- .../include/ipc/standard/ipc_client_stub.h | 6 +- .../include/ipc/standard/ipc_remote_broker.h | 6 +- .../include/notify/device_manager_notify.h | 6 +- interfaces/kits/js/include/dm_native_event.h | 6 +- .../kits/js/include/native_devicemanager_js.h | 6 +- .../include/adapter/dm_adapter_manager.h | 17 +- .../dependency/hichain/hichain_connector.h | 36 +-- .../dependency/softbus/softbus_connector.h | 45 ++-- .../softbus/softbus_discovery_callback.h | 8 +- .../dependency/softbus/softbus_session.h | 7 +- .../softbus/softbus_session_callback.h | 4 +- .../softbus/softbus_state_callback.h | 8 +- ...anager_impl.h => device_manager_service.h} | 16 +- ...er.h => device_manager_service_listener.h} | 12 +- .../include/discovery/dm_discovery_manager.h | 3 + .../include/ipc/lite/ipc_cmd_register.h | 114 +++++++++ .../include/ipc/lite/ipc_server_listener.h | 6 +- .../include/ipc/lite/ipc_server_listenermgr.h | 6 +- .../include/ipc/lite/ipc_server_stub.h | 6 +- .../include/ipc/standard/ipc_cmd_register.h | 94 +++++++ .../ipc/standard/ipc_server_client_proxy.h | 6 +- .../ipc/standard/ipc_server_listener.h | 6 +- .../include/ipc/standard/ipc_server_stub.h | 6 +- .../dependency/hichain/hichain_connector.cpp | 200 ++++++++------- .../dependency/softbus/softbus_connector.cpp | 230 +++++++++++------- .../dependency/softbus/softbus_session.cpp | 26 +- ...er_impl.cpp => device_manager_service.cpp} | 63 +++-- ...pp => device_manager_service_listener.cpp} | 27 +- .../src/deviceinfo/dm_device_info_manager.cpp | 29 ++- .../devicestate/dm_device_state_manager.cpp | 2 +- .../src/discovery/dm_discovery_manager.cpp | 7 +- .../src/ipc/ipc_server_adapter.cpp | 198 --------------- .../src/ipc/lite/ipc_cmd_parser.cpp | 43 ++-- .../src/ipc/lite/ipc_cmd_register.cpp | 68 ++++++ .../src/ipc/lite/ipc_server_listener.cpp | 18 +- .../src/ipc/lite/ipc_server_listenermgr.cpp | 6 +- .../src/ipc/lite/ipc_server_main.cpp | 4 +- .../src/ipc/lite/ipc_server_stub.cpp | 12 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 58 ++--- .../src/ipc/standard/ipc_cmd_register.cpp | 55 +++++ .../ipc/standard/ipc_server_client_proxy.cpp | 4 +- .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 19 +- test/unittest/device_manager_impl_test.cpp | 12 +- test/unittest/device_manager_impl_test.h | 6 +- 84 files changed, 1046 insertions(+), 818 deletions(-) rename services/devicemanagerservice/include/ipc/ipc_server_adapter.h => common/include/utils/dm_random.h (37%) rename services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h => common/src/utils/dm_random.cpp (40%) create mode 100644 ext/profile/BUILD.gn rename {services/devicemanagerservice/include/adapter/profile => ext/profile/include}/device_profile_adapter.h (94%) rename {services/devicemanagerservice/src/adapter/profile => ext/profile/src}/device_profile_adapter.cpp (100%) rename services/devicemanagerservice/include/{device_manager_impl.h => device_manager_service.h} (86%) rename services/devicemanagerservice/include/{device_manager_listener.h => device_manager_service_listener.h} (83%) create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h rename services/devicemanagerservice/src/{device_manager_impl.cpp => device_manager_service.cpp} (62%) rename services/devicemanagerservice/src/{ipc/ipc_server_listener_adapter.cpp => device_manager_service_listener.cpp} (81%) delete mode 100644 services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index 12ee9cbab..e5adf3a26 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_CONSTANTS_H -#define OHOS_DEVICE_MANAGER_CONSTANTS_H +#ifndef OHOS_DM_CONSTANTS_H +#define OHOS_DM_CONSTANTS_H #include #include @@ -37,6 +37,9 @@ namespace DistributedHardware { DM_INPUT_PARA_INVALID, DM_SERVICE_NOT_READY, DM_DEVICE_ALREADY_TRUSTED, + DM_HICHAIN_GROUP_CREATE_FAILED, + DM_HICHAIN_MEMBER_ADD_FAILED, + DM_HICHAIN_CREATE_CHANNEL_FAILED DM_OK = 0; }; diff --git a/common/include/ipc/model/ipc_authenticate_device_req.h b/common/include/ipc/model/ipc_authenticate_device_req.h index f4f066b3f..47ef2ca0f 100644 --- a/common/include/ipc/model/ipc_authenticate_device_req.h +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_AUTHENTICATE_DEVICE_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_AUTHENTICATE_DEVICE_REQ_H +#ifndef OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H +#define OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H #include "ipc_req.h" @@ -62,4 +62,4 @@ private: }; } // 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 index ea136b421..ef2bd1031 100644 --- a/common/include/ipc/model/ipc_check_authenticate_req.h +++ b/common/include/ipc/model/ipc_check_authenticate_req.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H +#ifndef OHOS_DM_IPC_CHECK_AUTHENTICATE_REQ_H +#define OHOS_DM_IPC_CHECK_AUTHENTICATE_REQ_H #include "ipc_req.h" @@ -37,4 +37,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H +#endif // OHOS_DM_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 index b12c39f68..b2dd00214 100644 --- a/common/include/ipc/model/ipc_get_authenticationparam_rsp.h +++ b/common/include/ipc/model/ipc_get_authenticationparam_rsp.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_GET_AUTH_PARAM_RSP_H -#define OHOS_DEVICE_MANAGER_IPC_GET_AUTH_PARAM_RSP_H +#ifndef OHOS_DM_IPC_GET_AUTH_PARAM_RSP_H +#define OHOS_DM_IPC_GET_AUTH_PARAM_RSP_H #include "ipc_rsp.h" #include "dm_device_info.h" @@ -38,4 +38,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_GET_AUTH_PARAM_RSP_H \ No newline at end of file +#endif // OHOS_DM_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..442d1e12b 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_req.h +++ b/common/include/ipc/model/ipc_get_trustdevice_req.h @@ -13,8 +13,8 @@ * 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" @@ -37,4 +37,4 @@ private: }; } // 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..b42e592b5 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_rsp.h +++ b/common/include/ipc/model/ipc_get_trustdevice_rsp.h @@ -13,8 +13,8 @@ * 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_TRUSTDEVICE_RSP_H +#define OHOS_DM_IPC_GET_TRUSTDEVICE_RSP_H #include @@ -41,4 +41,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_GET_TRUSTDEVICE_RSP_H +#endif // OHOS_DM_IPC_GET_TRUSTDEVICE_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..d6d32cfad 100644 --- a/common/include/ipc/model/ipc_notify_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_auth_result_req.h @@ -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 @@ -72,4 +72,4 @@ private: }; } // 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 index 0e153d560..21a44eb6d 100644 --- a/common/include/ipc/model/ipc_notify_check_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_check_auth_result_req.h @@ -13,8 +13,8 @@ * 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 +#ifndef OHOS_DM_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H +#define OHOS_DM_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H #include @@ -61,4 +61,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H +#endif // OHOS_DM_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..75229b85c 100644 --- a/common/include/ipc/model/ipc_notify_device_found_req.h +++ b/common/include/ipc/model/ipc_notify_device_found_req.h @@ -13,8 +13,8 @@ * 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" @@ -50,4 +50,4 @@ private: }; } // 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..05e946f01 100644 --- a/common/include/ipc/model/ipc_notify_device_state_req.h +++ b/common/include/ipc/model/ipc_notify_device_state_req.h @@ -13,8 +13,8 @@ * 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" @@ -50,4 +50,4 @@ private: }; } // 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..708f4dddd 100644 --- a/common/include/ipc/model/ipc_notify_discover_result_req.h +++ b/common/include/ipc/model/ipc_notify_discover_result_req.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DISCOVER_RESULT_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_DISCOVER_RESULT_REQ_H +#ifndef OHOS_DM_IPC_NOTIFY_DISCOVER_RESULT_REQ_H +#define OHOS_DM_IPC_NOTIFY_DISCOVER_RESULT_REQ_H #include @@ -50,4 +50,4 @@ private: }; } // 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..741ba7e50 100644 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DMFA_RESULT_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_DMFA_RESULT_REQ_H +#ifndef OHOS_DM_IPC_NOTIFY_DMFA_RESULT_REQ_H +#define OHOS_DM_IPC_NOTIFY_DMFA_RESULT_REQ_H #include @@ -39,4 +39,4 @@ private: }; } // 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_register_listener_req.h b/common/include/ipc/model/ipc_register_listener_req.h index 67690a5b8..5b82a2fcc 100644 --- a/common/include/ipc/model/ipc_register_listener_req.h +++ b/common/include/ipc/model/ipc_register_listener_req.h @@ -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" @@ -59,4 +59,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..bed6b4950 100644 --- a/common/include/ipc/model/ipc_req.h +++ b/common/include/ipc/model/ipc_req.h @@ -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 @@ -39,4 +39,4 @@ private: }; } // 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..1af507684 100644 --- a/common/include/ipc/model/ipc_rsp.h +++ b/common/include/ipc/model/ipc_rsp.h @@ -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 @@ -39,4 +39,4 @@ private: }; } // 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..5f56e27bf 100644 --- a/common/include/ipc/model/ipc_set_useroperation_req.h +++ b/common/include/ipc/model/ipc_set_useroperation_req.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_GET_USER_OPERATION_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_GET_USER_OPERATION_REQ_H +#ifndef OHOS_DM_IPC_GET_USER_OPERATION_REQ_H +#define OHOS_DM_IPC_GET_USER_OPERATION_REQ_H #include "ipc_req.h" #include "dm_device_info.h" @@ -38,4 +38,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_GET_USER_OPERATION_REQ_H +#endif // OHOS_DM_IPC_GET_USER_OPERATION_REQ_H diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h index 341641e61..f77d5372a 100644 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ b/common/include/ipc/model/ipc_start_discovery_req.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_START_DISCOVERY_REQ_H -#define OHOS_DEVICE_MANAGER_IPC_START_DISCOVERY_REQ_H +#ifndef OHOS_DM_IPC_START_DISCOVERY_REQ_H +#define OHOS_DM_IPC_START_DISCOVERY_REQ_H #include "ipc_req.h" @@ -39,4 +39,4 @@ private: }; } // 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..2d53adc2b 100644 --- a/common/include/ipc/model/ipc_stop_discovery_req.h +++ b/common/include/ipc/model/ipc_stop_discovery_req.h @@ -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 @@ -39,4 +39,4 @@ private: }; } // 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..e2601b876 100644 --- a/common/include/single_instance.h +++ b/common/include/single_instance.h @@ -13,8 +13,8 @@ * 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 { @@ -43,4 +43,4 @@ className & className::GetInstance() \ }; // 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/common/include/utils/dm_anonymous.h b/common/include/utils/dm_anonymous.h index a31ad8a60..5ae9757df 100644 --- a/common/include/utils/dm_anonymous.h +++ b/common/include/utils/dm_anonymous.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_ANONYMOUS_H -#define OHOS_DEVICE_MANAGER_ANONYMOUS_H +#ifndef OHOS_DM_ANONYMOUS_H +#define OHOS_DM_ANONYMOUS_H #include namespace OHOS { @@ -24,4 +24,4 @@ std::string GetAnonyInt32(const int32_t value); } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_ANONYMOUS_H \ No newline at end of file +#endif // OHOS_DM_ANONYMOUS_H \ No newline at end of file diff --git a/common/include/utils/dm_log.h b/common/include/utils/dm_log.h index ba6a4b749..aade3ef58 100644 --- a/common/include/utils/dm_log.h +++ b/common/include/utils/dm_log.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_LOG_H -#define OHOS_DEVICE_MANAGER_LOG_H +#ifndef OHOS_DM_LOG_H +#define OHOS_DM_LOG_H #include @@ -35,4 +35,4 @@ void DMLog(DMLogLevel logLevel, const char *fmt, ...); } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LOG_H +#endif // OHOS_DM_LOG_H diff --git a/services/devicemanagerservice/include/ipc/ipc_server_adapter.h b/common/include/utils/dm_random.h similarity index 37% rename from services/devicemanagerservice/include/ipc/ipc_server_adapter.h rename to common/include/utils/dm_random.h index deec8bfee..835be8bc8 100644 --- a/services/devicemanagerservice/include/ipc/ipc_server_adapter.h +++ b/common/include/utils/dm_random.h @@ -13,38 +13,16 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H +#ifndef OHOS_DM_RANDOM_H +#define OHOS_DM_RANDOM_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); -}; +int32_t GenRandInt(int32_t randMin, int32_t randMax); +int64_t GenRandLongLong(int64_t randMin, int64_t randMax); } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H + +#endif // OHOS_DM_RANDOM_H diff --git a/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h b/common/src/utils/dm_random.cpp similarity index 40% rename from services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h rename to common/src/utils/dm_random.cpp index b812eca27..ede0904e2 100644 --- a/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h +++ b/common/src/utils/dm_random.cpp @@ -13,31 +13,28 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H +#include "dm_random.h" -#include "discovery_service.h" +#include -#include "ipc_server_listener.h" - -#include "single_instance.h" -#include "dm_device_info.h" +#include "dm_constants.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_; -}; +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); +} } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn new file mode 100644 index 000000000..0d4468cdd --- /dev/null +++ b/ext/profile/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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") + +shared_library("devicemanagerext") { + include_dirs = [ + "${common_path}/include", + "${services_path}/include/adapter/", + "crypto/include", + "ds/include", + ] + + include_dirs += [ + "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", + "//utils/native/lite/include", + "//utils/system/safwk/native/include", + "//third_party/json/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//foundation/communication/dsoftbus/interfaces/kits/discovery", + "//foundation/communication/dsoftbus/interfaces/kits/transport", + "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + ] + + sources = [ + # "src/anonymous_string.cpp", + # "src/ipc/lite/ipc_cmd_register.cpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerext\"", + "LOG_DOMAIN=0xD004100", + ] + + 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", + ] +} + diff --git a/services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h similarity index 94% rename from services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h rename to ext/profile/include/device_profile_adapter.h index f2ba658cd..3213e5689 100644 --- a/services/devicemanagerservice/include/adapter/profile/device_profile_adapter.h +++ b/ext/profile/include/device_profile_adapter.h @@ -20,7 +20,7 @@ namespace OHOS { namespace DistributedHardware { -class DeviceProfileAdapter : ProfileAdapter { +class DeviceProfileAdapter : IProfileAdapter { public: DeviceProfileAdapter(); diff --git a/services/devicemanagerservice/src/adapter/profile/device_profile_adapter.cpp b/ext/profile/src/device_profile_adapter.cpp similarity index 100% rename from services/devicemanagerservice/src/adapter/profile/device_profile_adapter.cpp rename to ext/profile/src/device_profile_adapter.cpp diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index cfea7f212..4ce780a5f 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -46,4 +46,4 @@ public: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_H +#endif // OHOS_DM_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 ff9f3d246..8c71697c3 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -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 @@ -59,4 +59,4 @@ public: }; } // 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 664b52f15..1b4e95d91 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IMPL_H -#define OHOS_DEVICE_MANAGER_IMPL_H +#ifndef OHOS_DM_IMPL_H +#define OHOS_DM_IMPL_H #include "device_manager.h" @@ -55,4 +55,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IMPL_H +#endif // OHOS_DM_IMPL_H 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..1a3e7256c 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 @@ -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 @@ -180,4 +180,4 @@ private: }; } // 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 4adc83e11..961d5eca7 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -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 @@ -56,4 +56,4 @@ typedef struct DmAuthParam { } 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..57eccdb88 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h @@ -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 @@ -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..661229f63 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h @@ -13,8 +13,8 @@ * 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 @@ -34,4 +34,4 @@ public: }; } // 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..8b05a7b70 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 @@ -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 @@ -38,4 +38,4 @@ private: }; } // 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..8144399cf 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 @@ -13,8 +13,8 @@ * 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 @@ -39,4 +39,4 @@ private: }; } // 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..1389af5ff 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 @@ -13,8 +13,8 @@ * 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 @@ -42,4 +42,4 @@ private: }; } // 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..5c019d6d5 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 @@ -13,8 +13,8 @@ * 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 @@ -40,4 +40,4 @@ private: }; } // 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..e2ea1cc26 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 @@ -13,8 +13,8 @@ * 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 @@ -55,4 +55,4 @@ private: }; } // 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..154994b83 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 @@ -13,8 +13,8 @@ * 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 @@ -36,4 +36,4 @@ private: }; } // 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..f1d1e7407 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 @@ -13,8 +13,8 @@ * 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 @@ -37,4 +37,4 @@ public: }; } // 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..1d2eda69f 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 @@ -13,8 +13,8 @@ * 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 @@ -35,4 +35,4 @@ public: }; } // 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..45c779ab2 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 @@ -13,8 +13,8 @@ * 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 @@ -72,4 +72,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_NOTIFY_H +#endif // OHOS_DM_NOTIFY_H diff --git a/interfaces/kits/js/include/dm_native_event.h b/interfaces/kits/js/include/dm_native_event.h index 6a3858bdd..d551fbac8 100644 --- a/interfaces/kits/js/include/dm_native_event.h +++ b/interfaces/kits/js/include/dm_native_event.h @@ -13,8 +13,8 @@ * 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 @@ -41,4 +41,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..554418cf5 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -13,8 +13,8 @@ * 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 @@ -196,4 +196,4 @@ private: static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; }; -#endif // OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H +#endif // OHOS_DM_NATIVE_DEVICEMANAGER_JS_H diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index 7edae2856..4624478eb 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -16,20 +16,23 @@ #ifndef OHOS_DM_ADAPTER_MANAGER_H #define OHOS_DM_ADAPTER_MANAGER_H +#include "decision_adapter.h" +#include "profile_adapter.h" +#include "crypto_adapter.h" + namespace OHOS { namespace DistributedHardware { class DmAdapterManager { public: DmAdapterManager(); - std::shared_ptr GetDecisionAdapter(); - std::shared_ptr GetProfileAdapter(); - std::shared_ptr GetCryptoAdapter(); - + std::shared_ptr GetDecisionAdapter(); + std::shared_ptr GetProfileAdapter(); + std::shared_ptr GetCryptoAdapter(); private: - std::shared_ptr decisionAdapterPtr_; - std::shared_ptr profileAdapterPtr_; - std::shared_ptr cryptoAdapterPtr_; + std::shared_ptr decisionAdapterPtr_; + std::shared_ptr profileAdapterPtr_; + std::shared_ptr cryptoAdapterPtr_; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 83bef0943..0a1b9d811 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -21,19 +21,11 @@ #include #include "nlohmann/json.hpp" - #include "device_auth.h" - #include "single_instance.h" namespace OHOS { namespace DistributedHardware { -// enum { -// HICHAIN_SUCCESS = 0, -// GROUP_CREATE_FAILED = 1, -// MEMBER_ADD_FAILED = 2, -// CREATE_CHANNEL_FAILED = 3, -// }; //move to constant or error code struct GroupInfo { std::string groupName; @@ -47,43 +39,33 @@ struct GroupInfo { void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo); - -class HichainAuthenCallBack { +class HiChainConnector { 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 { public: HiChainConnector(); ~HiChainConnector(); - void Init(); - bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - int64_t GenRequestId(); - void RegisterHiChainCallback(std::shared_ptr callback); + void RegisterHiChainCallback(const string &pkgName, const IHiChainConnectorCallback &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: + int64_t GenRequestId(); + void GetRelatedGroups(std::string DeviceId, std::vector &groupList); + 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::shared_ptr msgResponseAuth); + int32_t IsGroupCreated(std::string groupName, GroupInfo &groupInfo); bool IsGroupInfoInvalid(GroupInfo &group); - private: const DeviceGroupManager *deviceGroupManager_ = nullptr; DeviceAuthCallback deviceAuthCallback_ ; + std::map hichainConnectorCallback_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index f1c93df8d..fddf3a3bf 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -41,36 +41,37 @@ public: public: SoftbusConnector(); ~SoftbusConnector(); - int32_t Init(); - int32_t RegisterSoftbusStateCallback(); - int32_t RegisterSoftbusDiscoveryCallback(); - int32_t GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum); - int32_t GetLocalDeviceInfo(const std::string &pkgName, NodeBasicInfo *info); - int32_t StartDiscovery(const std::string &pkgName, SubscribeInfo *info); + int32_t RegisterSoftbusStateCallback(const string &pkgName, const ISoftbusStateCallback &callback); + int32_t UnRegisterSoftbusStateCallback(const string &pkgName); + int32_t RegisterSoftbusDiscoveryCallback(const string &pkgName, const ISoftbusDiscoveryCallback &callback); + int32_t UnRegisterSoftbusDiscoveryCallback(const string &pkgName); + int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector deviceList); + int32_t GetLocalDeviceInfo(DmDeviceInfo &info); + int32_t StartDiscovery(const std::string &pkgName, const DmSubscribeInfo &info); int32_t StopDiscovery(const std::string &pkgName, uint16_t subscribeId); bool IsDeviceOnLine(const std::string &deviceId); int32_t GetConnectionIpAddr(const std::string &deviceId, std::string &ipAddr); - ConnectionAddr *GetConnectAddr(const std::string &deviceId); - private: - bool GetSubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId); - bool GetPkgNameBySubscribeId(int32_t adapterId, std::string &pkgName); - void SaveDiscoveryDeviceInfo(const DeviceInfo *deviceInfo); - void RemoveDiscoveryDeviceInfo(const std::string deviceId); + int32_t Init(); + ConnectionAddr *GetConnectAddr(const std::string &deviceId); + // bool GetSubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId); + // bool GetPkgNameBySubscribeId(int32_t adapterId, std::string &pkgName); + // void SaveDiscoveryDeviceInfo(const DeviceInfo *deviceInfo); + // void RemoveDiscoveryDeviceInfo(const std::string deviceId); void NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo); void DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo); ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); private: - struct SubscribeInfoAdapter { - SubscribeInfo info; - uint16_t subscribeIdOrigin; - uint16_t subscribeIdPrefix; - }; - std::map>> subscribeInfos_; - std::map> discoveryDeviceInfoMap_; - std::vector> discoveryDeviceInfoVector_; - uint16_t subscribeIdPrefix_; - std::mutex lock_; + // struct SubscribeInfoAdapter { + // SubscribeInfo info; + // uint16_t subscribeIdOrigin; + // uint16_t subscribeIdPrefix; + // }; + // std::map>> subscribeInfos_; + // std::map> discoveryDeviceInfoMap_; + // std::vector> discoveryDeviceInfoVector_; + // uint16_t subscribeIdPrefix_; + // std::mutex lock_; INodeStateCb softbusNodeStateCb_; IDiscoveryCallback softbusDiscoveryCallback_; IPublishCallback softbusPublishCallback_; diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h index f3b76c9ae..512cef99d 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h @@ -19,11 +19,11 @@ namespace OHOS { namespace DistributedHardware { -class ISoftbusStateCallback { +class ISoftbusDiscoveryCallback { public: - virtual int32_t OnDeviceFound(); - virtual int32_t OnDeviceLost(); - virtual int32_t OnDiscoveryFailed(); + virtual int32_t OnDeviceFound(uint16_t sbuscribeId, const DmDeviceInfo &info); + virtual int32_t OnDiscoverySuccess(int32_t subscribeId); + virtual int32_t OnDiscoveryFailed(uint16_t subscribeId, const std::string &failedReason); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 03020c907..8117ab72f 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -32,10 +32,9 @@ public: public: SoftbusSession(); ~SoftbusSession(); - void Init(); + int32_t RegisterSessionCallback(const string &pkgName, ISoftbusSessionCallback callback); + int32_t UnRegisterSessionCallback(const string& pkgName); int32_t OpenAuthSession(const char *deviceId); - int32_t RegisterSessionCallback(ISoftbusSessionCallback callback); - int32_t UnRegisterSessionCallback(); void CloseAuthSession(int32_t sessionId); // int32_t SendMessages(const char *deviceId, std::vector &messages); int32_t SendData(int32_t sessionId, std::string &message); @@ -48,4 +47,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H +#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 index 5a964f48f..7c8ecf49d 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h @@ -21,8 +21,8 @@ namespace OHOS { namespace DistributedHardware { class ISoftbusSessionCallback { public: - virtual int32_t OnSessionOpened(); - virtual int32_t OnSessionClosed(); + virtual int32_t OnSessionOpened(int32_t sessionId, int32_t result); + virtual int32_t OnSessionClosed(int32_t sessionId); virtual int32_t OnDataReceived(); }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h index dd06e702f..a393742ec 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h @@ -21,10 +21,10 @@ namespace OHOS { namespace DistributedHardware { class ISoftbusStateCallback { public: - virtual int32_t OnDeviceOnline(); - virtual int32_t OnDeviceOfflie(); - virtual int32_t OnDeviceChanged(); - virtual int32_t OnDeviceReady(); + virtual int32_t OnDeviceOnline(const DmDeviceInfo &info); + virtual int32_t OnDeviceOfflie(const DmDeviceInfo &info); + virtual int32_t OnDeviceChanged(const DmDeviceInfo &info); + virtual int32_t OnDeviceReady(const DmDeviceInfo &info); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/device_manager_impl.h b/services/devicemanagerservice/include/device_manager_service.h similarity index 86% rename from services/devicemanagerservice/include/device_manager_impl.h rename to services/devicemanagerservice/include/device_manager_service.h index 824b00695..f839326ae 100644 --- a/services/devicemanagerservice/include/device_manager_impl.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IMPL_H -#define OHOS_DEVICE_MANAGER_IMPL_H +#ifndef OHOS_DM_SERVICE_H +#define OHOS_DM_SERVICE_H #include #include @@ -30,9 +30,10 @@ namespace OHOS { namespace DistributedHardware { -class DeviceManagerImpl { - DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); +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 StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra); @@ -41,14 +42,15 @@ public: int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam); private: - DeviceManagerImpl(); - virtual ~DeviceManagerImpl() = default; + DeviceManagerService(); + virtual ~DeviceManagerService() = default; std::shared_ptr authMgrPtr_; std::shared_ptr deviceInfoMgrPtr_; std::shared_ptr deviceStateMgrPtr_; std::shared_ptr discoveryMgrPtr_; std::shared_ptr softbusConnectorPtr_; + std::shared_ptr listenerPtr_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IMPL_H +#endif // OHOS_DM_SERVICE_H diff --git a/services/devicemanagerservice/include/device_manager_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h similarity index 83% rename from services/devicemanagerservice/include/device_manager_listener.h rename to services/devicemanagerservice/include/device_manager_service_listener.h index 5501c66d5..d31017962 100644 --- a/services/devicemanagerservice/include/device_manager_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_LISTENER_H -#define OHOS_DEVICE_MANAGER_LISTENER_H +#ifndef OHOS_DM_SERVICE_LISTENER_H +#define OHOS_DM_SERVICE_LISTENER_H #include @@ -22,17 +22,15 @@ namespace OHOS { namespace DistributedHardware { -class DeviceManagerListener { +class DeviceManagerServiceListener { public: - DeviceManagerListener(); - ~DeviceManagerListener(); int32_t OnDeviceOnline(const DmDeviceInfo &info); int32_t OnDeviceOffline(const DmDeviceInfo &info); int32_t OnDeviceReady(const DmDeviceInfo &info); int32_t OnDeviceStateChange(const DmDeviceInfo &info); int32_t OnDeviceFound(uint16_t sbuscribeId, const DmDeviceInfo &info); - int32_t OnDeviceLost(uint16_t subscribeId, const DmDeviceInfo &info); int32_t OnDiscoveryFailed(uint16_t subscribeId, const std::string &failedReason); + int32_t OnDiscoverySuccess(int32_t subscribeId); int32_t OnAuthenticateResult(const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason); int32_t OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string &flag); private: @@ -40,4 +38,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LISTENER_H +#endif // OHOS_DM_SERVICE_LISTENER_H diff --git a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h index 371c914bc..2215e1b0d 100644 --- a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h @@ -32,6 +32,9 @@ public: private: std::shared_ptr softbusConnectorPtr_; std::shared_ptr listenerPtr_; + //TODO:discovery queue used to prevent re enty and stop discovery automatically when timeout + //also used to record the pkg which was being discovered + std::queue discoveryQueue_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h b/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h new file mode 100644 index 000000000..615e07b91 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_CMD_PARSER_H +#define OHOS_DM_IPC_CMD_PARSER_H + +#include +#include +#include + +#include "liteipc_adapter.h" +#include "single_instance.h" + +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) + { + onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); + }; + 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_; + std::unordered_map onIpcCmdFuncMap_; + std::unordered_map onIpcServerCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h index 9503191aa..840a4c0f6 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H +#ifndef OHOS_DM_IPC_SERVER_LISTENER_H +#define OHOS_DM_IPC_SERVER_LISTENER_H #include @@ -38,4 +38,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H +#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 index 26d2ee114..0dfc26074 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H +#ifndef OHOS_DM_IPC_SERVER_LISTENER_MGR_H +#define OHOS_DM_IPC_SERVER_LISTENER_MGR_H #include #include @@ -47,4 +47,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H +#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 index 9baa73d4a..d6ac9d1e7 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H +#ifndef OHOS_DM_IPC_SERVER_STUB_H +#define OHOS_DM_IPC_SERVER_STUB_H #include @@ -23,4 +23,4 @@ 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 +#endif // OHOS_DM_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h b/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h new file mode 100644 index 000000000..ce3123d25 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_CMD_PARSER_H +#define OHOS_DM_IPC_CMD_PARSER_H + +#include +#include +#include + +#include "iremote_broker.h" +#include "single_instance.h" + +#include "ipc_types.h" +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ + static int32_t IpcCmdProcess##cmdCode(paraA, paraB) + +using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); +using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); +using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); + +class IpcCmdRegister { +DECLARE_SINGLE_INSTANCE(IpcCmdRegister); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + int32_t SetRequest(int32_t cmdCode, 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_; + std::unordered_map onIpcCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h index 15b5e44a4..5349c7739 100644 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H +#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" @@ -32,4 +32,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H +#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 index 3737b7cde..ac7d4ca4a 100644 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H +#ifndef OHOS_DM_IPC_SERVER_LISTENER_H +#define OHOS_DM_IPC_SERVER_LISTENER_H #include @@ -33,4 +33,4 @@ public: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H +#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 index 4e653eb97..b2abdb4f5 100644 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H -#define OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H +#ifndef OHOS_DM_IPC_SERVER_STUB_H +#define OHOS_DM_IPC_SERVER_STUB_H #include #include @@ -73,4 +73,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H +#endif // OHOS_DM_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 536064802..c64b0b9ae 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -70,38 +70,34 @@ void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) HiChainConnector::HiChainConnector() { - Init(); -} - -HiChainConnector::~HiChainConnector() -{ - -} - -void HiChainConnector::Init() -{ - DMLOG(DM_LOG_INFO, "HiChainConnector::init, init device auth service."); + DMLOG(DM_LOG_INFO, "HiChainConnector::constructor"); + deviceAuthCallback_ = { + .onTransmit = nullptr, + .onFinish = HiChainConnector::onFinish, + .onError = HiChainConnector::onError, + .onRequest = HiChainConnector::onRequest + }; InitDeviceAuthService(); - deviceGroupManager_ = GetGmInstance(); if (deviceGroupManager_ == nullptr) { - DMLOG(DM_LOG_INFO, "HiChainConnector::init, failed to init group manager!"); + DMLOG(DM_LOG_INFO, "HiChainConnector::constructor, failed to init group manager!"); return; } - - 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; + DMLOG(DM_LOG_INFO, "HiChainConnector::constructor success."); } -int64_t HiChainConnector::GenRequestId() +HiChainConnector::~HiChainConnector() +{ + DMLOG(DM_LOG_INFO, "HiChainConnector::destructor."); + //TODO:delete resource +} + +HiChainConnector::RegisterHiChainCallback(const string &pkgName, const IHiChainConnectorCallback &callback) { - return EncryptUtils::GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); + if (hichainConnectorCallback.count(pkgName) == 0) { + hichainConnectorCallback[pkgName] = callback; + } } int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &groupName) @@ -133,7 +129,6 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou DMLOG(DM_LOG_ERROR, "Faild to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); return ret; } - return SUCCESS; } @@ -219,6 +214,82 @@ int32_t HiChainConnector::AddMemeber(std::string deviceId, std::shared_ptr callback) // { // HiChainConnectorCallback_ = callback; @@ -266,6 +337,10 @@ int32_t HiChainConnector::AddMemeber(std::string deviceId, std::shared_ptrOnMemberJoin(requestId, status); // } +int64_t HiChainConnector::GenRequestId() +{ + return GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); +} std::string HiChainConnector::GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth) @@ -410,82 +485,5 @@ void HiChainConnector::DeleteGroup(std::string &groupId) 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/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index cebbc7811..c9f69b823 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -32,7 +32,7 @@ namespace DistributedHardware { SoftbusConnector::SoftbusConnector() : subscribeInfos_(), discoveryDeviceInfoMap_(), discoveryDeviceInfoVector_() { DMLOG(DM_LOG_INFO,"SoftbusConnector constructor"); - softbusPublishCallback_ = = { + softbusPublishCallback_ = { .OnPublishSuccess = SoftbusConnector::OnPublishSuccess, .OnPublishFail = SoftbusConnector::OnPublishFail }; @@ -82,103 +82,147 @@ SoftbusConnector::Init() return ret; } -int32_t SoftbusConnector::GetTrustDevices(const std::string &pkgName, NodeBasicInfo **info, int32_t *infoNum) +int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceList) { - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices start, pkgName: %s", pkgName.c_str()); + DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices start"); + NodeBasicInfo *nodeInfo = nullptr; + *info = nullptr; + *infoNum = 0; int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), info, infoNum); if (ret != 0) { DMLOG(DM_LOG_ERROR, "GetAllNodeDeviceInfo failed with ret %d", ret); - return ret; + return DM_FAILED; + } + *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (*infoNum)); + if (*info == nullptr) { + FreeNodeInfo(nodeInfo); + return DM_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))) != DM_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))) != DM_OK) { + DMLOG(DM_LOG_ERROR, "memcpy failed"); + } + deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; + deviceList.push_back(*deviceInfo); } - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices success, pkgName: %s, deviceCount %d", pkgName.c_str(), *infoNum); + FreeNodeInfo(nodeInfo); + DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); return DM_OK; } -int32_t SoftbusConnector::GetLocalDeviceInfo(const std::string &pkgName, NodeBasicInfo *info) +int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &info) { - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo start, pkgName: %s", pkgName.c_str()); + DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo start"); + NodeBasicInfo *nodeInfo = nullptr; int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), info); if (ret != 0) { DMLOG(DM_LOG_ERROR, "GetLocalNodeDeviceInfo failed with ret %d", ret); - return ret; + return DM_FAILED; + } + if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, + std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_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))) != DM_OK) { + DMLOG(DM_LOG_ERROR, "memcpy failed"); } - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo success, pkgName: %s", pkgName.c_str()); + deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; + DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo success"); return DM_OK; } -int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, SubscribeInfo *info) +int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, const DmSubscribeInfo &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_DEBUG, "StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", - pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); - DMLOG(DM_LOG_DEBUG, "Capability: %s", subinfo->info.capability); - int32_t ret = ::StartDiscovery(DM_PKG_NAME.c_str(), &subinfo->info, &softbusDiscoveryCallback_); + 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; + + //TODO:check these later + // 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_DEBUG, "StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", + // pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); + // DMLOG(DM_LOG_DEBUG, "Capability: %s", subinfo->info.capability); + int32_t ret = ::StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); if (ret != 0) { DMLOG(DM_LOG_ERROR, "StartDiscovery failed with ret %d.", ret); - return DEVICEMANAGER_DISCOVERY_FAILED; + return DM_DISCOVERY_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } int32_t SoftbusConnector::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(DM_PKG_NAME.c_str(), subscribeIdAdapter); + // 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, subscribeId:%d", (int32_t)subscribeId); + int32_t ret = ::StopDiscovery(DM_PKG_NAME.c_str(), subscribeId); 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; + // 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, "SoftbusConnector::StopDiscovery completed"); + return DM_OK; } bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) @@ -186,7 +230,7 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) NodeBasicInfo *info = nullptr; int32_t infoNum = 0; - if (GetTrustDevices(DM_PKG_NAME.c_str(), &info, &infoNum) != DEVICEMANAGER_OK) { + if (GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &info, &infoNum) != DM_OK) { DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine DM_GetSoftbusTrustDevices failed"); return false; } @@ -207,7 +251,7 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) 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 != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine GetNodeKeyInfo failed"); break; } @@ -244,10 +288,10 @@ int32_t SoftbusConnector::GetConnectionIpAddr(std::string deviceId, std::string } ipAddr = deviceInfo->addr[i].info.ip.ip; DMLOG(DM_LOG_INFO, "DM_GetConnectionIpAddr get ip ok."); - return DEVICEMANAGER_OK; + return DM_OK; } DMLOG(DM_LOG_ERROR, "failed to get ipAddr for deviceId %s", GetAnonyString(deviceId).c_str()); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } ConnectionAddr *SoftbusConnector::GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type) @@ -310,28 +354,28 @@ void SoftbusConnector::NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, N { (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) { + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(nodeBasicInfo.networkId))) != DM_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) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DM_OK) { DMLOG(DM_LOG_ERROR, "memcpy failed"); } - dmDeviceInfo.deviceTypeId = (DMDeviceType)nodeBasicInfo.deviceTypeId; + dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId; } void SoftbusConnector::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) { + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != DM_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) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { DMLOG(DM_LOG_ERROR, "memcpy failed"); } - dmDeviceInfo.deviceTypeId = (DMDeviceType)deviceInfo.devType; + dmDeviceInfo.deviceTypeId = deviceInfo.devType; } void SoftbusConnector::OnPublishSuccess(int32_t publishId) @@ -350,20 +394,20 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) DMLOG(DM_LOG_ERROR, "SoftbusConnector::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()); - RemoveDiscoveryDeviceInfo(deviceId); + // 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 != DM_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()); + // RemoveDiscoveryDeviceInfo(deviceId); } void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 4f92b0be7..9e07c9a0d 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -21,16 +21,6 @@ namespace OHOS { namespace DistributedHardware { SoftbusSession::SoftbusSession() : sessionIdSet_(), messages_() -{ - Init(); -} - -SoftbusSession::~SoftbusSession() -{ - (void)RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME); -} - -void SoftbusSession::Init() { ISessionListener sessionListener = { .OnSessionOpened = SoftbusSession::OnSessionOpened, @@ -40,11 +30,15 @@ void SoftbusSession::Init() .OnStreamReceived = nullptr }; int32_t ret = CreateSessionServer(DM_PKG_NAME, DM_SESSION_NAME, &sessionListener); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_DEBUG, "CreateSessionServer failed"); return DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; } - return DM_OK; +} + +SoftbusSession::~SoftbusSession() +{ + (void)RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME); } int32_t SoftbusSession::OpenAuthSession(const char *deviceId) @@ -100,7 +94,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) 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) { + if (ret != DM_OK || outLen > MSG_MAX_SIZE) { DMLOG(DM_LOG_ERROR, "MbedtlsEncrypt data failed"); free(buf); return ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; @@ -116,7 +110,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) // int32_t ret = DEVICEMANAGER_FAILED; // if (sessionIdSet_.count(sessionId) > 0) { // ret = SendBytes(sessionId, data, len); -// if (ret != DEVICEMANAGER_OK) { +// if (ret != DM_OK) { // return DEVICEMANAGER_FAILED; // } // } else { @@ -141,7 +135,7 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) if (sessionSide == AUTH_SESSION_SIDE_CLIENT) { for (auto msg : messages_) { int32_t ret = SendMsg(sessionId, msg); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_INFO, "send message failed"); return ret; } @@ -176,7 +170,7 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 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) { + if (ret != DM_OK || outLen > (int32_t)dataLen) { DMLOG(DM_LOG_ERROR, "MbedtlsDecrypt data failed"); free(buf); return; diff --git a/services/devicemanagerservice/src/device_manager_impl.cpp b/services/devicemanagerservice/src/device_manager_service.cpp similarity index 62% rename from services/devicemanagerservice/src/device_manager_impl.cpp rename to services/devicemanagerservice/src/device_manager_service.cpp index f0cbbb8d3..dbe143743 100644 --- a/services/devicemanagerservice/src/device_manager_impl.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -13,36 +13,41 @@ * limitations under the License. */ -#include "device_manager_impl.h" +#include "device_manager_service.h" #include "dm_log.h" #include "dm_constants.h" namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); -int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) +int32_t DeviceManagerService::Init() { - if (pkgName == nullptr || pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, pkgName is empty"); - return ERROR_INPUT_PARA_EMPTY; + if (softbusConnectorPtr_ != nullptr) { + softbusConnectorPtr_ = std::make_shared(); } + listenerPtr_ = std::make_shared(); + deviceInfoMgrPtr_ = std::make_shared(); + deviceStateMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); + return DM_OK; +} - if (deviceList == nullptr) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, deviceList is null"); +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) +{ + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } //TODO:check permissions - if (deviceInfoMgrPtr_ == nullptr) { deviceInfoMgrPtr_ = std::make_shared(); } return deviceInfoMgrPtr_->GetTrustedDeviceList(pkgName, extra, deviceList); } -int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &info) +int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { if (deviceInfoMgrPtr_ == nullptr) { deviceInfoMgrPtr_ = std::make_shared(); @@ -50,56 +55,62 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &info) return deviceInfoMgrPtr_->GetLocalDeviceInfo(info); } -int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) +int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { - if (pkgName == nullptr || pkgName.empty()) { + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, pkgName is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; + } + if (softbusConnectorPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, softbus not ready"); + return DM_FAILED; } if (discoveryMgrPtr_ == nullptr) { - discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_); + discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); } return discoveryMgrPtr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); } -int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - if (pkgName == nullptr || pkgName.empty()) { + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } + if (softbusConnectorPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, softbus not ready"); + return ERROR_INPUT_PARA_EMPTY; + } if (discoveryMgrPtr_ == nullptr) { discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_); } return discoveryMgrPtr_->StopDeviceDiscovery(pkgName, subscribeId); } -int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra) +int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra) { - if (pkgName == nullptr || pkgName.empty()) { + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } - - if (deviceId == nullptr || deviceId.empty()) { + if (deviceId.empty()) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, deviceId is empty"); return ERROR_INPUT_PARA_EMPTY; } - if (authMgrPtr_ == nullptr) { authMgrPtr_ = std::make_shared(softbusConnectorPtr_); } return authMgrPtr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } -int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); +int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); { - if (pkgName == nullptr || pkgName.empty()) { + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } - if (deviceId == nullptr || deviceId.empty()) { + if (deviceId.empty()) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, deviceId is empty"); return ERROR_INPUT_PARA_EMPTY; } @@ -110,9 +121,9 @@ int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId) return authMgrPtr_->UnAuthenticateDevice(pkgName, deviceId); } -int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam) +int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) { - if (pkgName == nullptr || pkgName.empty()) { + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } diff --git a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp similarity index 81% rename from services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp rename to services/devicemanagerservice/src/device_manager_service_listener.cpp index 2fd07e261..766a58683 100644 --- a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -13,15 +13,15 @@ * limitations under the License. */ -#include "ipc_server_listener_adapter.h" +#include "device_manager_service_listener.h" #include #include "securec.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "anonymous_string.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_anonymous.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_check_auth_result_req.h" @@ -32,9 +32,8 @@ namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(IpcServerListenerAdapter); -void IpcServerListenerAdapter::OnDeviceStateChange(DmDeviceState state, DmDeviceInfo &deviceInfo) +void DeviceManagerServiceListener::OnDeviceStateChange(DmDeviceState state, DmDeviceInfo &deviceInfo) { DMLOG(DM_LOG_INFO, "OnDeviceStateChange"); std::shared_ptr pReq = std::make_shared(); @@ -45,7 +44,7 @@ void IpcServerListenerAdapter::OnDeviceStateChange(DmDeviceState state, DmDevice ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } -void IpcServerListenerAdapter::OnDeviceFound(std::string &pkgName, uint16_t originId, +void DeviceManagerServiceListener::OnDeviceFound(std::string &pkgName, uint16_t originId, DmDeviceInfo &deviceInfo) { DMLOG(DM_LOG_INFO, "call OnDeviceFound for %s, originId %d, deviceId %s", @@ -59,7 +58,7 @@ void IpcServerListenerAdapter::OnDeviceFound(std::string &pkgName, uint16_t orig ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } -void IpcServerListenerAdapter::OnDiscoverFailed(std::string &pkgName, uint16_t originId, +void DeviceManagerServiceListener::OnDiscoverFailed(std::string &pkgName, uint16_t originId, DiscoveryFailReason failReason) { DMLOG(DM_LOG_INFO, "OnDiscoverFailed"); @@ -72,7 +71,7 @@ void IpcServerListenerAdapter::OnDiscoverFailed(std::string &pkgName, uint16_t o ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } -void IpcServerListenerAdapter::OnDiscoverySuccess(std::string &pkgName, uint16_t originId) +void DeviceManagerServiceListener::OnDiscoverySuccess(std::string &pkgName, uint16_t originId) { DMLOG(DM_LOG_INFO, "OnDiscoverySuccess"); std::shared_ptr pReq = std::make_shared(); @@ -80,11 +79,11 @@ void IpcServerListenerAdapter::OnDiscoverySuccess(std::string &pkgName, uint16_t pReq->SetPkgName(pkgName); pReq->SetSubscribeId(originId); - pReq->SetResult(DEVICEMANAGER_OK); + pReq->SetResult(DM_OK); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } -void IpcServerListenerAdapter::OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, +void DeviceManagerServiceListener::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(), @@ -100,7 +99,7 @@ void IpcServerListenerAdapter::OnAuthResult(std::string &pkgName, std::string &d ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); } -void IpcServerListenerAdapter::OnCheckAuthResult(std::string &authParam, int32_t resultCode, +void DeviceManagerServiceListener::OnCheckAuthResult(std::string &authParam, int32_t resultCode, int32_t flag) { DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", @@ -114,7 +113,7 @@ void IpcServerListenerAdapter::OnCheckAuthResult(std::string &authParam, int32_t ipcServerListener_.SendAll(SERVER_CHECK_AUTH_RESULT, pReq, pRsp); } -void IpcServerListenerAdapter::OnFaCall(std::string &pkgName, std::string ¶mJson) +void DeviceManagerServiceListener::OnFaCall(std::string &pkgName, std::string ¶mJson) { DMLOG(DM_LOG_INFO, "OnFaCall in"); std::shared_ptr pReq = std::make_shared(); @@ -125,4 +124,4 @@ void IpcServerListenerAdapter::OnFaCall(std::string &pkgName, std::string ¶m ipcServerListener_.SendRequest(SERVER_DEVICEMANAGER_FA_NOTIFY, pReq, pRsp); } } // namespace DistributedHardware -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 9b0c3e732..409a706f0 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -27,20 +27,31 @@ DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr softb int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - //TODO: extra is not null then start adatper manager - if (extra != nullptr && !extra.empty()) { - adapterMgrPtr_ = std::make_shared(); + IDecisionAdapter decisionAdapter = nullptr; + //TODO:define the extra json format support multi filter algoritme + if (!extra.empty()) { + adapterMgrPtr_ = std::make_shared();+ + decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); } - - // softbusConnectorPtr->GetTru - return SUCCESS; - + int32_t ret = softbusConnectorPtr_->GetTrustedDeviceList(deviceList); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed"); + return ret; + } + if (decisionAdapter != nullptr) { + decisionAdapter->FilterDeviceList(deviceList, extra); + } + return DM_OK; } int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info) { - //get device info from softbus and copy to vector - return SUCCESS; + int32_t ret = softbusConnectorPtr_->GetLocalDeviceInfo(info); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "GetLocalDeviceInfo failed"); + return ret; + } + return DM_OK; } } diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 1e5e6b883..5d6734d32 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, - std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) + std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) { DMLOG(DM_LOG_INFO, "DmDeviceStateManager constructor"); } diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index ecd76b4eb..17155142b 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, - std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) + std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) { DMLOG(DM_LOG_INFO, "DmDiscoveryManager constructor"); } @@ -33,7 +33,10 @@ DmDiscoveryManager::~DmDiscoveryManager() int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { - return SUCCESS; + //TODO:prevent reentration + //TODO:save extra for later filter the found device + softbusConnectorPtr->RegisterSoftbusDiscoveryCallback(pkgName, ) + return softbusConnectorPtr->StartDeviceDiscovery(pkgName, subscribeInfo); } int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) 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/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index b71b3edfd..988c0a597 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -13,11 +13,10 @@ * limitations under the License. */ -#include "constants.h" #include "ipc_cmd_register.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" @@ -43,13 +42,13 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, IpcIoPushString(&request, pkgName.c_str()); IpcIoPushInt32(&request, deviceState); IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, IpcIo &request, @@ -64,13 +63,13 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, IpcIo IpcIoPushString(&request, pkgName.c_str()); IpcIoPushUint16(&request, subscribeId); IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, IpcIo &request, @@ -85,13 +84,13 @@ ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, Ipc IpcIoPushString(&request, pkgName.c_str()); IpcIoPushUint16(&request, subscribeId); IpcIoPushInt32(&request, result); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, @@ -110,13 +109,13 @@ ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo & IpcIoPushInt32(&request, pinToken); IpcIoPushInt32(&request, status); IpcIoPushInt32(&request, reason); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, @@ -133,13 +132,13 @@ ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, I IpcIoPushString(&request, deviceId.c_str()); IpcIoPushInt32(&request, result); IpcIoPushInt32(&request, flag); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) @@ -150,7 +149,7 @@ ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) 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); + int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); IpcIoPushInt32(&reply, infoNum); if (infoNum > 0) { IpcIoPushFlatObj(&reply, info, sizeof(DmDeviceInfo) * infoNum); @@ -179,7 +178,7 @@ ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) uint32_t size = 0; DmSubscribeInfo *pDmSubscribeInfo = (DmSubscribeInfo*)IpcIoPopFlatObj(&req, &size); - int32_t ret = IpcServerAdapter::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo); + int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo); IpcIoPushInt32(&reply, ret); } @@ -189,7 +188,7 @@ ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) 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); + int32_t ret = DeviceManagerService::GetInstance().StopDiscovery(pkgName, subscribeId); IpcIoPushInt32(&reply, ret); } @@ -203,7 +202,7 @@ ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) 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); + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); IpcIoPushInt32(&reply, ret); } @@ -212,7 +211,7 @@ 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); + int32_t ret = DeviceManagerService::GetInstance().CheckAuthentication(authPara); IpcIoPushInt32(&reply, ret); } @@ -222,7 +221,7 @@ ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) 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); + DeviceManagerService::GetInstance().GetAuthenticationParam(packName, authParam); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { IpcIoPushInt32(&reply, authParam.direction); IpcIoPushInt32(&reply, authParam.authType); @@ -258,7 +257,7 @@ 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); + DeviceManagerService::GetInstance().SetUserOperation(packName, action); IpcIoPushInt32(&reply, action); } @@ -271,13 +270,13 @@ ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBase std::string paramJson = pReq->GetJsonParam(); IpcIoPushString(&request, packagname.c_str()); IpcIoPushString(&request, paramJson.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo& reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp new file mode 100644 index 000000000..887337470 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_cmd_register.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) +{ + 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; + } + return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); +} + +int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + 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; + } + return (readResponseMapIter->second)(reply, pBaseRsp); +} + +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; + } + (onIpcCmdMapIter->second)(reply); + 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; + } + (onIpcServerCmdMapIter->second)(req, reply); + 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 index 7fe96002c..cd2964c31 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -38,33 +38,33 @@ void IpcServerListener::CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *ide int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity *svc) { CommonSvcId svcId; - if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DEVICEMANAGER_OK) { + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DM_OK) { DMLOG(DM_LOG_ERROR, "get identity failed."); return DEVICEMANAGER_FAILED; } CommonSvcToIdentity(&svcId, svc); - return DEVICEMANAGER_OK; + 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) != DEVICEMANAGER_OK) { + if (GetIdentityByPkgName(pkgName, &svc) != DM_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) { + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_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) { + if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); } - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) @@ -77,17 +77,17 @@ int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::string pkgName = kv.first; req->SetPkgName(pkgName); - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_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) { + if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); } } - return DEVICEMANAGER_OK; + 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 index 59aec4fda..3fe943d9c 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp @@ -31,7 +31,7 @@ int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const Commo DMLOG(DM_LOG_INFO, "new listener register:%s", pkgName.c_str()); std::lock_guard autoLock(lock_); dmListenerMap_[pkgName] = *svcId; - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId) @@ -47,14 +47,14 @@ int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonS return DEVICEMANAGER_FAILED; } *svcId = iter->second; - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcServerListenermgr::UnregisterListener(std::string &pkgName) { std::lock_guard autoLock(lock_); dmListenerMap_.erase(pkgName); - return DEVICEMANAGER_OK; + return DM_OK; } const std::map &IpcServerListenermgr::GetAllListeners() diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp index 565cfe637..fc2848839 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp @@ -29,11 +29,11 @@ static void InitAll() const int32_t DM_SERVICE_INIT_DELAY = 2; sleep(DM_SERVICE_INIT_DELAY); - if (IpcServerStubInit() != DEVICEMANAGER_OK) { + if (IpcServerStubInit() != DM_OK) { DMLOG(DM_LOG_ERROR, "IpcServerStubInit failed"); return; } - if (IpcServerAdapter::GetInstance().ModuleInit() != DEVICEMANAGER_OK) { + if (DeviceManagerService::GetInstance().Init() != DM_OK) { DMLOG(DM_LOG_ERROR, "module init failed"); return; } diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp index 458164274..da69cc39a 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -60,7 +60,7 @@ static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, voi } CommonSvcId svcId = {0}; std::string pkgName = (const char *)arg; - if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DEVICEMANAGER_OK) { + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_OK) { DMLOG(DM_LOG_ERROR, "not found client by package name."); free(arg); arg = NULL; @@ -77,7 +77,7 @@ static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, voi sid.token = svcId.token; sid.cookie = svcId.cookie; UnregisterDeathCallback(sid, svcId.cbId); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) @@ -108,7 +108,7 @@ int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) DMLOG(DM_LOG_ERROR, "malloc failed!"); return DEVICEMANAGER_MALLOC_ERROR; } - if (strcpy_s(pkgName, len + 1, (const char *)name) != DEVICEMANAGER_OK) { + if (strcpy_s(pkgName, len + 1, (const char *)name) != DM_OK) { DMLOG(DM_LOG_ERROR, "strcpy_s failed!"); free(pkgName); return DEVICEMANAGER_COPY_FAILED; @@ -130,12 +130,12 @@ int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) return DEVICEMANAGER_FAILED; } CommonSvcId svcId; - if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DEVICEMANAGER_OK) { + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_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) { + if (ret == DM_OK) { #ifdef __LINUX__ BinderRelease(svcId.ipcCtx, svcId.handle); #endif @@ -199,7 +199,7 @@ static void HOS_SystemInit(void) int32_t IpcServerStubInit(void) { HOS_SystemInit(); - return DEVICEMANAGER_OK; + return DM_OK; } static void DevMgrSvcInit(void) diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 5d3292e81..c2d12c256 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -48,13 +48,13 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); return DEVICEMANAGER_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, MessageParcel &data) @@ -75,13 +75,13 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, Messag DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); return DEVICEMANAGER_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, MessageParcel &data) @@ -102,13 +102,13 @@ ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, Mes DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) @@ -139,13 +139,13 @@ ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, Message DMLOG(DM_LOG_ERROR, "write reason failed"); return DEVICEMANAGER_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) @@ -171,13 +171,13 @@ ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, M DMLOG(DM_LOG_ERROR, "write flag failed"); return DEVICEMANAGER_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) @@ -187,7 +187,7 @@ ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) 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); + int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); reply.WriteInt32(infoNum); if (infoNum > 0 && info != nullptr) { if (!reply.WriteRawData(info, sizeof(DmDeviceInfo) * infoNum)) { @@ -199,7 +199,7 @@ ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) @@ -211,7 +211,7 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) @@ -222,7 +222,7 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) @@ -233,13 +233,13 @@ ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) if (subscribeInfo != nullptr) { DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); - result = IpcServerAdapter::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo); + result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo); } if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) @@ -247,12 +247,12 @@ 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); + int32_t result = DeviceManagerService::GetInstance().StopDiscovery(pkgName, subscribeId); if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) @@ -266,36 +266,36 @@ ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) uint8_t *appThumbnail = appThumbnailLen > 0? (uint8_t *)data.ReadRawData(appThumbnailLen) : nullptr; DmAppImageInfo imageInfo(appIcon, appIconLen, appThumbnail, appThumbnailLen); - int32_t result = DEVICEMANAGER_OK; + int32_t result = DM_OK; if (deviceInfo != nullptr) { - result = IpcServerAdapter::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); + result = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); } if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(CHECK_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) { std::string authPara = data.ReadString(); - int32_t result = IpcServerAdapter::GetInstance().CheckAuthentication(authPara); + int32_t result = DeviceManagerService::GetInstance().CheckAuthentication(authPara); if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) { std::string packName = data.ReadString(); DmAuthParam authParam; - int32_t ret = DEVICEMANAGER_OK; + int32_t ret = DM_OK; DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); - IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); + DeviceManagerService::GetInstance().GetAuthenticationParam(packName, authParam); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || !reply.WriteInt32(authParam.pinToken)) { @@ -330,14 +330,14 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re } } - return DEVICEMANAGER_OK; + return DM_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); + int result = DeviceManagerService::GetInstance().SetUserOperation(packageName, action); if (!reply.WriteInt32(action)) { DMLOG(DM_LOG_ERROR, "write result failed"); @@ -360,13 +360,13 @@ ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBase DMLOG(DM_LOG_ERROR, "write paramJson failed"); return DEVICEMANAGER_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp new file mode 100644 index 000000000..e958dfd04 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp @@ -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. + */ + +#include "ipc_cmd_register.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); + +int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) +{ + 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; + } + return (setRequestMapIter->second)(pBaseReq, data); +} + +int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + 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; + } + return (readResponseMapIter->second)(reply, pBaseRsp); +} + +int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &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; + } + return (onIpcCmdMapIter->second)(data, reply); +} +} // 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 index 6dc1a24c1..16ab7d0da 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp @@ -35,10 +35,10 @@ int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr r MessageParcel data; MessageParcel reply; MessageOption option; - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DEVICEMANAGER_OK) { + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) { return DEVICEMANAGER_FAILED; } - if (remote->SendRequest(cmdCode, data, reply, option) != DEVICEMANAGER_OK) { + if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); return DEVICEMANAGER_IPC_FAILED; } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp index e08eaeab5..fd9391561 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp @@ -42,7 +42,7 @@ int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, sptr listener = iface_cast(remote); listener->SendCmd(cmdCode, req, rsp); } - return DEVICEMANAGER_OK; + 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 index 7cf317ccd..bf259a6d8 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -28,8 +28,9 @@ #include "device_manager_errno.h" #include "device_manager_log.h" -#include "ipc_server_adapter.h" +// #include "ipc_server_adapter.h" #include "ipc_cmd_register.h" +#include "device_manager_impl.h" namespace OHOS { namespace DistributedHardware { @@ -71,7 +72,7 @@ bool IpcServerStub::Init() std::thread { [] { - IpcServerAdapter::GetInstance().ModuleInit(); + DeviceManagerService::GetInstance().Init(); } }.detach(); return true; @@ -88,7 +89,7 @@ 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; + int32_t ret = DM_OK; ret = IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply); if (ret == DEVICEMANAGER_IPC_NOT_REGISTER_FUNC) { DMLOG(DM_LOG_WARN, "unsupport code: %d", code); @@ -99,7 +100,7 @@ int32_t IpcServerStub::OnRemoteRequest(uint32_t code, int32_t IpcServerStub::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - return DEVICEMANAGER_OK; + return DM_OK; } ServiceRunningState IpcServerStub::QueryServiceState() const @@ -119,7 +120,7 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< auto iter = dmListener_.find(pkgName); if (iter != dmListener_.end()) { DMLOG(DM_LOG_INFO, "RegisterDeviceManagerListener: listener already exists"); - return DEVICEMANAGER_OK; + return DM_OK; } sptr appRecipient = sptr(new AppDeathRecipient()); @@ -128,7 +129,7 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< } dmListener_[pkgName] = listener; appRecipient_[pkgName] = appRecipient; - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) @@ -143,14 +144,14 @@ int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) auto listenerIter = dmListener_.find(pkgName); if (listenerIter == dmListener_.end()) { DMLOG(DM_LOG_INFO, "UnRegisterDeviceManagerListener: listener not exists"); - return DEVICEMANAGER_OK; + return DM_OK; } auto recipientIter = appRecipient_.find(pkgName); if (recipientIter == appRecipient_.end()) { DMLOG(DM_LOG_INFO, "UnRegisterDeviceManagerListener: appRecipient not exists"); dmListener_.erase(pkgName); - return DEVICEMANAGER_OK; + return DM_OK; } auto listener = listenerIter->second; @@ -158,7 +159,7 @@ int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) listener->RemoveDeathRecipient(appRecipient); appRecipient_.erase(pkgName); dmListener_.erase(pkgName); - return DEVICEMANAGER_OK; + return DM_OK; } const std::map> &IpcServerStub::GetDmListener() diff --git a/test/unittest/device_manager_impl_test.cpp b/test/unittest/device_manager_impl_test.cpp index a6070729f..620a5cf04 100644 --- a/test/unittest/device_manager_impl_test.cpp +++ b/test/unittest/device_manager_impl_test.cpp @@ -84,10 +84,10 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice3, testing::ext::TestSize.Leve 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)); + .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret= DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, dmAppImageInfo, extra, callback); - ASSERT_EQ(ret, DEVICEMANAGER_OK); + ASSERT_EQ(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; } @@ -122,9 +122,9 @@ HWTEST_F(DeviceManagerImplTest, CheckAuthentication3, testing::ext::TestSize.Lev 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)); + .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret= DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); - ASSERT_EQ(ret, DEVICEMANAGER_OK); + ASSERT_EQ(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; } @@ -145,9 +145,9 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, testing::ext::TestSize.Le 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)); + .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, test_callback_); - ASSERT_EQ(ret, DEVICEMANAGER_OK); + ASSERT_EQ(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; } diff --git a/test/unittest/device_manager_impl_test.h b/test/unittest/device_manager_impl_test.h index 9efa3619b..91ef0863a 100644 --- a/test/unittest/device_manager_impl_test.h +++ b/test/unittest/device_manager_impl_test.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_IMPL_TEST_H -#define OHOS_DEVICE_MANAGER_IMPL_TEST_H +#ifndef OHOS_DM_IMPL_TEST_H +#define OHOS_DM_IMPL_TEST_H #include #include @@ -47,4 +47,4 @@ public: } // namespace Vsync } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IMPL_TEST_H +#endif // OHOS_DM_IMPL_TEST_H -- Gitee From 2fc4f045d6763b0b3532e0f9d2006abb543bf0ed Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Fri, 26 Nov 2021 15:36:48 +0800 Subject: [PATCH 008/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/constants/dm_constants.h | 3 + .../include/device_manager_service.h | 15 +- .../include/device_manager_service_listener.h | 3 +- .../src/device_manager_service.cpp | 133 +++++++++++++----- .../src/device_manager_service_listener.cpp | 7 +- 5 files changed, 112 insertions(+), 49 deletions(-) diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index e5adf3a26..b4bdc7869 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -54,6 +54,9 @@ namespace DistributedHardware { // const int32_t FAIL = -1; // const int32_t SUCCESS = 0; + // const int32_t ERROR_NOT_INIT = 1997; + // const int32_t ERROR_MAKE_SHARED_FAIL = 1998; + // const int32_t ERROR_INIT_MULTIPLE = 1999; // 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; diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index f839326ae..f737d885e 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -18,8 +18,8 @@ #include #include +#include -#include "single_instance.h" #include "dm_auth_manager.h" #include "dm_device_info_manager.h" #include "dm_device_state_manager.h" @@ -27,12 +27,12 @@ #include "dm_device_info.h" #include "softbus_connector.h" - namespace OHOS { namespace DistributedHardware { class DeviceManagerService { - DECLARE_SINGLE_INSTANCE(DeviceManagerService); public: + static DeviceManagerService & GetInstance(); +public: int32_t Init(); int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); int32_t GetLocalDeviceInfo(DmDeviceInfo &info); @@ -42,8 +42,14 @@ public: int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam); private: - DeviceManagerService(); + DeviceManagerService() = default; virtual ~DeviceManagerService() = default; + DeviceManagerService(const DeviceManagerService&) = delete; + DeviceManagerService& operator= (const DeviceManagerService&) = delete; + DeviceManagerService(DeviceManagerService&&) = delete; + DeviceManagerService& operator= (DeviceManagerService&&) = delete; +private: + bool intFlag_ = false; std::shared_ptr authMgrPtr_; std::shared_ptr deviceInfoMgrPtr_; std::shared_ptr deviceStateMgrPtr_; @@ -53,4 +59,5 @@ private: }; } // 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 index d31017962..d024158fa 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -33,9 +33,8 @@ public: int32_t OnDiscoverySuccess(int32_t subscribeId); int32_t OnAuthenticateResult(const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason); int32_t OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string &flag); -private: - }; } // namespace DistributedHardware } // namespace OHOS + #endif // OHOS_DM_SERVICE_LISTENER_H diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index dbe143743..6effe2160 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -19,92 +19,151 @@ namespace OHOS { namespace DistributedHardware { - -IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); +DeviceManagerService& DeviceManagerService::GetInstance() +{ + static DeviceManagerService instance; + return instance; +} int32_t DeviceManagerService::Init() { - if (softbusConnectorPtr_ != nullptr) { + if (intFlag_) { + DMLOG(DM_LOG_ERROR, "Init failed, singleton cannot be initialized multiple times"); + return ERROR_INT_MULTIPLE; + } + + if (softbusConnectorPtr_ == nullptr) { softbusConnectorPtr_ = std::make_shared(); + if (softbusConnectorPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "Init failed, softbusConnectorPtr_ apply for failure"); + return ERROR_MAKE_SHARED_FAIL; + } + } + + if (listenerPtr_ == nullptr) { + listenerPtr_ = std::make_shared(); + if (softbusConnectorPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "Init failed, listenerPtr_ apply for failure"); + return ERROR_MAKE_SHARED_FAIL; + } + } + + if (deviceInfoMgrPtr_ == nullptr) { + deviceInfoMgrPtr_ = std::make_shared(); + if (deviceInfoMgrPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "Init failed, deviceInfoMgrPtr_ apply for failure"); + return ERROR_MAKE_SHARED_FAIL; + } + } + + if (deviceStateMgrPtr_ == nullptr) { + deviceStateMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); + if (deviceStateMgrPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "Init failed, deviceStateMgrPtr_ apply for failure"); + return ERROR_MAKE_SHARED_FAIL; + } } - listenerPtr_ = std::make_shared(); - deviceInfoMgrPtr_ = std::make_shared(); - deviceStateMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); + + if (discoveryMgrPtr_ == nullptr) { + discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); + if (discoveryMgrPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "Init failed, discoveryMgrPtr_ apply for failure"); + return ERROR_MAKE_SHARED_FAIL; + } + } + + if(authMgrPtr_ == nullptr) { + authMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); + if (authMgrPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "Init failed, authMgrPtr_ apply for failure"); + return ERROR_MAKE_SHARED_FAIL; + } + } + + DMLOG(DM_LOG_INFO, "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_) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, singleton not init or init fail"); + return ERROR_NOT_INIT; + } + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } - //TODO:check permissions - if (deviceInfoMgrPtr_ == nullptr) { - deviceInfoMgrPtr_ = std::make_shared(); - } return deviceInfoMgrPtr_->GetTrustedDeviceList(pkgName, extra, deviceList); } int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - if (deviceInfoMgrPtr_ == nullptr) { - deviceInfoMgrPtr_ = std::make_shared(); + if (!intFlag_) { + DMLOG(DM_LOG_ERROR, "GetLocalDeviceInfo failed, singleton not init or init fail"); + return ERROR_NOT_INIT; } + return deviceInfoMgrPtr_->GetLocalDeviceInfo(info); } int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { + if (!intFlag_) { + DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, singleton not init or init fail"); + return ERROR_NOT_INIT; + } + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - if (softbusConnectorPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, softbus not ready"); - return DM_FAILED; - } - if (discoveryMgrPtr_ == nullptr) { - discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); - } return discoveryMgrPtr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); } int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { + if (!intFlag_) { + DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, singleton not init or init fail"); + return ERROR_NOT_INIT; + } + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } - if (softbusConnectorPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, softbus not ready"); - return ERROR_INPUT_PARA_EMPTY; - } - if (discoveryMgrPtr_ == nullptr) { - discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_); - } return discoveryMgrPtr_->StopDeviceDiscovery(pkgName, subscribeId); } int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra) { + if (!intFlag_) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, singleton not init or init fail"); + return ERROR_NOT_INIT; + } + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } + if (deviceId.empty()) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, deviceId is empty"); return ERROR_INPUT_PARA_EMPTY; } - if (authMgrPtr_ == nullptr) { - authMgrPtr_ = std::make_shared(softbusConnectorPtr_); - } return authMgrPtr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); { + if (!intFlag_) { + DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, singleton not init or init fail"); + return ERROR_NOT_INIT; + } + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; @@ -115,24 +174,22 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c return ERROR_INPUT_PARA_EMPTY; } - if (authMgrPtr_ == nullptr) { - authMgrPtr_ = std::make_shared(softbusConnectorPtr_); - } return authMgrPtr_->UnAuthenticateDevice(pkgName, deviceId); } int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) { + if (!intFlag_) { + DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, singleton not init or init fail"); + return ERROR_NOT_INIT; + } + if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } - if (authMgrPtr_ == nullptr) { - authMgrPtr_ = std::make_shared(softbusConnectorPtr_); - } return authMgrPtr_->VerifyAuthentication(pkgName, authParam); } - -} -} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 766a58683..85579b814 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -17,8 +17,6 @@ #include -#include "securec.h" - #include "dm_constants.h" #include "dm_log.h" #include "dm_anonymous.h" @@ -99,8 +97,7 @@ void DeviceManagerServiceListener::OnAuthResult(std::string &pkgName, std::strin ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnCheckAuthResult(std::string &authParam, int32_t resultCode, - int32_t flag) +void DeviceManagerServiceListener::OnCheckAuthResult(std::string &authParam, int32_t resultCode, int32_t flag) { DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", GetAnonyString(authParam).c_str(), resultCode); @@ -124,4 +121,4 @@ void DeviceManagerServiceListener::OnFaCall(std::string &pkgName, std::string &p ipcServerListener_.SendRequest(SERVER_DEVICEMANAGER_FA_NOTIFY, pReq, pRsp); } } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS -- Gitee From 19fef1a1f427f84b6e0aaca3b9b9f4c946c988a2 Mon Sep 17 00:00:00 2001 From: puhui Date: Fri, 26 Nov 2021 17:30:40 +0800 Subject: [PATCH 009/110] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/include/constants/dm_constants.h | 5 +- common/include/ipc/ipc_def.h | 6 +- common/include/utils/dm_log.h | 2 +- common/src/utils/dm_random.cpp | 2 - .../include/adapter/crypto_adapter.h | 5 +- .../include/adapter/decision_adapter.h | 4 +- .../include/adapter/dm_adapter_manager.h | 4 +- .../include/authentication/dm_auth_manager.h | 23 +- .../dependency/softbus/softbus_connector.h | 24 +- .../include/device_manager_service.h | 11 +- .../include/device_manager_service_listener.h | 7 +- .../deviceinfo/dm_device_info_manager.h | 1 + .../devicestate/dm_device_state_manager.h | 14 +- .../include/discovery/dm_discovery_manager.h | 9 +- .../src/adapter/dm_adapter_manager.cpp | 13 +- .../dependency/hichain/hichain_connector.cpp | 7 +- .../dependency/softbus/softbus_connector.cpp | 213 +++++++++--------- .../src/device_manager_service.cpp | 37 ++- .../src/deviceinfo/dm_device_info_manager.cpp | 3 +- .../src/discovery/dm_discovery_manager.cpp | 10 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 117 ++++------ 21 files changed, 245 insertions(+), 272 deletions(-) diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index e5adf3a26..a090f7825 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -35,12 +35,13 @@ namespace DistributedHardware { DM_FAILED = (-10000), DM_INPUT_PARA_EMPTY, DM_INPUT_PARA_INVALID, + DM_MALLOC_ERROR, DM_SERVICE_NOT_READY, DM_DEVICE_ALREADY_TRUSTED, DM_HICHAIN_GROUP_CREATE_FAILED, DM_HICHAIN_MEMBER_ADD_FAILED, - DM_HICHAIN_CREATE_CHANNEL_FAILED - DM_OK = 0; + DM_HICHAIN_CREATE_CHANNEL_FAILED, + DM_OK = 0 }; //Softbus diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index b4dff8d42..2cc4e6fdb 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -47,9 +47,9 @@ enum IpcCmdID { SERVER_DISCOVER_FINISH, SERVER_AUTH_RESULT, SERVER_CHECK_AUTH_RESULT, - SERVER_GET_AUTHENTCATION_INFO, - SERVER_USER_AUTHORIZATION_OPERATION, - SERVER_DEVICEMANAGER_FA_NOTIFY, +// SERVER_GET_AUTHENTCATION_INFO, +// SERVER_USER_AUTHORIZATION_OPERATION, +// SERVER_DEVICEMANAGER_FA_NOTIFY, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/utils/dm_log.h b/common/include/utils/dm_log.h index aade3ef58..80822e790 100644 --- a/common/include/utils/dm_log.h +++ b/common/include/utils/dm_log.h @@ -31,7 +31,7 @@ typedef enum { void DMLog(DMLogLevel logLevel, const char *fmt, ...); #define DMLOG(level, fmt, ...) DMLog(level, \ - (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + (std::string("[") + "DH_LOG_TAG" + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) } // namespace DistributedHardware } // namespace OHOS diff --git a/common/src/utils/dm_random.cpp b/common/src/utils/dm_random.cpp index ede0904e2..5c05af675 100644 --- a/common/src/utils/dm_random.cpp +++ b/common/src/utils/dm_random.cpp @@ -17,8 +17,6 @@ #include -#include "dm_constants.h" - namespace OHOS { namespace DistributedHardware { int32_t GenRandInt(int32_t randMin, int32_t randMax) diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h index 9292c787f..ea1fc3146 100644 --- a/services/devicemanagerservice/include/adapter/crypto_adapter.h +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.h @@ -17,16 +17,15 @@ #define OHOS_DM_CRYPTO_ADAPTER_H #include -#include namespace OHOS { namespace DistributedHardware { class ICryptoAdapter { public: virtual ~ICryptoAdapter() = default; - virtual int32_t MbedtlsEncrypt(const uint8_t *plainText, int32_t plainTextLen, uint8_t *cipherText, + 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, + virtual int32_t MbedTlsDecrypt(const uint8_t *cipherText, int32_t cipherTextLen, uint8_t *plainText, int32_t plainTextLen, int32_t *outLen) = 0; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/adapter/decision_adapter.h b/services/devicemanagerservice/include/adapter/decision_adapter.h index 8356758c3..e62529e5e 100644 --- a/services/devicemanagerservice/include/adapter/decision_adapter.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.h @@ -24,8 +24,8 @@ namespace DistributedHardware { class IDecisionAdapter { public: virtual ~IDecisionAdapter() = default; - virtual int32_t FilterDeviceList(std::vector &infoList, const string &filterOptions) = 0; - virtual int32_t SortDeviceList(std::vector &infoList, const string &sortOptions) = 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; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index 4624478eb..1297b694e 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -16,6 +16,8 @@ #ifndef OHOS_DM_ADAPTER_MANAGER_H #define OHOS_DM_ADAPTER_MANAGER_H +#include + #include "decision_adapter.h" #include "profile_adapter.h" #include "crypto_adapter.h" @@ -26,6 +28,7 @@ namespace DistributedHardware { class DmAdapterManager { public: DmAdapterManager(); + ~DmAdapterManager(); std::shared_ptr GetDecisionAdapter(); std::shared_ptr GetProfileAdapter(); std::shared_ptr GetCryptoAdapter(); @@ -33,7 +36,6 @@ private: std::shared_ptr decisionAdapterPtr_; std::shared_ptr profileAdapterPtr_; std::shared_ptr cryptoAdapterPtr_; - }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 68412b322..0362fb88d 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -19,28 +19,29 @@ #include #include -#include "nlohmann/json.hpp" -#include "softbus_session.h" -#include "device_manager_listener.h" -#include "adapter_manager.h" #include "authentication.h" +#include "softbus_session.h" +#include "device_manager_service_listener.h" +#include "dm_adapter_manager.h" +#include "softbus_connector.h" +#include "hichain_connector.h" namespace OHOS { namespace DistributedHardware { class DmAuthManager { public: - DmAuthManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + DmAuthManager(std::shared_ptr softbusConnectorPtr, std::shared_ptr listenerPtr); ~DmAuthManager(); - int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra); - int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); + 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 &pkgName, const std::string &authParam); private: std::shared_ptr softbusSession_; - std::shared_ptr hichainConnector_; - std::shared_ptr listenerPtr_; - std::shared_ptr adapterMgr_; - std::map authenticationMap_; + std::shared_ptr hiChainConnector_; + std::shared_ptr listenerPtr_; + std::shared_ptr adapterMgr_; + std::map authenticationMap_; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index fddf3a3bf..d377211e4 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -25,6 +25,8 @@ #include "discovery_service.h" #include "dm_device_info.h" #include "dm_subscribe_info.h" +#include "softbus_state_callback.h" +#include "softbus_discovery_callback.h" namespace OHOS { namespace DistributedHardware { @@ -41,26 +43,26 @@ public: public: SoftbusConnector(); ~SoftbusConnector(); - int32_t RegisterSoftbusStateCallback(const string &pkgName, const ISoftbusStateCallback &callback); - int32_t UnRegisterSoftbusStateCallback(const string &pkgName); - int32_t RegisterSoftbusDiscoveryCallback(const string &pkgName, const ISoftbusDiscoveryCallback &callback); - int32_t UnRegisterSoftbusDiscoveryCallback(const string &pkgName); - int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector deviceList); - int32_t GetLocalDeviceInfo(DmDeviceInfo &info); - int32_t StartDiscovery(const std::string &pkgName, const DmSubscribeInfo &info); - int32_t StopDiscovery(const std::string &pkgName, uint16_t subscribeId); + int32_t RegisterSoftbusStateCallback(const std::string &pkgName, const ISoftbusStateCallback &callback); + int32_t UnRegisterSoftbusStateCallback(const std::string &pkgName); + int32_t RegisterSoftbusDiscoveryCallback(const std::string &pkgName, const ISoftbusDiscoveryCallback &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); bool IsDeviceOnLine(const std::string &deviceId); - int32_t GetConnectionIpAddr(const std::string &deviceId, std::string &ipAddr); +// int32_t GetConnectionIpAddr(const std::string &deviceId, std::string &ipAddr); private: int32_t Init(); - ConnectionAddr *GetConnectAddr(const std::string &deviceId); +// ConnectionAddr *GetConnectAddr(const std::string &deviceId); // bool GetSubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId); // bool GetPkgNameBySubscribeId(int32_t adapterId, std::string &pkgName); // void SaveDiscoveryDeviceInfo(const DeviceInfo *deviceInfo); // void RemoveDiscoveryDeviceInfo(const std::string deviceId); void NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo); void DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo); - ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); +// ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); private: // struct SubscribeInfoAdapter { // SubscribeInfo info; diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index f839326ae..7f669223b 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -19,14 +19,13 @@ #include #include -#include "single_instance.h" #include "dm_auth_manager.h" #include "dm_device_info_manager.h" #include "dm_device_state_manager.h" #include "dm_discovery_manager.h" #include "dm_device_info.h" #include "softbus_connector.h" - +#include "single_instance.h" namespace OHOS { namespace DistributedHardware { @@ -38,14 +37,12 @@ public: int32_t GetLocalDeviceInfo(DmDeviceInfo &info); 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 string &deviceId, const std::string extra); - int32_t UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); + 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 &pkgName, const std::string &authParam); private: - DeviceManagerService(); - virtual ~DeviceManagerService() = default; std::shared_ptr authMgrPtr_; - std::shared_ptr deviceInfoMgrPtr_; + std::shared_ptr deviceInfoMgrPtr_; std::shared_ptr deviceStateMgrPtr_; std::shared_ptr discoveryMgrPtr_; std::shared_ptr softbusConnectorPtr_; diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index d31017962..7dc3da8a9 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -19,6 +19,7 @@ #include #include "dm_device_info.h" +#include "ipc_server_listener.h" namespace OHOS { namespace DistributedHardware { @@ -27,14 +28,14 @@ public: int32_t OnDeviceOnline(const DmDeviceInfo &info); int32_t OnDeviceOffline(const DmDeviceInfo &info); int32_t OnDeviceReady(const DmDeviceInfo &info); - int32_t OnDeviceStateChange(const DmDeviceInfo &info); - int32_t OnDeviceFound(uint16_t sbuscribeId, const DmDeviceInfo &info); + int32_t OnDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info); + int32_t OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &info); int32_t OnDiscoveryFailed(uint16_t subscribeId, const std::string &failedReason); int32_t OnDiscoverySuccess(int32_t subscribeId); int32_t OnAuthenticateResult(const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason); int32_t OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string &flag); private: - + IpcServerListener ipcServerListener_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h index 7e7385928..36edc2c18 100644 --- a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h @@ -21,6 +21,7 @@ #include "dm_device_info.h" #include "softbus_connector.h" +#include "dm_adapter_manager.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index f09cf0ff4..e7a69515c 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -13,26 +13,26 @@ * limitations under the License. */ -#ifndef OHOS_DM_DEVICE_STATE_MAGANGER_H -#define OHOS_DM_DEVICE_STATE_MAGANGER_H +#ifndef OHOS_DM_DEVICE_STATE_MANAGER_H +#define OHOS_DM_DEVICE_STATE_MANAGER_H #include "softbus_connector.h" -#include "adapter_manager.h" -#include "device_manager_listener.h" +#include "dm_adapter_manager.h" +#include "device_manager_service_listener.h" namespace OHOS { namespace DistributedHardware { class DmDeviceStateManager { public: - DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, std::shared_ptr listenerPtr); ~DmDeviceStateManager(); private: std::shared_ptr softbusConnectorPtr_; std::shared_ptr adapterMgrPtr_; - std::shared_ptr listenerPtr_; + std::shared_ptr listenerPtr_; }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_DEVICE_STATE_MAGANGER_H +#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 index 2215e1b0d..823c39b20 100644 --- a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h @@ -17,22 +17,23 @@ #define OHOS_DM_DISCOVERY_MANAGER_H +#include #include "softbus_connector.h" -#include "device_manager_listener.h" +#include "device_manager_service_listener.h" namespace OHOS { namespace DistributedHardware { class DmDiscoveryManager { public: - DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, std::shared listenerPtr); + DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, std::shared_ptr listenerPtr); ~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); private: std::shared_ptr softbusConnectorPtr_; - std::shared_ptr listenerPtr_; - //TODO:discovery queue used to prevent re enty and stop discovery automatically when timeout + std::shared_ptr listenerPtr_; + //TODO:discovery queue used to prevent re entry and stop discovery automatically when timeout //also used to record the pkg which was being discovered std::queue discoveryQueue_; }; diff --git a/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp index dd2d04b1f..e7b847994 100644 --- a/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp @@ -25,20 +25,27 @@ DmAdapterManager::DmAdapterManager() DMLOG(DM_LOG_INFO, "DmAdapterManager constructor"); } -std::shared_ptr DmAdapterManager::GetDecisionAdapter() +DmAdapterManager::~DmAdapterManager() +{ + DMLOG(DM_LOG_INFO, "DmAdapterManager destructor"); +} + +std::shared_ptr DmAdapterManager::GetDecisionAdapter() { return decisionAdapterPtr_; } -std::shared_ptr DmAdapterManager::GetProfileAdapter() +std::shared_ptr DmAdapterManager::GetProfileAdapter() { return profileAdapterPtr_; } -std::shared_ptr DmAdapterManager::GetCryptoAdapter() +std::shared_ptr DmAdapterManager::GetCryptoAdapter() { return cryptoAdapterPtr_; } + + } } diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index c64b0b9ae..1090459a8 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -26,6 +26,7 @@ #include "dm_anonymous.h" #include "dm_log.h" #include "dm_constants.h" +#include "hichain_connector_callback.h" namespace OHOS { namespace DistributedHardware { @@ -83,7 +84,7 @@ HiChainConnector::HiChainConnector() DMLOG(DM_LOG_INFO, "HiChainConnector::constructor, failed to init group manager!"); return; } - deviceGroupManager_->regCallback(DEVICE_MANAGER_APP.c_str(), &deviceAuthCallback_); + deviceGroupManager_->regCallback(DM_PKG_NAME.c_str(), &deviceAuthCallback_); DMLOG(DM_LOG_INFO, "HiChainConnector::constructor success."); } @@ -93,9 +94,9 @@ HiChainConnector::~HiChainConnector() //TODO:delete resource } -HiChainConnector::RegisterHiChainCallback(const string &pkgName, const IHiChainConnectorCallback &callback) +HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, const IHiChainConnectorCallback &callback) { - if (hichainConnectorCallback.count(pkgName) == 0) { + if (hichainConnectorCallback_.count(pkgName) == 0) { hichainConnectorCallback[pkgName] = callback; } } diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index c9f69b823..657d65957 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -20,8 +20,6 @@ #include #include -#include "softbus_bus_center.h" - #include "dm_log.h" #include "dm_anonymous.h" #include "dm_constants.h" @@ -29,7 +27,7 @@ namespace OHOS { namespace DistributedHardware { -SoftbusConnector::SoftbusConnector() : subscribeInfos_(), discoveryDeviceInfoMap_(), discoveryDeviceInfoVector_() +SoftbusConnector::SoftbusConnector() { DMLOG(DM_LOG_INFO,"SoftbusConnector constructor"); softbusPublishCallback_ = { @@ -54,7 +52,7 @@ SoftbusConnector::~SoftbusConnector() { DMLOG(DM_LOG_INFO,"SoftbusConnector destructor"); } -SoftbusConnector::Init() +int32_t SoftbusConnector::Init() { //TODO:optimize implementation later use semaphore instead int32_t ret; @@ -69,38 +67,38 @@ SoftbusConnector::Init() } while (ret != DM_OK); DMLOG(DM_LOG_INFO, "RegNodeDeviceStateCb success."); //TODO:check system properties first - 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(DM_PKG_NAME.c_str(), &dmPublishInfo, &servicePublishCallback_); + PublishInfo publishInfo; + publishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; + publishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; + publishInfo.medium = ExchanageMedium::AUTO; + publishInfo.freq = ExchangeFreq::HIGH; + publishInfo.capability = DM_CAPABILITY_OSD; + publishInfo.capabilityData = nullptr; + publishInfo.dataLen = 0; + ret = PublishService(DM_PKG_NAME.c_str(), &publishInfo, &softbusPublishCallback_); DMLOG(DM_LOG_INFO, "service publish result is : %d", ret); return ret; } -int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceList) +int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceInfoList) { DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices start"); NodeBasicInfo *nodeInfo = nullptr; - *info = nullptr; - *infoNum = 0; - int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), info, infoNum); + int32_t *infoNum = 0; + int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeInfo, infoNum); if (ret != 0) { DMLOG(DM_LOG_ERROR, "GetAllNodeDeviceInfo failed with ret %d", ret); return DM_FAILED; } - *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (*infoNum)); - if (*info == nullptr) { + 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 = *info + i; + DmDeviceInfo *deviceInfo = *pInfoList + i; if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { DMLOG(DM_LOG_ERROR, "memcpy failed"); @@ -110,36 +108,38 @@ int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceL DMLOG(DM_LOG_ERROR, "memcpy failed"); } deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; - deviceList.push_back(*deviceInfo); + deviceInfoList.push_back(*deviceInfo); } FreeNodeInfo(nodeInfo); + free(info); DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); return DM_OK; } -int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &info) +int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) { DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo start"); NodeBasicInfo *nodeInfo = nullptr; - int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), info); + int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeInfo); if (ret != 0) { DMLOG(DM_LOG_ERROR, "GetLocalNodeDeviceInfo failed with ret %d", ret); return DM_FAILED; } - if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, - std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { + DmDeviceInfo *pInfo = &deviceInfo; + if (memcpy_s(pInfo->deviceId, sizeof(pInfo->deviceId), nodeBasicInfo->networkId, + std::min(sizeof(pInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_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))) != DM_OK) { + if (memcpy_s(pInfo->deviceName, sizeof(pInfo->deviceName), nodeBasicInfo->deviceName, + std::min(sizeof(pInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { DMLOG(DM_LOG_ERROR, "memcpy failed"); } - deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; + pInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo success"); return DM_OK; } -int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, const DmSubscribeInfo &info) +int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &subscribeInfo) { SubscribeInfo subscribeInfo; subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; @@ -184,7 +184,7 @@ int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, const DmSub // DMLOG(DM_LOG_DEBUG, "StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", // pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); // DMLOG(DM_LOG_DEBUG, "Capability: %s", subinfo->info.capability); - int32_t ret = ::StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); + int32_t ret = StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); if (ret != 0) { DMLOG(DM_LOG_ERROR, "StartDiscovery failed with ret %d.", ret); return DM_DISCOVERY_FAILED; @@ -192,7 +192,7 @@ int32_t SoftbusConnector::StartDiscovery(const std::string &pkgName, const DmSub return DM_OK; } -int32_t SoftbusConnector::StopDiscovery(std::string &pkgName, uint16_t subscribeId) +int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) { // int32_t subscribeIdAdapter = -1; // if (!GetsubscribeIdAdapter(pkgName, subscribeId, subscribeIdAdapter)) { @@ -201,7 +201,7 @@ int32_t SoftbusConnector::StopDiscovery(std::string &pkgName, uint16_t subscribe // } DMLOG(DM_LOG_INFO, "StopDiscovery begin, subscribeId:%d", (int32_t)subscribeId); - int32_t ret = ::StopDiscovery(DM_PKG_NAME.c_str(), subscribeId); + int32_t ret = StopDiscovery(DM_PKG_NAME.c_str(), subscribeId); if (ret != 0) { DMLOG(DM_LOG_ERROR, "StopDiscovery failed with ret %d", ret); return ret; @@ -229,12 +229,10 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) { NodeBasicInfo *info = nullptr; int32_t infoNum = 0; - if (GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &info, &infoNum) != DM_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; @@ -255,9 +253,8 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) 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()); + DMLOG(DM_LOG_INFO, "DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str()); bDeviceOnline = true; break; } @@ -266,46 +263,46 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) return bDeviceOnline; } -int32_t SoftbusConnector::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 DM_OK; - } - DMLOG(DM_LOG_ERROR, "failed to get ipAddr 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; -} +//int32_t SoftbusConnector::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 DM_OK; +// } +// DMLOG(DM_LOG_ERROR, "failed to get ipAddr 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(std::string deviceId) { @@ -327,25 +324,21 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(std::string deviceId) 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; } @@ -430,7 +423,7 @@ void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBa void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) { if (device == nullptr) { - DMLOG(DM_LOG_ERROR, "deviceinfo is null"); + DMLOG(DM_LOG_ERROR, "device is null"); return; } std::string deviceId = device->devId; @@ -438,46 +431,46 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) 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); - } - } +// 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); +// } +// } } void SoftbusConnector::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, "SoftbusConnector::OnSoftbusDiscoverFailed: pkgName not found"); - return; - } - - uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); +// std::string pkgName; +// if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { +// DMLOG(DM_LOG_ERROR, "SoftbusConnector::OnSoftbusDiscoverFailed: pkgName not found"); +// return; +// } +// +// uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); // IpcServerListenerAdapter::GetInstance().OnDiscoverFailed(pkgName, originId, failReason); } void SoftbusConnector::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); +// 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); } diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index dbe143743..79af01f31 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -14,8 +14,10 @@ */ #include "device_manager_service.h" +#include "device_manager_service_listener.h" #include "dm_log.h" #include "dm_constants.h" +#include "dm_device_info_manager.h" namespace OHOS { namespace DistributedHardware { @@ -28,7 +30,7 @@ int32_t DeviceManagerService::Init() softbusConnectorPtr_ = std::make_shared(); } listenerPtr_ = std::make_shared(); - deviceInfoMgrPtr_ = std::make_shared(); + deviceInfoMgrPtr_ = std::make_shared(softbusConnectorPtr_); deviceStateMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); return DM_OK; } @@ -37,21 +39,14 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c { if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, pkgName is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } - //TODO:check permissions - if (deviceInfoMgrPtr_ == nullptr) { - deviceInfoMgrPtr_ = std::make_shared(); - } return deviceInfoMgrPtr_->GetTrustedDeviceList(pkgName, extra, deviceList); } int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - if (deviceInfoMgrPtr_ == nullptr) { - deviceInfoMgrPtr_ = std::make_shared(); - } return deviceInfoMgrPtr_->GetLocalDeviceInfo(info); } @@ -75,48 +70,46 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui { if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, pkgName is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } if (softbusConnectorPtr_ == nullptr) { DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, softbus not ready"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } if (discoveryMgrPtr_ == nullptr) { - discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_); + discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); } return discoveryMgrPtr_->StopDeviceDiscovery(pkgName, subscribeId); } -int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra) +int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, pkgName is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } if (deviceId.empty()) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, deviceId is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } if (authMgrPtr_ == nullptr) { - authMgrPtr_ = std::make_shared(softbusConnectorPtr_); + authMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); } return authMgrPtr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } -int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const string &deviceId); +int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId); { if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, pkgName is empty"); return ERROR_INPUT_PARA_EMPTY; } - if (deviceId.empty()) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, deviceId is empty"); return ERROR_INPUT_PARA_EMPTY; } - if (authMgrPtr_ == nullptr) { - authMgrPtr_ = std::make_shared(softbusConnectorPtr_); + authMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); } return authMgrPtr_->UnAuthenticateDevice(pkgName, deviceId); } @@ -125,11 +118,11 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c { if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, pkgName is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } if (authMgrPtr_ == nullptr) { - authMgrPtr_ = std::make_shared(softbusConnectorPtr_); + authMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); } return authMgrPtr_->VerifyAuthentication(pkgName, authParam); } diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 409a706f0..2438e6d25 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -14,6 +14,7 @@ */ #include "dm_device_info_manager.h" + #include "dm_log.h" #include "dm_constants.h" @@ -30,7 +31,7 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co IDecisionAdapter decisionAdapter = nullptr; //TODO:define the extra json format support multi filter algoritme if (!extra.empty()) { - adapterMgrPtr_ = std::make_shared();+ + adapterMgrPtr_ = std::make_shared(); decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); } int32_t ret = softbusConnectorPtr_->GetTrustedDeviceList(deviceList); diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 17155142b..a8fa30cf3 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, - std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) + std::shared_ptr listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) { DMLOG(DM_LOG_INFO, "DmDiscoveryManager constructor"); } @@ -35,13 +35,15 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con { //TODO:prevent reentration //TODO:save extra for later filter the found device - softbusConnectorPtr->RegisterSoftbusDiscoveryCallback(pkgName, ) - return softbusConnectorPtr->StartDeviceDiscovery(pkgName, subscribeInfo); + softbusConnectorPtr_->RegisterSoftbusDiscoveryCallback(pkgName, ); + return softbusConnectorPtr_->StartDiscovery(subscribeInfo); } int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - return SUCCESS; + //TODO:stop discovery and remove queue + softbusConnectorPtr_->UnRegisterSoftbusDiscoveryCallback(pkgName); + return softbusConnectorPtr_->StopDiscovery(subscribeId); } } diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 988c0a597..83526be74 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -17,6 +17,7 @@ #include "dm_constants.h" #include "dm_log.h" +#include "device_manager_service.h" #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" @@ -25,7 +26,6 @@ #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 { @@ -188,7 +188,7 @@ ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) size_t len = 0; std::string pkgName = (const char *)IpcIoPopString(&req, &len); uint16_t subscribeId = IpcIoPopUint16(&req); - int32_t ret = DeviceManagerService::GetInstance().StopDiscovery(pkgName, subscribeId); + int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); IpcIoPushInt32(&reply, ret); } @@ -201,9 +201,9 @@ ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) 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 = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); - IpcIoPushInt32(&reply, ret); +// DmAppImageInfo imageInfo(nullptr, 0, nullptr, 0); +// int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); +// IpcIoPushInt32(&reply, ret); } ON_IPC_SERVER_CMD(CHECK_AUTHENTICATION, IpcIo &req, IpcIo &reply) @@ -211,72 +211,45 @@ 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 = DeviceManagerService::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()); - DeviceManagerService::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); - DeviceManagerService::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 DM_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DM_OK; -} +// int32_t ret = DeviceManagerService::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()); +// DeviceManagerService::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); +// } +//} } // namespace DistributedHardware } // namespace OHOS -- Gitee From c65d2b700b3a530a7fa9cd05889df80a15427be4 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Fri, 26 Nov 2021 21:07:30 +0800 Subject: [PATCH 010/110] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=83=A8=E5=88=86ipc?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/constants/dm_constants.h | 2 + common/include/ipc/ipc_def.h | 3 + .../ipc/model/ipc_start_discovery_req.h | 11 +++ .../src/ipc/lite/ipc_cmd_parser.cpp | 22 +++++ .../include/device_manager_service.h | 2 +- .../deviceinfo/dm_device_info_manager.h | 5 +- .../dependency/softbus/softbus_connector.cpp | 1 - .../src/device_manager_service.cpp | 16 ++-- .../src/deviceinfo/dm_device_info_manager.cpp | 32 ++++--- .../src/ipc/lite/ipc_cmd_parser.cpp | 88 ++++++++++++------- .../src/ipc/standard/ipc_cmd_parser.cpp | 6 +- 11 files changed, 129 insertions(+), 59 deletions(-) diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index 7d0e7bcb5..296d35d8c 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -33,6 +33,8 @@ namespace DistributedHardware { enum { DM_FAILED = (-10000), + DM_NOT_INIT, + DM_POINT_NULL, DM_INPUT_PARA_EMPTY, DM_INPUT_PARA_INVALID, DM_MALLOC_ERROR, diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 2cc4e6fdb..3ba79b9eb 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -38,9 +38,12 @@ enum IpcCmdID { REGISTER_DEVICE_MANAGER_LISTENER = 0, UNREGISTER_DEVICE_MANAGER_LISTENER, GET_TRUST_DEVICE_LIST, + GET_LOCAL_DEVICE_INFO, START_DEVICE_DISCOVER, STOP_DEVICE_DISCOVER, AUTHENTICATE_DEVICE, + UNAUTHENTICATE_DEVICE, + VERIFY_AUTHENTICATE, CHECK_AUTHENTICATION, SERVER_DEVICE_STATE_NOTIFY, SERVER_DEVICE_FOUND, diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h index f77d5372a..1d03b1ce7 100644 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ b/common/include/ipc/model/ipc_start_discovery_req.h @@ -34,7 +34,18 @@ public: { subscribeInfo_ = subscribeInfo; } + + const std::string& GetExtra() const + { + return extra_; + } + + void SetExtra(std::string &extra) + { + extra_ = extra; + } private: + std::string extra_; DmSubscribeInfo subscribeInfo_; }; } // namespace DistributedHardware 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..aaf6054f1 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 @@ -109,15 +109,37 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + IpcIoInit(&request, buffer, buffLen, 0); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + + int32_t size = 0; + DmDeviceInfo* dmDeviceInfo = (DmDeviceInfo *)IpcIoPopFlatObj(&reply, &size); + if (dmDeviceInfo != nullptr) { + pRsp->SetLocalDeviceInfo(*dmDeviceInfo); + } + pRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + 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; } diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index 498d872e7..ca049c1d2 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -35,7 +35,7 @@ public: static DeviceManagerService & GetInstance(); public: int32_t Init(); - int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); + int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList, const std::string &extra,); int32_t GetLocalDeviceInfo(DmDeviceInfo &info); int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra); int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId); diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h index 36edc2c18..77fe61dc5 100644 --- a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h @@ -27,15 +27,14 @@ namespace OHOS { namespace DistributedHardware { class DmDeviceInfoManager { public: - DmDeviceInfoManager(std::shared_ptr softbusConnectorPtr); - ~DmDeviceInfoManager(); + 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 softbusConnectorPtr_; std::shared_ptr adapterMgrPtr_; }; } // namespace DistributedHardware } // namespace OHOS + #endif // OHOS_DM_DEVICEINFO_MANAGER_H diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 657d65957..abf7b2e89 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace DistributedHardware { - SoftbusConnector::SoftbusConnector() { DMLOG(DM_LOG_INFO,"SoftbusConnector constructor"); diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index a8b49b9f9..608c3490a 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -87,11 +87,11 @@ int32_t DeviceManagerService::Init() return DM_OK; } -int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList, const std::string &extra) { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, singleton not init or init fail"); - return ERROR_NOT_INIT; + return DM_NOT_INIT; } if (pkgName.empty()) { @@ -105,7 +105,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "GetLocalDeviceInfo failed, singleton not init or init fail"); - return ERROR_NOT_INIT; + return DM_NOT_INIT; } return deviceInfoMgrPtr_->GetLocalDeviceInfo(info); @@ -115,7 +115,7 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, singleton not init or init fail"); - return ERROR_NOT_INIT; + return DM_NOT_INIT; } if (pkgName.empty()) { @@ -129,7 +129,7 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, singleton not init or init fail"); - return ERROR_NOT_INIT; + return DM_NOT_INIT; } if (pkgName.empty()) { @@ -143,7 +143,7 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, singleton not init or init fail"); - return ERROR_NOT_INIT; + return DM_NOT_INIT; } if (pkgName.empty()) { @@ -162,7 +162,7 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, singleton not init or init fail"); - return ERROR_NOT_INIT; + return DM_NOT_INIT; } if (pkgName.empty()) { @@ -180,7 +180,7 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, singleton not init or init fail"); - return ERROR_NOT_INIT; + return DM_NOT_INIT; } if (pkgName.empty()) { diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 2438e6d25..45e0f5f7e 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -20,28 +20,35 @@ namespace OHOS { namespace DistributedHardware { - -DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr softbusConnectorPtr) : softbusConnectorPtr_(softbusConnectorPtr) +DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr& softbusConnectorPtr) : softbusConnectorPtr_(softbusConnectorPtr) { DMLOG(DM_LOG_INFO,"DmDeviceInfoManager constructor"); } int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - IDecisionAdapter decisionAdapter = nullptr; - //TODO:define the extra json format support multi filter algoritme - if (!extra.empty()) { - adapterMgrPtr_ = std::make_shared(); - decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); - } int32_t ret = softbusConnectorPtr_->GetTrustedDeviceList(deviceList); if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed"); return ret; } - if (decisionAdapter != nullptr) { - decisionAdapter->FilterDeviceList(deviceList, extra); + + if (!extra.empty() && !deviceList.empty()) { + adapterMgrPtr_ = std::make_shared(); + if (adapterMgrPtr_ == nullptr) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList adapterMgrPtr_ is nullptr"); + return DM_POINT_NULL; + } + + IDecisionAdapter decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); + if (decisionAdapter != nullptr) { + decisionAdapter->FilterDeviceList(deviceList, extra); + } else { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList decisionAdapter is nullptr"); + return DM_POINT_NULL; + } } + return DM_OK; } @@ -54,6 +61,5 @@ int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info) } return DM_OK; } - -} -} +} // 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 index 83526be74..872c0eb24 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -141,23 +141,6 @@ ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, IpcIo &reply, std::shared_ptr 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); @@ -170,23 +153,46 @@ ON_IPC_SERVER_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, errCode); } +ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) +{ + DMLOG(DM_LOG_INFO, "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, deviceList, extra); + 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) +{ + DMLOG(DM_LOG_INFO, "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) { DMLOG(DM_LOG_INFO, "StartDeviceDiscovery service listener."); - size_t len = 0; - std::string pkgName = (const char *)IpcIoPopString(&req, &len); + 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); + int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo, extra); 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); + std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); uint16_t subscribeId = IpcIoPopUint16(&req); int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); IpcIoPushInt32(&reply, ret); @@ -195,15 +201,33 @@ ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) 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 = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); -// IpcIoPushInt32(&reply, ret); + 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) +{ + DMLOG(DM_LOG_INFO, "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_AUTHENTICATE, IpcIo &req, IpcIo &reply) +{ + DMLOG(DM_LOG_INFO, "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(CHECK_AUTHENTICATION, IpcIo &req, IpcIo &reply) diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index c2d12c256..e4dad5de4 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -228,12 +228,13 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce 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 = DEVICEMANAGER_NULLPTR; if (subscribeInfo != nullptr) { DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); - result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo); + result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo, extra); } if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); @@ -259,6 +260,9 @@ 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(); + DmDeviceInfo *deviceInfo = (DmDeviceInfo *)data.ReadRawData(sizeof(DmDeviceInfo)); int32_t appIconLen = data.ReadInt32(); int32_t appThumbnailLen = data.ReadInt32(); -- Gitee From 334a213a390c59d3d46fc5b5759bb33cf4fdc1fd Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sat, 27 Nov 2021 09:09:07 +0800 Subject: [PATCH 011/110] =?UTF-8?q?=E5=A2=9E=E5=8A=A0ipc=E9=80=9A=E4=BF=A1?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E7=9A=84=E5=A4=B4=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ipc/model/ipc_get_localdevice_rsp.h | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 common/include/ipc/model/ipc_get_localdevice_rsp.h diff --git a/common/include/ipc/model/ipc_get_localdevice_rsp.h b/common/include/ipc/model/ipc_get_localdevice_rsp.h new file mode 100644 index 000000000..e7cea15af --- /dev/null +++ b/common/include/ipc/model/ipc_get_localdevice_rsp.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_GET_LOCALDEVICE_RSP_H +#define OHOS_DM_IPC_GET_LOCALDEVICE_RSP_H + +#include "dm_device_info.h" + +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetLocaldeviceRsp : public IpcRsp { +DECLARE_IPC_MODEL(IpcGetTrustdeviceRsp); +public: + DmDeviceInfo GetLocalDeviceInfo() const + { + return deviceVec_; + } + + void SetLocalDeviceInfo(DmDeviceInfo deviceInfo) + { + localDeviceInfo_ = deviceInfo; + } +private: + DmDeviceInfo localDeviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_GET_LOCALDEVICE_RSP_H -- Gitee From 36f79052c49fd9e6c85eea6de89c7fdb4525b7d0 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sat, 27 Nov 2021 15:27:07 +0800 Subject: [PATCH 012/110] =?UTF-8?q?commom=E7=9B=AE=E5=BD=95L1=E7=9A=84?= =?UTF-8?q?=E7=BC=96=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BUILD.gn | 18 +++++---- common/BUILD.gn | 38 ++++++------------- common/include/constants/dm_constants.h | 2 +- .../ipc/model/ipc_get_localdevice_rsp.h | 2 +- common/include/utils/dm_anonymous.h | 1 + devicemanager.gni | 9 +++-- 6 files changed, 32 insertions(+), 38 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 073e23cdd..b4b2702f8 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. -if (defined(ohos_lite)) { - import("//build/lite/config/component/lite_component.gni") +import("//build/lite/config/component/lite_component.gni") + +if (defined(ohos_lite)) { lite_component("devicemanager_lite") { - features = [ - "utils:devicemanagercommon", - "services/devicemanagerservice:devicemanagerservice", - "interfaces/inner_kits/native_cpp:devicemanagersdk", - ] + if (ohos_kernel_type == "liteos_m") { + } else { + features = [ + "common:devicemanagercommon", + #"services/devicemanagerservice:devicemanagerservice", + #"interfaces/inner_kits/native_cpp:devicemanagersdk", + ] + } } } diff --git a/common/BUILD.gn b/common/BUILD.gn index cb34d5061..a95f94478 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -22,36 +22,25 @@ import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { shared_library("devicemanagercommon") { include_dirs = [ - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "include", - "include/log", - "include/cipher", - "include/ipc/lite", + "include/ipc", + "include/ipc/model", + "include/utils", + "include/constants", + "${innerkits_path}/native_cpp/include", ] include_dirs += [ - "//base/security/deviceauth/interfaces/innerkits", - "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", "//utils/native/lite/include", - "//utils/system/safwk/native/include", - "//third_party/json/include", - "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", "//third_party/bounds_checking_function/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", "//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", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", ] sources = [ - "src/anonymous_string.cpp", - "src/ipc/lite/ipc_cmd_register.cpp", - "src/log/dm_log.cpp", + "src/utils/dm_anonymous.cpp", + "src/utils/dm_log.cpp", + "src/utils/dm_random.cpp", ] defines = [ @@ -61,14 +50,11 @@ if (defined(ohos_lite)) { ] deps = [ + "//utils/native/lite:utils", + "//third_party/bounds_checking_function:libsec_shared", "//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", ] } } else { diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index 296d35d8c..ca1d51a10 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -24,7 +24,7 @@ namespace DistributedHardware { const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; - // const int32_t LOG_MAX_LEN = 512; + 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; diff --git a/common/include/ipc/model/ipc_get_localdevice_rsp.h b/common/include/ipc/model/ipc_get_localdevice_rsp.h index e7cea15af..81b4b0c7d 100644 --- a/common/include/ipc/model/ipc_get_localdevice_rsp.h +++ b/common/include/ipc/model/ipc_get_localdevice_rsp.h @@ -27,7 +27,7 @@ DECLARE_IPC_MODEL(IpcGetTrustdeviceRsp); public: DmDeviceInfo GetLocalDeviceInfo() const { - return deviceVec_; + return localDeviceInfo_; } void SetLocalDeviceInfo(DmDeviceInfo deviceInfo) diff --git a/common/include/utils/dm_anonymous.h b/common/include/utils/dm_anonymous.h index 5ae9757df..e8e55878d 100644 --- a/common/include/utils/dm_anonymous.h +++ b/common/include/utils/dm_anonymous.h @@ -15,6 +15,7 @@ #ifndef OHOS_DM_ANONYMOUS_H #define OHOS_DM_ANONYMOUS_H + #include namespace OHOS { diff --git a/devicemanager.gni b/devicemanager.gni index 9fbc9b19d..e24d59514 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -11,14 +11,17 @@ # See the License for the specific language governing permissions and # limitations under the License. +#------------------------device manager------------------------------# devicemanager_path = "//foundation/distributedhardware/devicemanager" +ext_path = "${devicemanager_path}/ext" common_path = "${devicemanager_path}/common" - services_path = "${devicemanager_path}/services" - innerkits_path = "${devicemanager_path}/interfaces/inner_kits" -ext_path = "${devicemanager_path}/ext" +#--------------------------softbus----------------------------------# + +#---------------------------hichan----------------------------------# +#----------------------compilation options--------------------------# dm_ldflags = [ "-lpthread" ] -- Gitee From be3184388aef25efc98d91662db2e3f44e2785e1 Mon Sep 17 00:00:00 2001 From: puhui Date: Sat, 27 Nov 2021 22:49:40 +0800 Subject: [PATCH 013/110] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/BUILD.gn | 67 +++--- common/include/constants/dm_constants.h | 8 +- ext/ds/BUILD.gn | 1 - ext/profile/BUILD.gn | 1 - interfaces/inner_kits/native_cpp/BUILD.gn | 24 +- .../native_cpp/include/device_manager.h | 20 +- .../include/device_manager_callback.h | 6 +- .../native_cpp/include/device_manager_impl.h | 37 ++- .../native_cpp/include/ipc/ipc_client.h | 4 +- .../native_cpp/include/ipc/ipc_client_proxy.h | 4 +- .../include/ipc/lite/ipc_cmd_register.h | 113 +++++++++ .../include/ipc/standard/ipc_cmd_register.h | 93 +++++++ .../include/notify/device_manager_notify.h | 13 +- .../native_cpp/src/device_manager_impl.cpp | 85 ++++--- .../native_cpp/src/ipc/ipc_client_proxy.cpp | 14 +- .../src/ipc/lite/ipc_client_manager.cpp | 20 +- .../src/ipc/lite/ipc_client_server_proxy.cpp | 22 +- .../src/ipc/lite/ipc_client_stub.cpp | 10 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 49 ++-- .../src/ipc/standard/ipc_client_manager.cpp | 30 +-- .../ipc/standard/ipc_client_server_proxy.cpp | 8 +- .../src/ipc/standard/ipc_client_stub.cpp | 10 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 226 +++++++----------- .../src/notify/device_manager_notify.cpp | 45 ++-- interfaces/kits/js/BUILD.gn | 8 +- .../kits/js/include/native_devicemanager_js.h | 27 +-- interfaces/kits/js/src/dm_native_event.cpp | 2 +- .../kits/js/src/native_devicemanager_js.cpp | 205 ++++++---------- ohos.build | 2 +- services/devicemanagerservice/BUILD.gn | 61 +++-- .../src/ipc/lite/ipc_server_listener.cpp | 4 +- .../src/ipc/lite/ipc_server_listenermgr.cpp | 4 +- .../src/ipc/lite/ipc_server_main.cpp | 4 +- .../src/ipc/lite/ipc_server_stub.cpp | 4 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 7 +- .../src/ipc/standard/ipc_cmd_register.cpp | 4 +- .../ipc/standard/ipc_server_client_proxy.cpp | 4 +- .../src/ipc/standard/ipc_server_listener.cpp | 4 +- .../src/ipc/standard/ipc_server_stub.cpp | 4 +- test/unittest/BUILD.gn | 11 +- test/unittest/device_manager_impl_test.cpp | 10 +- utils/BUILD.gn | 123 ++++++++++ utils/include/anonymous_string.h | 26 ++ utils/include/cipher/encrypt_utils.h | 46 ++++ utils/include/ipc/lite/ipc_cmd_register.h | 113 +++++++++ utils/include/ipc/standard/ipc_cmd_register.h | 93 +++++++ 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 | 68 ++++++ utils/src/ipc/standard/ipc_cmd_register.cpp | 55 +++++ utils/src/log/dm_log.cpp | 89 +++++++ 52 files changed, 1536 insertions(+), 603 deletions(-) create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.h create mode 100644 utils/BUILD.gn create mode 100644 utils/include/anonymous_string.h create mode 100644 utils/include/cipher/encrypt_utils.h create mode 100644 utils/include/ipc/lite/ipc_cmd_register.h create mode 100644 utils/include/ipc/standard/ipc_cmd_register.h create mode 100644 utils/include/log/dm_log.h create mode 100644 utils/src/anonymous_string.cpp create mode 100644 utils/src/cipher/encrypt_utils.cpp create mode 100644 utils/src/ipc/lite/ipc_cmd_register.cpp create mode 100644 utils/src/ipc/standard/ipc_cmd_register.cpp create mode 100644 utils/src/log/dm_log.cpp diff --git a/common/BUILD.gn b/common/BUILD.gn index a95f94478..7af38d100 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -22,19 +22,28 @@ import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { shared_library("devicemanagercommon") { include_dirs = [ + "include", + "include/constants", "include/ipc", "include/ipc/model", "include/utils", - "include/constants", - "${innerkits_path}/native_cpp/include", ] include_dirs += [ + "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", "//utils/native/lite/include", - "//third_party/bounds_checking_function/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/ipc/interfaces/innerkits/ipc_core/include", + "//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 = [ @@ -50,58 +59,56 @@ if (defined(ohos_lite)) { ] deps = [ - "//utils/native/lite:utils", - "//third_party/bounds_checking_function:libsec_shared", "//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", + "//utils/native/lite:utils", ] } } else { ohos_shared_library("devicemanagercommon") { include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", +# "//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", "include", - "include/cipher", - "include/log", - "include/ipc/standard", - "//base/security/deviceauth/interfaces/innerkits", - "//base/startup/syspara_lite/adapter/native/syspara/include", - "//third_party/json/include", + "include/constants", + "include/ipc", + "include/ipc/model", + "include/utils", ] sources = [ - "src/anonymous_string.cpp", - "src/cipher/encrypt_utils.cpp", - "src/ipc/standard/ipc_cmd_register.cpp", - "src/log/dm_log.cpp", + "src/utils/dm_anonymous.cpp", + "src/utils/dm_log.cpp", + "src/utils/dm_random.cpp", ] deps = [ - "//third_party/mbedtls:mbedtls_shared", "//utils/native/base:utils", ] defines = [ "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerutils\"", + "DH_LOG_TAG=\"devicemanagercommon\"", "LOG_DOMAIN=0xD004100", ] external_deps = [ "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", - "dsoftbus_standard:softbus_client", +# "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", +# "ipc:ipc_core", +# "safwk:system_ability_fwk", +# "samgr_L2:samgr_proxy", +# "startup_l2:syspara", ] subsystem_name = "distributedhardware" diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index ca1d51a10..a9bea7dad 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -36,8 +36,11 @@ namespace DistributedHardware { DM_NOT_INIT, DM_POINT_NULL, DM_INPUT_PARA_EMPTY, - DM_INPUT_PARA_INVALID, DM_MALLOC_ERROR, + DM_INVALID_VALUE, + DM_IPC_TRANSACTION_FAILED, + DM_IPC_FLATTEN_OBJECT, + DM_IPC_COPY_FAILED, DM_SERVICE_NOT_READY, DM_DEVICE_ALREADY_TRUSTED, DM_HICHAIN_GROUP_CREATE_FAILED, @@ -95,7 +98,6 @@ namespace DistributedHardware { // const int32_t DEVICEMANAGER_MALLOC_ERROR; // const int32_t DEVICEMANAGER_LOCK_ERROR; // const int32_t DEVICEMANAGER_INVALID_PARAM; - // const int32_t DEVICEMANAGER_INVALID_VALUE; // const int32_t DEVICEMANAGER_COPY_FAILED; // const int32_t DEVICEMANAGER_NULLPTR; // const int32_t DEVICEMANAGER_DISCOVERY_FAILED; @@ -121,7 +123,7 @@ namespace DistributedHardware { // const int32_t DEVICEMANAGER_OPEN_SESSION_FAILED; // const int32_t AUTH_PARA_INVALID; // const int32_t ENCODE_DATA_ERROR; - // const int32_t DEVICEMANAGER_OK = 0; + // const int32_t DM_OK = 0; // const int32_t ENCRYPT_TAG_LEN = 32; diff --git a/ext/ds/BUILD.gn b/ext/ds/BUILD.gn index 0d4468cdd..37658245e 100644 --- a/ext/ds/BUILD.gn +++ b/ext/ds/BUILD.gn @@ -62,7 +62,6 @@ shared_library("devicemanagerext") { # "//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", ] } diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn index 0d4468cdd..37658245e 100644 --- a/ext/profile/BUILD.gn +++ b/ext/profile/BUILD.gn @@ -62,7 +62,6 @@ shared_library("devicemanagerext") { # "//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", ] } diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 2903afc98..5313c2aa9 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -25,11 +25,11 @@ if (defined(ohos_lite)) { "include/ipc", "include/ipc/lite", "include/notify", - "${utils_path}/include/log", - "${utils_path}/include/ipc/lite", + "${common_path}/include", + "${common_path}/include/constants", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include", + "${common_path}/include/utils", ] include_dirs += [ "//utils/native/lite/include", @@ -59,7 +59,7 @@ if (defined(ohos_lite)) { ] deps = [ - "${utils_path}:devicemanagerutils", + "${common_path}:devicemanagercommon", "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", "//foundation/communication/ipc_lite:liteipc_adapter", "//foundation/distributedschedule/samgr_lite/samgr:samgr", @@ -70,18 +70,18 @@ if (defined(ohos_lite)) { } else { ohos_shared_library("devicemanagersdk") { include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", "include", - "include/ipc/standard", "include/ipc", + "include/ipc/standard", "include/notify", - "${utils_path}/include/log", + "${common_path}/include", + "${common_path}/include/constants", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${utils_path}/include/ipc/standard", - "${common_path}/include", + "${common_path}/include/utils", "//third_party/json/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", ] sources = [ @@ -96,7 +96,7 @@ if (defined(ohos_lite)) { ] deps = [ - "${utils_path}:devicemanagerutils", + "${common_path}:devicemanagercommon", "//utils/native/base:utils", ] @@ -112,7 +112,7 @@ if (defined(ohos_lite)) { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", + "samgr_L2:samgr_proxy", ] subsystem_name = "distributedhardware" diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 4ce780a5f..903775a61 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -31,18 +31,20 @@ public: public: 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, std::string &extra, - std::vector &deviceList) = 0; - virtual int32_t RegisterDevStateCallback(const std::string &pkgName, std::string &extra, + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) = 0; + virtual int32_t GetLocalDeviceInfo(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, DmSubscribeInfo &subscribeInfo, + virtual int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, 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, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra, std::shared_ptr callback) = 0; - virtual int32_t VerifyAuthentication(const std::string &pkgName, std::string &authPara, - std::shared_ptr callback) = 0; + virtual int32_t StopDeviceDiscovery(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 DmDeviceInfo &deviceInfo) = 0; + virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 8c71697c3..7ad4fb3ed 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -33,9 +33,9 @@ class DeviceStateCallback { public: 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 { @@ -49,13 +49,13 @@ public: class AuthenticateCallback { public: virtual ~AuthenticateCallback() {} - virtual void OnAuthResult(std::string &deviceId, const std::string &token, int32_t status, int32_t reason) = 0; + virtual void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) = 0; }; class VerifyAuthCallback { public: virtual ~VerifyAuthCallback() {} - virtual void OnVerifyAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) = 0; + virtual void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) = 0; }; } // namespace DistributedHardware } // namespace OHOS 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 1b4e95d91..eb8486bd5 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -28,27 +28,24 @@ namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); public: - virtual int32_t InitDeviceManager(std::string &pkgName, + virtual int32_t InitDeviceManager(const 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; + 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(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, + std::shared_ptr callback) override; + virtual int32_t StopDeviceDiscovery(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 DmDeviceInfo &deviceInfo) override; + virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) override; + private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); 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 661229f63..8db238f87 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h @@ -28,8 +28,8 @@ namespace DistributedHardware { class 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 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 8b05a7b70..95866c599 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 @@ -30,8 +30,8 @@ DECLARE_IPC_INTERFACE(IpcClientProxy); public: 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}; diff --git a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h new file mode 100644 index 000000000..36c20961f --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h @@ -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. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H +#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H + +#include +#include + +#include "liteipc_adapter.h" +#include "single_instance.h" + +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) + { + onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); + }; + 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_; + std::unordered_map onIpcCmdFuncMap_; + std::unordered_map onIpcServerCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.h new file mode 100644 index 000000000..dc852f57e --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.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_DEVICE_MANAGER_IPC_CMD_PARSER_H +#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H + +#include +#include + +#include "iremote_broker.h" +#include "single_instance.h" + +#include "ipc_types.h" +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ + static int32_t IpcCmdProcess##cmdCode(paraA, paraB) + +using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); +using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); +using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); + +class IpcCmdRegister { +DECLARE_SINGLE_INSTANCE(IpcCmdRegister); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + int32_t SetRequest(int32_t cmdCode, 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_; + std::unordered_map onIpcCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file 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 45c779ab2..ce933d7e2 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 @@ -43,12 +43,9 @@ public: 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 RegisterVerifyAuthenticationCallback(std::string &pkgName, std::string &authPara, + std::shared_ptr callback); + void UnRegisterVerifyAuthenticationCallback(std::string &pkgName); public: void OnRemoteDied(); void OnDeviceOnline(std::string &pkgName, const DmDeviceInfo &deviceInfo); @@ -60,15 +57,13 @@ public: 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 OnFaCall(std::string &pkgName, std::string ¶mJson); private: std::mutex lock_; std::map> deviceStateCallback_; std::map>> deviceDiscoverCallbacks_; std::map>> authenticateCallback_; - std::map> checkauthcallback_; + std::map> verifyAuthCallback_; std::map> dmInitCallback_; - std::map> dmFaCallback_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 23f7ef2c6..74dc54b92 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,10 +15,9 @@ #include "device_manager_impl.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" #include "device_manager_notify.h" -#include "constants.h" #include "ipc_authenticate_device_req.h" #include "ipc_check_authenticate_req.h" @@ -35,21 +34,21 @@ namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); -int32_t DeviceManagerImpl::InitDeviceManager(std::string &pkgName, std::shared_ptr dmInitCallback) +int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) { DMLOG(DM_LOG_INFO, "DeviceManager::InitDeviceManager start, pkgName: %s", pkgName.c_str()); if (pkgName.empty() || dmInitCallback == nullptr) { DMLOG(DM_LOG_ERROR, "InitDeviceManager error: Invalid parameter"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } int32_t ret = ipcClientProxy_->Init(pkgName); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { return ret; } DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); DMLOG(DM_LOG_INFO, "success"); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::UnInitDeviceManager(std::string &pkgName) @@ -57,16 +56,16 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(std::string &pkgName) DMLOG(DM_LOG_INFO, "DeviceManager::UnInitDeviceManager start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "InitDeviceManager error: Invalid parameter"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } int32_t ret = ipcClientProxy_->UnInit(pkgName); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { return ret; } DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); DMLOG(DM_LOG_INFO, "DeviceManager::UnInitDeviceManager completed with errcode %d", ret); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::GetTrustedDeviceList(std::string &pkgName, std::string &extra, @@ -75,21 +74,21 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(std::string &pkgName, std::strin DMLOG(DM_LOG_INFO, "DeviceManager::GetTrustedDeviceList start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetExtra(extra); - if (ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp) != DEVICEMANAGER_OK) { + if (ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp) != DM_OK) { return DEVICEMANAGER_IPC_FAILED; } - if (rsp->GetErrCode() == DEVICEMANAGER_OK) { + if (rsp->GetErrCode() == DM_OK) { deviceList = rsp->GetDeviceVec(); } DMLOG(DM_LOG_INFO, "DeviceManager::GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::RegisterDevStateCallback(std::string &pkgName, std::string &extra, @@ -98,12 +97,12 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(std::string &pkgName, std::s DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); if (pkgName.empty() || callback == nullptr) { DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::UnRegisterDevStateCallback(std::string &pkgName) @@ -111,12 +110,12 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(std::string &pkgName) DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &subscribeInfo, @@ -125,7 +124,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(std::string &pkgName, DmSubscrib DMLOG(DM_LOG_INFO, "DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); if (pkgName.empty() || callback == nullptr) { DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } DMLOG(DM_LOG_INFO, "DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); @@ -135,16 +134,16 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(std::string &pkgName, DmSubscrib std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetSubscribeInfo(subscribeInfo); - if (ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp) != DEVICEMANAGER_OK) { + if (ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp) != DM_OK) { return DEVICEMANAGER_IPC_FAILED; } int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "DeviceManager StartDeviceDiscovery Failed with ret %d", ret); return ret; } - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::StopDeviceDiscovery(std::string &pkgName, uint16_t subscribeId) @@ -152,7 +151,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(std::string &pkgName, uint16_t su DMLOG(DM_LOG_INFO, "DeviceManager::StopDeviceDiscovery start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } DMLOG(DM_LOG_INFO, "StopDeviceDiscovery in, pkgName %s", pkgName.c_str()); @@ -160,18 +159,18 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(std::string &pkgName, uint16_t su std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetSubscribeId(subscribeId); - if (ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp) != DEVICEMANAGER_OK) { + if (ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp) != DM_OK) { return DEVICEMANAGER_IPC_FAILED; } int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery Failed with ret %d", ret); return ret; } DeviceManagerNotify::GetInstance().UnRegisterDiscoverCallback(pkgName, subscribeId); DMLOG(DM_LOG_INFO, "DeviceManager::StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, @@ -180,7 +179,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(std::string &pkgName, const DmDevi DMLOG(DM_LOG_INFO, "DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } DMLOG(DM_LOG_INFO, "AuthenticateDevice in, pkgName %s", pkgName.c_str()); @@ -190,19 +189,19 @@ int32_t DeviceManagerImpl::AuthenticateDevice(std::string &pkgName, const DmDevi req->SetExtra(extra); req->SetDeviceInfo(deviceInfo); req->SetAppImageInfo(imageInfo); - if (ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp) != DEVICEMANAGER_OK) { + if (ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { return DEVICEMANAGER_IPC_FAILED; } int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice Failed with ret %d", ret); return ret; } 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; + return DM_OK; } int32_t DeviceManagerImpl::CheckAuthentication(std::string &pkgName, std::string &authPara, @@ -211,25 +210,25 @@ int32_t DeviceManagerImpl::CheckAuthentication(std::string &pkgName, std::string DMLOG(DM_LOG_INFO, "DeviceManager::CheckAuthentication start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + return DM_INVALID_VALUE; } DMLOG(DM_LOG_INFO, "CheckAuthentication in, pkgName %s", pkgName.c_str()); 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) { + if (ipcClientProxy_->SendRequest(CHECK_AUTHENTICATION, req, rsp) != DM_OK) { return DEVICEMANAGER_IPC_FAILED; } int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "CheckAuthentication 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; + return DM_OK; } int32_t DeviceManagerImpl::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) @@ -238,11 +237,11 @@ int32_t DeviceManagerImpl::GetAuthenticationParam(std::string &pkgName, DmAuthPa std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - if (ipcClientProxy_->SendRequest(SERVER_GET_AUTHENTCATION_INFO, req, rsp) != DEVICEMANAGER_OK) { + if (ipcClientProxy_->SendRequest(SERVER_GET_AUTHENTCATION_INFO, req, rsp) != DM_OK) { return DEVICEMANAGER_IPC_FAILED; } authParam = rsp->GetAuthParam(); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action) @@ -254,15 +253,15 @@ int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action req->SetPkgName(pkgName); req->SetOperation(action); - if (ipcClientProxy_->SendRequest(SERVER_USER_AUTHORIZATION_OPERATION, req, rsp) != DEVICEMANAGER_OK) { + if (ipcClientProxy_->SendRequest(SERVER_USER_AUTHORIZATION_OPERATION, req, rsp) != DM_OK) { return DEVICEMANAGER_IPC_FAILED; } int32_t ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "CheckAuthentication Failed with ret %d", ret); return ret; } - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(std::string &packageName, @@ -271,11 +270,11 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(std::string &packageN 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; + return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(packageName, callback); DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback completed, pkgName: %s", packageName.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(std::string &pkgName) @@ -283,11 +282,11 @@ int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(std::string &pkgNam 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; + return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + 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..b261b2a6c 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 @@ -15,23 +15,23 @@ #include "ipc_client_proxy.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.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); } @@ -40,7 +40,7 @@ int32_t IpcClientProxy::SendRequest(int32_t cmdCode, std::shared_ptr req { if (req == nullptr || rsp == nullptr || ipcClientManager_ == nullptr) { DMLOG(DM_LOG_INFO, "req,rsp or ipc client is null"); - return DEVICEMANAGER_NULLPTR; + 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..34966d33a 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 @@ -15,8 +15,8 @@ #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" @@ -27,13 +27,13 @@ int32_t IpcClientManager::Init(std::string &pkgName) { if (IsInit(pkgName)) { DMLOG(DM_LOG_INFO, "already init"); - return DEVICEMANAGER_OK; + return DM_OK; } - if (serverProxy_.Init() != DEVICEMANAGER_OK) { + if (serverProxy_.Init() != DM_OK) { DMLOG(DM_LOG_ERROR, "server proxy init failed."); return DEVICEMANAGER_INIT_FAILED; } - if (IpcClientStub::GetInstance().Init() != DEVICEMANAGER_OK) { + if (IpcClientStub::GetInstance().Init() != DM_OK) { DMLOG(DM_LOG_ERROR, "ipcclientstub init failed."); return DEVICEMANAGER_INIT_FAILED; } @@ -43,17 +43,17 @@ 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) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); return ret; } ret = rsp->GetErrCode(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "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) @@ -66,13 +66,13 @@ int32_t IpcClientManager::UnInit(std::string &pkgName) 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) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); return ret; } packageInitSet_.erase(pkgName); DMLOG(DM_LOG_INFO, "UnInitDeviceManager SUCCESS"); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) 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..1706784ef 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 @@ -15,8 +15,8 @@ #include "ipc_client_server_proxy.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" #include "device_manager_notify.h" #include "ipc_def.h" @@ -50,7 +50,7 @@ int32_t DMDeathCallback(const IpcContext *ctx, void *ipcMsg, IpcIo *data, void * 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) @@ -59,7 +59,7 @@ static int32_t SendCmdResultCb(IOwner owner, int32_t code, IpcIo *reply) int32_t cmdCode = *(int32_t *)owner; DMLOG(DM_LOG_INFO, "SendCmdResultCb code:%d", cmdCode); (void)IpcCmdRegister::GetInstance().ReadResponse(cmdCode, *reply, pCurRsp); - return DEVICEMANAGER_OK; + return DM_OK; } IClientProxy *IpcClientServerProxy::GetServerProxy(void) @@ -72,7 +72,7 @@ IClientProxy *IpcClientServerProxy::GetServerProxy(void) 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"); } @@ -87,7 +87,7 @@ int IpcClientServerProxy::RegisterServerDeathCb(void) DMLOG(DM_LOG_ERROR, "reg death callback failed"); return DEVICEMANAGER_FAILED; } - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) @@ -96,7 +96,7 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r uint8_t data[MAX_DM_IPC_LEN] = {0}; IpcIo request; - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, request, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, request, data, MAX_DM_IPC_LEN) != DM_OK) { return DEVICEMANAGER_FAILED; } { @@ -109,14 +109,14 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r } } DMLOG(DM_LOG_INFO, "SendCmd:%d end", cmdCode); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcClientServerProxy::Init(void) { if (serviceProxy_ != nullptr) { DMLOG(DM_LOG_INFO, "ServerProxy already Init"); - return DEVICEMANAGER_OK; + return DM_OK; } HOS_SystemInit(); serviceProxy_ = GetServerProxy(); @@ -124,12 +124,12 @@ int32_t IpcClientServerProxy::Init(void) DMLOG(DM_LOG_ERROR, "get ipc client proxy failed"); return DEVICEMANAGER_FAILED; } - if (RegisterServerDeathCb() != DEVICEMANAGER_OK) { + if (RegisterServerDeathCb() != DM_OK) { DMLOG(DM_LOG_ERROR, "register server death cb failed"); return DEVICEMANAGER_FAILED; } DMLOG(DM_LOG_INFO, "ServerProxyInit ok"); - return DEVICEMANAGER_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..1eab12e20 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 @@ -15,8 +15,8 @@ #include "ipc_client_stub.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" #include "device_manager_notify.h" #include "ipc_def.h" @@ -36,7 +36,7 @@ static int32_t ClientIpcInterfaceMsgHandle(const IpcContext *ctx, void *ipcMsg, 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); @@ -48,14 +48,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; } 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 aaf6054f1..14959faea 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 @@ -17,9 +17,8 @@ #include "ipc_def.h" #include "securec.h" -#include "constants.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" #include "device_manager_notify.h" #include "dm_device_info.h" @@ -47,13 +46,13 @@ 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, @@ -63,13 +62,13 @@ ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr p 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, @@ -82,7 +81,7 @@ ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, IpcI 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) @@ -106,14 +105,14 @@ 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 DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, IpcIo &reply, std::shared_ptr pBaseRsp) @@ -126,7 +125,7 @@ ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, IpcIo &reply, std::shared_ptrSetLocalDeviceInfo(*dmDeviceInfo); } pRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, @@ -141,13 +140,13 @@ ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcI 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, @@ -160,13 +159,13 @@ 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, @@ -182,13 +181,13 @@ 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, @@ -199,13 +198,13 @@ ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, IpcIo 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) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply) @@ -260,7 +259,7 @@ ON_IPC_CMD(SERVER_DISCOVER_FINISH, IpcIo &reply) DMLOG(DM_LOG_ERROR, "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); @@ -308,7 +307,7 @@ ON_IPC_SET_REQUEST(SERVER_GET_AUTHENTCATION_INFO, std::shared_ptr pBaseR IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, packagename.c_str()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, IpcIo& reply, std::shared_ptr pBaseRsp) @@ -320,7 +319,7 @@ ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, IpcIo& reply, std::shared_pt if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { authParam.pinToken = IpcIoPopInt32(&reply); pRsp->SetAuthParam(authParam); - return DEVICEMANAGER_OK; + return DM_OK; } size_t PackagerNamelen = 0; authParam.packageName = strdup((const char *)IpcIoPopString(&reply, &PackagerNamelen)); @@ -345,7 +344,7 @@ ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, IpcIo& reply, std::shared_pt authParam.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); pRsp->SetAuthParam(authParam); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr pBaseReq, IpcIo& request, @@ -358,13 +357,13 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, pkgName.c_str()); IpcIoPushInt32(&request, action); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) 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..1813dc860 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 @@ -20,8 +20,8 @@ #include "iservice_registry.h" #include "system_ability_definition.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" #include "device_manager_notify.h" #include "ipc_register_listener_req.h" @@ -40,19 +40,19 @@ int32_t IpcClientManager::ClientInit() DMLOG(DM_LOG_INFO, "InitDeviceManagerService start"); if (dmInterface_ != nullptr) { DMLOG(DM_LOG_INFO, "DeviceManagerService Already Init"); - return DEVICEMANAGER_OK; + return DM_OK; } auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { DMLOG(DM_LOG_ERROR, "Get SystemAbilityManager Failed"); - return DEVICEMANAGER_SERVICE_NOT_READY; + 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; + return DM_SERVICE_NOT_READY; } if (dmRecipient_ == nullptr) { @@ -63,20 +63,20 @@ int32_t IpcClientManager::ClientInit() } dmInterface_ = iface_cast(object); DMLOG(DM_LOG_INFO, "DeviceManager::InitDeviceManagerService completed"); - return DEVICEMANAGER_OK; + return DM_OK; } int32_t IpcClientManager::Init(std::string &pkgName) { std::lock_guard autoLock(lock_); int32_t ret = ClientInit(); - if (ret != DEVICEMANAGER_OK) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "InitDeviceManager Failed with ret %d", ret); return ret; } if (dmListener_.count(pkgName) > 0) { DMLOG(DM_LOG_INFO, "dmListener_ Already Init"); - return DEVICEMANAGER_OK; + return DM_OK; } sptr listener = sptr(new IpcClientStub()); @@ -85,17 +85,17 @@ 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) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "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; + return DM_OK; } int32_t IpcClientManager::UnInit(std::string &pkgName) @@ -103,7 +103,7 @@ int32_t IpcClientManager::UnInit(std::string &pkgName) DMLOG(DM_LOG_INFO, "in, pkgName %s", pkgName.c_str()); if (dmInterface_ == nullptr) { DMLOG(DM_LOG_ERROR, "DeviceManager not Init"); - return DEVICEMANAGER_SERVICE_NOT_READY; + return DM_SERVICE_NOT_READY; } std::lock_guard autoLock(lock_); @@ -112,7 +112,7 @@ 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) { + if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); return ret; } @@ -123,14 +123,14 @@ int32_t IpcClientManager::UnInit(std::string &pkgName) dmRecipient_ = nullptr; } DMLOG(DM_LOG_INFO, "completed, pkgName: %s", pkgName.c_str()); - return DEVICEMANAGER_OK; + 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 dmInterface_->SendCmd(cmdCode, req, rsp); } 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..8bb6fe9e5 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 @@ -18,8 +18,8 @@ #include "ipc_cmd_register.h" #include "ipc_types.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { @@ -34,10 +34,10 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r MessageParcel data; MessageParcel reply; MessageOption option; - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DEVICEMANAGER_OK) { + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) { return DEVICEMANAGER_FAILED; } - if (remote->SendRequest(cmdCode, data, reply, option) != DEVICEMANAGER_OK) { + if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); return DEVICEMANAGER_IPC_FAILED; } 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..ea2ad8f74 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 @@ -20,8 +20,8 @@ #include "ipc_cmd_register.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { @@ -29,8 +29,8 @@ int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Messa 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; + if (IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply) == DM_OK) { + return DM_OK; } DMLOG(DM_LOG_WARN, "unsupport code: %d", code); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); @@ -39,7 +39,7 @@ int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Messa int32_t IpcClientStub::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { DMLOG(DM_LOG_ERROR, "error"); - return DEVICEMANAGER_OK; + 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..68938e08b 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 @@ -16,9 +16,8 @@ #include "ipc_cmd_register.h" #include "securec.h" -#include "constants.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" #include "device_manager_notify.h" #include "ipc_def.h" @@ -41,19 +40,19 @@ ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBa sptr listener = pReq->GetListener(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteRemoteObject(listener)) { DMLOG(DM_LOG_ERROR, "write listener failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + 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) @@ -61,15 +60,15 @@ ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr p std::string pkgName = pBaseReq->GetPkgName(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write papam failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + 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) @@ -79,13 +78,13 @@ ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, Mess std::string extra = pReq->GetExtra(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkg failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteString(extra)) { DMLOG(DM_LOG_ERROR, "write extra failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + 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) @@ -98,8 +97,8 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, MessageParcel &reply, std::shared_pt 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; + pRsp->SetErrCode(DM_IPC_TRANSACTION_FAILED); + return DM_IPC_TRANSACTION_FAILED; } for (int32_t i = 0; i < deviceNum; ++i) { pDmDeviceinfo = pDmDeviceinfo + i; @@ -108,7 +107,7 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, MessageParcel &reply, std::shared_pt pRsp->SetDeviceVec(deviceInfoVec); } pRsp->SetErrCode(reply.ReadInt32()); - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) @@ -118,19 +117,19 @@ ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, Mess const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo))) { DMLOG(DM_LOG_ERROR, "write subscribe info failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + 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) @@ -140,19 +139,19 @@ ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, Messa uint16_t subscribeId = pReq->GetSubscribeId(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteInt16(subscribeId)) { DMLOG(DM_LOG_ERROR, "write subscribeId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + 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) @@ -165,41 +164,41 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteString(extra)) { DMLOG(DM_LOG_ERROR, "write extra failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + 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; + return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteInt32(appThumbnailLen)) { DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnailLen failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + 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_IPC_FLATTEN_OBJECT; } if (appThumbnailLen > 0 && !data.WriteRawData(imageInfo.GetAppThumbnail(), appThumbnailLen)) { DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnail failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_FLATTEN_OBJECT; } - return DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(AUTHENTICATE_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) @@ -207,15 +206,15 @@ ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, Messa 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 DEVICEMANAGER_OK; + return DM_OK; } ON_IPC_READ_RESPONSE(CHECK_AUTHENTICATION, 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 +225,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: @@ -243,8 +242,8 @@ ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply DMLOG(DM_LOG_ERROR, "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 +254,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,13 +268,13 @@ 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); } - reply.WriteInt32(DEVICEMANAGER_OK); - return DEVICEMANAGER_OK; + reply.WriteInt32(DM_OK); + return DM_OK; } ON_IPC_CMD(SERVER_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) @@ -287,104 +286,59 @@ ON_IPC_CMD(SERVER_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) int32_t reason = data.ReadInt32(); DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, pinToken, status, reason); - reply.WriteInt32(DEVICEMANAGER_OK); - return DEVICEMANAGER_OK; + 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; + DeviceManagerNotify::GetInstance().OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); + reply.WriteInt32(DM_OK); + return DM_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; -} - -ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_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)) { - 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; - } - 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 DM_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 DM_OK; +//} + +//ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +//{ +// pBaseRsp->SetErrCode(reply.ReadInt32()); +// 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..2a324bd11 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 @@ -15,43 +15,42 @@ #include "device_manager_notify.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" #include "nlohmann/json.hpp" -#include "constants.h" #include "device_manager.h" namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); -void DeviceManagerNotify::RegisterDeathRecipientCallback(std::string &pkgName, +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, +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, +void DeviceManagerNotify::RegisterDiscoverCallback(const std::string &pkgName, uint16_t subscribeId, std::shared_ptr callback) { std::lock_guard autoLock(lock_); @@ -61,7 +60,7 @@ void DeviceManagerNotify::RegisterDiscoverCallback(std::string &pkgName, uint16_ deviceDiscoverCallbacks_[pkgName][subscribeId] = callback; } -void DeviceManagerNotify::UnRegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId) +void DeviceManagerNotify::UnRegisterDiscoverCallback(const std::string &pkgName, uint16_t subscribeId) { std::lock_guard autoLock(lock_); if (deviceDiscoverCallbacks_.count(pkgName) > 0) { @@ -72,7 +71,7 @@ void DeviceManagerNotify::UnRegisterDiscoverCallback(std::string &pkgName, uint1 } } -void DeviceManagerNotify::RegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId, +void DeviceManagerNotify::RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, std::shared_ptr callback) { std::lock_guard autoLock(lock_); @@ -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,7 +92,7 @@ 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); @@ -103,32 +102,18 @@ void DeviceManagerNotify::UnRegisterPackageCallback(std::string &pkgName) } void DeviceManagerNotify::RegisterCheckAuthenticationCallback(std::string &pkgName, std::string &authPara, - std::shared_ptr callback) + 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); -} - -void DeviceManagerNotify::RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback) -{ - std::lock_guard autoLock(lock_); - dmFaCallback_[packageName] = callback; + verifyAuthCallback_.erase(pkgName); } -void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(std::string &pkgName) -{ - std::lock_guard autoLock(lock_); - dmFaCallback_.erase(pkgName); -} - - void DeviceManagerNotify::OnRemoteDied() { DMLOG(DM_LOG_WARN, "DeviceManager : OnRemoteDied"); diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 3ed612208..b5843f4a2 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -18,13 +18,13 @@ ohos_shared_library("devicemanager") { include_dirs = [ "//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", "${common_path}/include/ipc", + "${common_path}/include/utils", "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/standard", ] @@ -35,7 +35,7 @@ ohos_shared_library("devicemanager") { ] deps = [ - "${utils_path}:devicemanagerutils", + "${common_path}:devicemanagercommon", "//foundation/ace/napi:ace_napi", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//utils/native/base:utils", @@ -53,7 +53,7 @@ ohos_shared_library("devicemanager") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", + "samgr_L2:samgr_proxy", ] subsystem_name = "distributedhardware" diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 554418cf5..c18853446 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -20,11 +20,11 @@ #include #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "nlohmann/json.hpp" #include "device_manager_callback.h" #include "dm_native_event.h" #include "dm_device_info.h" #include "dm_subscribe_info.h" -#include "nlohmann/json.hpp" #include "dm_device_info.h" #define DM_NAPI_BUF_LENGTH (256) @@ -106,21 +106,11 @@ private: std::string bundleName_; }; -class DmNapiCheckAuthCallback : public OHOS::DistributedHardware::CheckAuthCallback { -public: - explicit DmNapiCheckAuthCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiCheckAuthCallback() {}; - void OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) 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(std::string &deviceId, int32_t resultCode, int32_t flag) override; private: std::string bundleName_; @@ -141,9 +131,9 @@ public: 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 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); @@ -183,7 +173,6 @@ public: void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason); void OnAuthResult(const std::string &deviceId, int32_t pinToken, 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); diff --git a/interfaces/kits/js/src/dm_native_event.cpp b/interfaces/kits/js/src/dm_native_event.cpp index 70084134b..3a8b7d16f 100644 --- a/interfaces/kits/js/src/dm_native_event.cpp +++ b/interfaces/kits/js/src/dm_native_event.cpp @@ -15,7 +15,7 @@ #include "dm_native_event.h" -#include "device_manager_log.h" +#include "dm_log.h" using namespace OHOS::DistributedHardware; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index bb38a37fd..b6e6d5bf4 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -19,8 +19,8 @@ #include "nlohmann/json.hpp" #include "device_manager.h" -#include "device_manager_log.h" -#include "constants.h" +#include "dm_log.h" +#include "dm_constants.h" using namespace OHOS::DistributedHardware; @@ -56,8 +56,7 @@ std::map> g_initCallbackMap; std::map> g_deviceStateCallbackMap; std::map> g_discoverCallbackMap; std::map> g_authCallbackMap; -std::map> g_checkAuthCallbackMap; -std::map> g_dmfaCallbackMap; +std::map> g_checkAuthCallbackMap; } napi_ref DeviceManagerNapi::sConstructor_ = nullptr; @@ -172,7 +171,7 @@ void DmNapiAuthenticateCallback::OnAuthResult(std::string &deviceId, int32_t pin deviceManagerNapi->OnAuthResult(deviceId, pinToken, status, reason); } -void DmNapiCheckAuthCallback::OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) +void DmNapiCheckAuthCallback::OnVerifyAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { @@ -182,16 +181,6 @@ void DmNapiCheckAuthCallback::OnCheckAuthResult(std::string &deviceId, int32_t r 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; @@ -542,40 +531,40 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & info.deviceTypeId = (DMDeviceType)deviceType; } -void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const napi_value &object, - DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) -{ - DMLOG(DM_LOG_INFO, "JsToDmAppImageInfoAndDmExtra in."); - int32_t authTypeTemp = -1; - JsObjectToInt(env, object, "authType", authTypeTemp); - authType = authTypeTemp; - - uint8_t *appIconBufferPtr = nullptr; - int32_t appIconBufferLen = 0; - JsToDmBuffer(env, object, "appIcon", &appIconBufferPtr, appIconBufferLen); - - uint8_t *appThumbnailBufferPtr = nullptr; - int32_t appThumbnailBufferLen = 0; - JsToDmBuffer(env, object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); - - appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); - if (appIconBufferPtr != nullptr) { - free(appIconBufferPtr); - appIconBufferPtr = nullptr; - } - if (appThumbnailBufferPtr != nullptr) { - free(appThumbnailBufferPtr); - appThumbnailBufferPtr = nullptr; - } - - nlohmann::json jsonObj; - jsonObj[AUTH_TYPE] = authType; - std::string extraInfo = "extraInfo"; - - JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(); - DMLOG(DM_LOG_INFO, "appIconLen %d, appThumbnailLen %d", appIconBufferLen, appThumbnailBufferLen); -} +//void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const napi_value &object, +// DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) +//{ +// DMLOG(DM_LOG_INFO, "JsToDmAppImageInfoAndDmExtra in."); +// int32_t authTypeTemp = -1; +// JsObjectToInt(env, object, "authType", authTypeTemp); +// authType = authTypeTemp; +// +// uint8_t *appIconBufferPtr = nullptr; +// int32_t appIconBufferLen = 0; +// JsToDmBuffer(env, object, "appIcon", &appIconBufferPtr, appIconBufferLen); +// +// uint8_t *appThumbnailBufferPtr = nullptr; +// int32_t appThumbnailBufferLen = 0; +// JsToDmBuffer(env, object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); +// +// appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); +// if (appIconBufferPtr != nullptr) { +// free(appIconBufferPtr); +// appIconBufferPtr = nullptr; +// } +// if (appThumbnailBufferPtr != nullptr) { +// free(appThumbnailBufferPtr); +// appThumbnailBufferPtr = nullptr; +// } +// +// nlohmann::json jsonObj; +// jsonObj[AUTH_TYPE] = authType; +// std::string extraInfo = "extraInfo"; +// +// JsToJsonObject(env, object, "extraInfo", jsonObj); +// extra = jsonObj.dump(); +// DMLOG(DM_LOG_INFO, "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) @@ -726,20 +715,6 @@ void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &e discoverCallback->IncreaseRefCount(); return; } - - if (eventType == DM_NAPI_EVENT_DMFA_CALLBACK) { - auto iter = g_dmfaCallbackMap.find(bundleName); - if (iter == g_dmfaCallbackMap.end()) { - 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()); - return; - } - g_dmfaCallbackMap[bundleName] = callback; - } - return; - } } void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string &eventType) @@ -773,71 +748,34 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & } return; } - - 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()); - return; - } - int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); - return; - } - g_dmfaCallbackMap.erase(bundleName); - return; - } -} - -napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_info info) -{ - DMLOG(DM_LOG_INFO, "SetUserOperationSync in"); - GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[0], &valueType); - NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Object expected."); - - int32_t action = 0; - napi_get_value_int32(env, argv[0], &action); - DeviceManagerNapi *deviceManagerWrapper = nullptr; - 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); - } - napi_value result = nullptr; - napi_get_undefined(env, &result); - return result; } -napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_callback_info info) -{ - DMLOG(DM_LOG_INFO, "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().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; - } - - napi_create_object(env, &resultParam); - DmAuthParamToJsAuthParamy(env, authParam, resultParam); - return resultParam; -} +//napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_callback_info info) +//{ +// DMLOG(DM_LOG_INFO, "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().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; +// } +// +// napi_create_object(env, &resultParam); +// DmAuthParamToJsAuthParamy(env, authParam, resultParam); +// return resultParam; +//} napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callback_info info) { @@ -977,12 +915,13 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf DmDeviceInfo deviceInfo; JsToDmDeviceInfo(env, argv[0], deviceInfo); - DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); +// DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); std::string extra; - JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], appImageInfo, extra, authAsyncCallbackInfo_.authType); + JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], extra, authAsyncCallbackInfo_.authType); - int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, deviceInfo, - appImageInfo, extra, authCallback); + //TODO:get real authType + int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, + extra, authCallback); if (ret != 0) { DMLOG(DM_LOG_ERROR, "AuthenticateDevice for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); @@ -1011,10 +950,10 @@ 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; + std::shared_ptr verifyCallback = nullptr; auto iter = g_checkAuthCallbackMap.find(deviceManagerWrapper->bundleName_); if (iter == g_checkAuthCallbackMap.end()) { - verifyCallback = std::make_shared(deviceManagerWrapper->bundleName_); + verifyCallback = std::make_shared(deviceManagerWrapper->bundleName_); g_checkAuthCallbackMap[deviceManagerWrapper->bundleName_] = verifyCallback; } else { verifyCallback = iter->second; @@ -1022,7 +961,7 @@ napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info in std::string authParam; JsToDmAuthInfo(env, argv[0], authParam); - int32_t ret = DeviceManager::GetInstance().CheckAuthentication(deviceManagerWrapper->bundleName_, + int32_t ret = DeviceManager::GetInstance().VerifyAuthentication(deviceManagerWrapper->bundleName_, authParam, verifyCallback); if (ret != 0) { DMLOG(DM_LOG_ERROR, "VerifyAuthInfo for bunderName %s failed, ret %d", diff --git a/ohos.build b/ohos.build index 8630c9844..beca5c3b1 100644 --- a/ohos.build +++ b/ohos.build @@ -19,7 +19,7 @@ } ], "module_list": [ - "//foundation/distributedhardware/devicemanager/utils:devicemanagercommon", + "//foundation/distributedhardware/devicemanager/common:devicemanagercommon", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager_native_js", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice:devicemanagerservice", diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index e9a8782c4..5a0969874 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -24,8 +24,8 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "include/adapter", - "include/adapter/profile", "include/authentication", + "include/authentication/pin_auth", "include/deviceinfo", "include/devicestate", "include/discovery", @@ -38,8 +38,8 @@ if (defined(ohos_lite)) { "${common_path}/include/utils", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - # "${innerkits_path}/native_cpp/include", - # "${innerkits_path}/native_cpp/include/ipc/lite", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc/lite", ] include_dirs += [ @@ -60,22 +60,22 @@ if (defined(ohos_lite)) { ] sources = [ - "src/adapter/profile/device_profile_adapter.cpp", + "src/device_manager_service.cpp", + "src/device_manager_service_listener.cpp", "src/adapter/dm_adapter_manager.cpp", + "src/authentication/dm_auth_manager.cpp", "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.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/ipc/ipc_server_adapter.cpp", - "src/ipc/ipc_server_listener_adapter.cpp", + "src/dependency/softbus/softbus_connector.cpp", + "src/dependency/softbus/softbus_session.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/ipc/lite/ipc_cmd_register.cpp", ] defines = [ @@ -85,19 +85,17 @@ if (defined(ohos_lite)) { "LOG_DOMAIN=0xD004100", ] - ldflags = dm_ldflags - deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", - "${utils_path}:devicemanagerutils", + "${common_path}:devicemanagercommon", "//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", + "//third_party/bounds_checking_function:libsec_shared", +# "//third_party/mbedtls:mbedtls_shared", "//utils/native/lite:utils", ] } @@ -106,53 +104,52 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "include/adapter", - "include/adapter/profile", "include/authentication", + "include/authentication/pin_auth", "include/deviceinfo", "include/devicestate", "include/discovery", "include/dependency/hichain", "include/dependency/softbus", - "include/ipc/standard", + "include/ipc", + "include/ipc/lite", "${common_path}/include", "${common_path}/include/constants", "${common_path}/include/utils", "${common_path}/include/ipc", "${common_path}/include/ipc/model", "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/ipc/standard", + "${innerkits_path}/native_cpp/include/ipc/lite", + "//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", - "//utils/native/base/include", - "//utils/system/safwk/native/include", ] sources = [ - "src/adapter/profile/device_profile_adapter.cpp", + "src/device_manager_service.cpp", + "src/device_manager_service_listener.cpp", "src/adapter/dm_adapter_manager.cpp", + "src/authentication/dm_auth_manager.cpp", "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.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/ipc/ipc_server_adapter.cpp", - "src/ipc/ipc_server_listener_adapter.cpp", + "src/dependency/softbus/softbus_connector.cpp", + "src/dependency/softbus/softbus_session.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_client_proxy.cpp", "src/ipc/standard/ipc_server_stub.cpp", + "src/ipc/standard/ipc_cmd_register.cpp", ] deps = [ - "${innerkits_path}/native_cpp:devicemanagersdk", - "${common_path}:devicemanagercommon", "//base/security/deviceauth/services:deviceauth_sdk", - # "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/want:want", - # "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//utils/native/base:utils", ] @@ -169,8 +166,8 @@ if (defined(ohos_lite)) { "dsoftbus_standard:softbus_client", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - # "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", "startup_l2:syspara", ] diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp index cd2964c31..7a5083f4b 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -15,8 +15,8 @@ #include "ipc_server_listener.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" #include "ipc_cmd_register.h" #include "ipc_def.h" diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp index 3fe943d9c..c54d83827 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp @@ -15,8 +15,8 @@ #include "ipc_server_listenermgr.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp index fc2848839..7edf7eea4 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp @@ -16,8 +16,8 @@ #include #include -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" #include "ipc_server_stub.h" #include "ipc_server_adapter.h" diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp index da69cc39a..aeff02448 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -22,8 +22,8 @@ #include "samgr_lite.h" #include "iproxy_server.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" #include "dm_subscribe_info.h" #include "ipc_cmd_register.h" diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index e4dad5de4..5e7d1a879 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "constants.h" +#include #include "ipc_cmd_register.h" #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" @@ -21,12 +21,11 @@ #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" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp index e958dfd04..741a250e2 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp @@ -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 { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp index 16ab7d0da..a5e959d17 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp @@ -19,8 +19,8 @@ #include "ipc_cmd_register.h" #include "ipc_def.h" -#include "device_manager_log.h" -#include "device_manager_errno.h" +#include "dm_log.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp index fd9391561..6b282da4d 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp @@ -16,8 +16,8 @@ #include "ipc_server_listener.h" #include "ipc_server_stub.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp index bf259a6d8..0675cb8bc 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -25,8 +25,8 @@ #include "string_ex.h" #include "system_ability_definition.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "dm_constants.h" +#include "dm_log.h" // #include "ipc_server_adapter.h" #include "ipc_cmd_register.h" diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 9c2c9dcce..515cf57f2 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -41,12 +41,13 @@ config("device_manager_test_common_public_config") { "//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", + "//third_party/json/include", + "${common_path}/include", + "${common_path}/include/constants", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${utils_path}/include/ipc/standard", - "${common_path}/include", - "//third_party/json/include", + "${common_path}/include/utils", + ] cflags = [ @@ -66,7 +67,7 @@ ohos_static_library("device_manager_test_common") { public_configs = [ ":device_manager_test_common_public_config" ] public_deps = [ - "${utils_path}:devicemanagerutils", + "${common_path}:devicemanagercommon", "//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", diff --git a/test/unittest/device_manager_impl_test.cpp b/test/unittest/device_manager_impl_test.cpp index 620a5cf04..d3c3dd2ae 100644 --- a/test/unittest/device_manager_impl_test.cpp +++ b/test/unittest/device_manager_impl_test.cpp @@ -14,7 +14,7 @@ */ #include "device_manager_impl_test.h" -#include "device_manager_errno.h" +#include "dm_constants.h" #include "dm_device_info.h" #include @@ -42,7 +42,7 @@ 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); + ASSERT_EQ(ret, DM_INVALID_VALUE); } HWTEST_F(DeviceManagerImplTest, AuthenticateDevice1, testing::ext::TestSize.Level0) @@ -54,7 +54,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice1, testing::ext::TestSize.Leve std::shared_ptr callback = nullptr; int32_t ret= DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, dmAppImageInfo, extra, callback); - ASSERT_EQ(ret, DEVICEMANAGER_INVALID_VALUE); + ASSERT_EQ(ret, DM_INVALID_VALUE); } HWTEST_F(DeviceManagerImplTest, AuthenticateDevice2, testing::ext::TestSize.Level0) @@ -97,7 +97,7 @@ HWTEST_F(DeviceManagerImplTest, CheckAuthentication1, testing::ext::TestSize.Lev std::string authPara = ""; std::shared_ptr callback = nullptr; int32_t ret = DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); - ASSERT_EQ(ret, DEVICEMANAGER_INVALID_VALUE); + ASSERT_EQ(ret, DM_INVALID_VALUE); } HWTEST_F(DeviceManagerImplTest, CheckAuthentication2, testing::ext::TestSize.Level0) @@ -134,7 +134,7 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery1, testing::ext::TestSize.Le DmSubscribeInfo subscribeInfo; std::shared_ptr callback = nullptr; int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, callback); - ASSERT_EQ(ret, DEVICEMANAGER_INVALID_VALUE); + ASSERT_EQ(ret, DM_INVALID_VALUE); } HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, testing::ext::TestSize.Level0) diff --git a/utils/BUILD.gn b/utils/BUILD.gn new file mode 100644 index 000000000..a218e443f --- /dev/null +++ b/utils/BUILD.gn @@ -0,0 +1,123 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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)) { + shared_library("devicemanagerutils") { + include_dirs = [ + "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "include", + "include/log", + "include/cipher", + "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/anonymous_string.cpp", + "src/cipher/encrypt_utils.cpp", + "src/ipc/lite/ipc_cmd_register.cpp", + "src/log/dm_log.cpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerutils\"", + "LOG_DOMAIN=0xD004100", + ] + + 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", + ] + } +} 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", + "//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/ipc/standard/ipc_cmd_register.cpp", + "src/log/dm_log.cpp", + ] + + deps = [ "//utils/native/base:utils" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerutils\"", + "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_L2:samgr_proxy", + "startup_l2:syspara", + ] + + subsystem_name = "distributedhardware" + + part_name = "device_manager_base" + } +} diff --git a/utils/include/anonymous_string.h b/utils/include/anonymous_string.h new file mode 100644 index 000000000..4144e517c --- /dev/null +++ b/utils/include/anonymous_string.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 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 new file mode 100644 index 000000000..db19b2364 --- /dev/null +++ b/utils/include/cipher/encrypt_utils.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_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 new file mode 100644 index 000000000..36c20961f --- /dev/null +++ b/utils/include/ipc/lite/ipc_cmd_register.h @@ -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. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H +#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H + +#include +#include + +#include "liteipc_adapter.h" +#include "single_instance.h" + +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) + { + onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); + }; + 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_; + std::unordered_map onIpcCmdFuncMap_; + std::unordered_map onIpcServerCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..dc852f57e --- /dev/null +++ b/utils/include/ipc/standard/ipc_cmd_register.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_DEVICE_MANAGER_IPC_CMD_PARSER_H +#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H + +#include +#include + +#include "iremote_broker.h" +#include "single_instance.h" + +#include "ipc_types.h" +#include "ipc_req.h" +#include "ipc_rsp.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() \ + { \ + IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ + } \ + }; \ + 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() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ + static int32_t IpcCmdProcess##cmdCode(paraA, paraB) + +using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); +using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); +using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); + +class IpcCmdRegister { +DECLARE_SINGLE_INSTANCE(IpcCmdRegister); +public: + void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) + { + setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); + }; + void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) + { + readResponseFuncMap_.emplace(cmdCode, readResponseFunc); + }; + void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) + { + onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); + }; + int32_t SetRequest(int32_t cmdCode, 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_; + std::unordered_map onIpcCmdFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..1db27040a --- /dev/null +++ b/utils/include/log/dm_log.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_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 new file mode 100644 index 000000000..f5834ee37 --- /dev/null +++ b/utils/src/anonymous_string.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 new file mode 100644 index 000000000..67a39b9c4 --- /dev/null +++ b/utils/src/cipher/encrypt_utils.cpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 new file mode 100644 index 000000000..4fbab5a16 --- /dev/null +++ b/utils/src/ipc/lite/ipc_cmd_register.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_cmd_register.h" + +#include "device_manager_errno.h" +#include "device_manager_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) +{ + 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; + } + return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); +} + +int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + 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; + } + return (readResponseMapIter->second)(reply, pBaseRsp); +} + +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; + } + (onIpcCmdMapIter->second)(reply); + return DEVICEMANAGER_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; + } + (onIpcServerCmdMapIter->second)(req, reply); + return DEVICEMANAGER_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 new file mode 100644 index 000000000..e958dfd04 --- /dev/null +++ b/utils/src/ipc/standard/ipc_cmd_register.cpp @@ -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. + */ + +#include "ipc_cmd_register.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); + +int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) +{ + 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; + } + return (setRequestMapIter->second)(pBaseReq, data); +} + +int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + 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; + } + return (readResponseMapIter->second)(reply, pBaseRsp); +} + +int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &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; + } + return (onIpcCmdMapIter->second)(data, reply); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/src/log/dm_log.cpp b/utils/src/log/dm_log.cpp new file mode 100644 index 000000000..538594b15 --- /dev/null +++ b/utils/src/log/dm_log.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "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 110593a691a32761b7c247c85c39c8c66351e093 Mon Sep 17 00:00:00 2001 From: skypuhui Date: Sun, 28 Nov 2021 03:38:39 +0800 Subject: [PATCH 014/110] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/BUILD.gn | 2 +- common/include/constants/dm_constants.h | 46 +--- common/include/ipc/ipc_def.h | 2 +- .../ipc/model/ipc_authenticate_device_req.h | 2 +- .../ipc/model/ipc_check_authenticate_req.h | 2 +- .../ipc/model/ipc_get_trustdevice_req.h | 2 +- .../ipc/model/ipc_notify_auth_result_req.h | 12 +- .../model/ipc_notify_check_auth_result_req.h | 2 +- .../ipc/model/ipc_notify_device_found_req.h | 2 +- .../ipc/model/ipc_notify_device_state_req.h | 2 +- common/include/ipc/model/ipc_req.h | 2 +- .../ipc/model/ipc_start_discovery_req.h | 4 +- interfaces/inner_kits/native_cpp/BUILD.gn | 2 +- .../native_cpp/include/device_manager.h | 6 +- .../include/device_manager_callback.h | 8 +- .../native_cpp/include/device_manager_impl.h | 6 +- .../include/ipc/standard/ipc_client_manager.h | 4 +- .../include/notify/device_manager_notify.h | 47 ++-- .../native_cpp/src/device_manager_impl.cpp | 109 +++----- .../src/ipc/lite/ipc_cmd_parser.cpp | 2 +- .../src/ipc/standard/ipc_client_manager.cpp | 11 +- .../ipc/standard/ipc_client_server_proxy.cpp | 6 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 8 +- .../src/notify/device_manager_notify.cpp | 94 +++---- interfaces/kits/js/BUILD.gn | 3 +- .../kits/js/include/native_devicemanager_js.h | 24 +- .../kits/js/src/native_devicemanager_js.cpp | 237 +++++++++--------- services/devicemanagerservice/BUILD.gn | 4 +- .../include/authentication/dm_auth_manager.h | 5 +- .../dependency/hichain/hichain_connector.h | 13 +- .../dependency/softbus/softbus_session.h | 4 +- .../include/device_manager_service.h | 16 +- .../include/device_manager_service_listener.h | 15 +- .../src/authentication/dm_auth_manager.cpp | 12 +- .../dependency/hichain/hichain_connector.cpp | 139 +++++----- .../dependency/softbus/softbus_connector.cpp | 6 +- .../src/device_manager_service.cpp | 31 ++- .../src/device_manager_service_listener.cpp | 56 ++--- .../src/deviceinfo/dm_device_info_manager.cpp | 14 +- .../devicestate/dm_device_state_manager.cpp | 2 +- .../src/discovery/dm_discovery_manager.cpp | 1 - test/unittest/device_manager_impl_test.cpp | 12 +- test/unittest/device_manager_impl_test.h | 10 +- utils/BUILD.gn | 2 +- 44 files changed, 431 insertions(+), 558 deletions(-) diff --git a/common/BUILD.gn b/common/BUILD.gn index 7af38d100..07d7ce0f9 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -107,7 +107,7 @@ if (defined(ohos_lite)) { "hiviewdfx_hilog_native:libhilog", # "ipc:ipc_core", # "safwk:system_ability_fwk", -# "samgr_L2:samgr_proxy", +# "samgr_standard:samgr_proxy", # "startup_l2:syspara", ] diff --git a/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h index a9bea7dad..5c2e7e2af 100644 --- a/common/include/constants/dm_constants.h +++ b/common/include/constants/dm_constants.h @@ -41,7 +41,10 @@ namespace DistributedHardware { DM_IPC_TRANSACTION_FAILED, DM_IPC_FLATTEN_OBJECT, DM_IPC_COPY_FAILED, + DM_IPC_SEND_REQUEST_FAILED, DM_SERVICE_NOT_READY, + DM_INT_MULTIPLE, + DM_MAKE_SHARED_FAIL, DM_DEVICE_ALREADY_TRUSTED, DM_HICHAIN_GROUP_CREATE_FAILED, DM_HICHAIN_MEMBER_ADD_FAILED, @@ -50,13 +53,20 @@ namespace DistributedHardware { }; //Softbus - const char *DM_CAPABILITY_OSD = "osdCapability"; + const std::string DM_CAPABILITY_OSD = "osdCapability"; 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_DEVICEINFO_MAX_SIZE = 20; //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 FAIL = -1; // const int32_t SUCCESS = 0; @@ -126,29 +136,6 @@ namespace DistributedHardware { // const int32_t DM_OK = 0; - // 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"; @@ -216,18 +203,7 @@ namespace DistributedHardware { // 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/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 3ba79b9eb..059cc079b 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -49,7 +49,7 @@ enum IpcCmdID { SERVER_DEVICE_FOUND, SERVER_DISCOVER_FINISH, SERVER_AUTH_RESULT, - SERVER_CHECK_AUTH_RESULT, + SERVER_VERIFY_AUTH_RESULT, // SERVER_GET_AUTHENTCATION_INFO, // SERVER_USER_AUTHORIZATION_OPERATION, // SERVER_DEVICEMANAGER_FA_NOTIFY, diff --git a/common/include/ipc/model/ipc_authenticate_device_req.h b/common/include/ipc/model/ipc_authenticate_device_req.h index 47ef2ca0f..e69b04976 100644 --- a/common/include/ipc/model/ipc_authenticate_device_req.h +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -51,7 +51,7 @@ public: return extra_; } - void SetExtra(std::string &extra) + void SetExtra(const std::string &extra) { extra_ = extra; } diff --git a/common/include/ipc/model/ipc_check_authenticate_req.h b/common/include/ipc/model/ipc_check_authenticate_req.h index ef2bd1031..0015534b3 100644 --- a/common/include/ipc/model/ipc_check_authenticate_req.h +++ b/common/include/ipc/model/ipc_check_authenticate_req.h @@ -28,7 +28,7 @@ public: return authPara_; } - void SetAuthPara(std::string &authPara) + void SetAuthPara(const std::string &authPara) { authPara_ = authPara; } diff --git a/common/include/ipc/model/ipc_get_trustdevice_req.h b/common/include/ipc/model/ipc_get_trustdevice_req.h index 442d1e12b..7d78e0fc8 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_req.h +++ b/common/include/ipc/model/ipc_get_trustdevice_req.h @@ -28,7 +28,7 @@ public: return extra_; } - void SetExtra(std::string &extra) + void SetExtra(const std::string &extra) { extra_ = extra; } 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 d6d32cfad..8dfb3ce83 100644 --- a/common/include/ipc/model/ipc_notify_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_auth_result_req.h @@ -30,19 +30,19 @@ public: 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 @@ -66,7 +66,7 @@ public: } private: std::string deviceId_; - int32_t pinToken_ {0}; + std::string token_; int32_t status_ {0}; int32_t reason_ {0}; }; 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 index 21a44eb6d..9499bc0f7 100644 --- a/common/include/ipc/model/ipc_notify_check_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_check_auth_result_req.h @@ -30,7 +30,7 @@ public: return deviceId_; } - void SetDeviceId(std::string& deviceId) + void SetDeviceId(const std::string& deviceId) { deviceId_ = deviceId; } 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 75229b85c..cb51464c9 100644 --- a/common/include/ipc/model/ipc_notify_device_found_req.h +++ b/common/include/ipc/model/ipc_notify_device_found_req.h @@ -30,7 +30,7 @@ public: return dmDeviceInfo_; } - void SetDeviceInfo(DmDeviceInfo& dmDeviceInfo) + void SetDeviceInfo(const DmDeviceInfo& dmDeviceInfo) { dmDeviceInfo_ = dmDeviceInfo; } 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 05e946f01..0cb6cb5bf 100644 --- a/common/include/ipc/model/ipc_notify_device_state_req.h +++ b/common/include/ipc/model/ipc_notify_device_state_req.h @@ -40,7 +40,7 @@ public: return dmDeviceInfo_; } - void SetDeviceInfo(DmDeviceInfo& dmDeviceInfo) + void SetDeviceInfo(const DmDeviceInfo& dmDeviceInfo) { dmDeviceInfo_ = dmDeviceInfo; } diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index bed6b4950..4f2d1bc24 100644 --- a/common/include/ipc/model/ipc_req.h +++ b/common/include/ipc/model/ipc_req.h @@ -30,7 +30,7 @@ public: return pkgName_; } - void SetPkgName(std::string &pkgName) + void SetPkgName(const std::string &pkgName) { pkgName_ = pkgName; } diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h index 1d03b1ce7..5a2918ced 100644 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ b/common/include/ipc/model/ipc_start_discovery_req.h @@ -30,7 +30,7 @@ public: return subscribeInfo_; } - void SetSubscribeInfo(DmSubscribeInfo &subscribeInfo) + void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) { subscribeInfo_ = subscribeInfo; } @@ -40,7 +40,7 @@ public: return extra_; } - void SetExtra(std::string &extra) + void SetExtra(const std::string &extra) { extra_ = extra; } diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 5313c2aa9..eb0422718 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -112,7 +112,7 @@ if (defined(ohos_lite)) { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "distributedhardware" diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 903775a61..c92edcd0e 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -37,9 +37,9 @@ public: 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, - std::shared_ptr callback) = 0; - virtual int32_t StopDeviceDiscovery(uint16_t subscribeId) = 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 DmDeviceInfo &deviceInfo) = 0; 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 7ad4fb3ed..2892970c3 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -38,11 +38,11 @@ public: virtual void OnDeviceReady(const DmDeviceInfo &deviceInfo) = 0; }; -class DiscoverCallback { +class DiscoveryCallback { public: - virtual ~DiscoverCallback() {} - // virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; - virtual void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) = 0; + virtual ~DiscoveryCallback() {} + virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; + virtual void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) = 0; virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) = 0; }; 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 eb8486bd5..5b2899d18 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -37,9 +37,9 @@ public: 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, - std::shared_ptr callback) override; - virtual int32_t StopDeviceDiscovery(uint16_t subscribeId) 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 DmDeviceInfo &deviceInfo) override; 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 e2ea1cc26..548686e9c 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 @@ -41,8 +41,8 @@ class IpcClientManager : public IpcClient { 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); 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 ce933d7e2..0dc82bfd6 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 @@ -32,35 +32,34 @@ namespace DistributedHardware { class 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 RegisterVerifyAuthenticationCallback(std::string &pkgName, std::string &authPara, - std::shared_ptr callback); - void UnRegisterVerifyAuthenticationCallback(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); 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 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); private: std::mutex lock_; std::map> deviceStateCallback_; - std::map>> deviceDiscoverCallbacks_; + std::map>> deviceDiscoveryCallbacks_; std::map>> authenticateCallback_; std::map> verifyAuthCallback_; std::map> dmInitCallback_; 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 74dc54b92..2b19918c0 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -51,7 +51,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh 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()); if (pkgName.empty()) { @@ -68,8 +68,8 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(std::string &pkgName) 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()); if (pkgName.empty()) { @@ -82,7 +82,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(std::string &pkgName, std::strin req->SetPkgName(pkgName); req->SetExtra(extra); if (ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } if (rsp->GetErrCode() == DM_OK) { deviceList = rsp->GetDeviceVec(); @@ -91,7 +91,12 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(std::string &pkgName, std::strin return DM_OK; } -int32_t DeviceManagerImpl::RegisterDevStateCallback(std::string &pkgName, std::string &extra, +int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) +{ + return DM_OK; +} + +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()); @@ -105,7 +110,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(std::string &pkgName, std::s 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()); if (pkgName.empty()) { @@ -118,8 +123,8 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(std::string &pkgName) 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()); if (pkgName.empty() || callback == nullptr) { @@ -128,14 +133,14 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(std::string &pkgName, DmSubscrib } DMLOG(DM_LOG_INFO, "DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); - DeviceManagerNotify::GetInstance().RegisterDiscoverCallback(pkgName, subscribeInfo.subscribeId, callback); + 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->SetSubscribeInfo(subscribeInfo); if (ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -146,7 +151,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(std::string &pkgName, DmSubscrib 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()); if (pkgName.empty()) { @@ -160,7 +165,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(std::string &pkgName, uint16_t su req->SetPkgName(pkgName); req->SetSubscribeId(subscribeId); if (ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -168,13 +173,13 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(std::string &pkgName, uint16_t su DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery Failed with ret %d", ret); return ret; } - DeviceManagerNotify::GetInstance().UnRegisterDiscoverCallback(pkgName, subscribeId); + DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); DMLOG(DM_LOG_INFO, "DeviceManager::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()); if (pkgName.empty()) { @@ -188,9 +193,8 @@ int32_t DeviceManagerImpl::AuthenticateDevice(std::string &pkgName, const DmDevi req->SetPkgName(pkgName); req->SetExtra(extra); req->SetDeviceInfo(deviceInfo); - req->SetAppImageInfo(imageInfo); if (ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -204,8 +208,13 @@ int32_t DeviceManagerImpl::AuthenticateDevice(std::string &pkgName, const DmDevi 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 DmDeviceInfo &deviceInfo) +{ + return DM_OK; +} + +int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) { DMLOG(DM_LOG_INFO, "DeviceManager::CheckAuthentication start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { @@ -218,7 +227,7 @@ int32_t DeviceManagerImpl::CheckAuthentication(std::string &pkgName, std::string req->SetPkgName(pkgName); req->SetAuthPara(authPara); if (ipcClientProxy_->SendRequest(CHECK_AUTHENTICATION, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -226,67 +235,9 @@ int32_t DeviceManagerImpl::CheckAuthentication(std::string &pkgName, std::string DMLOG(DM_LOG_ERROR, "CheckAuthentication Failed with ret %d", ret); return ret; } - DeviceManagerNotify::GetInstance().RegisterCheckAuthenticationCallback(pkgName, authPara, callback); + DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); DMLOG(DM_LOG_INFO, "DeviceManager::CheckAuthentication completed, pkgName: %s", pkgName.c_str()); return DM_OK; } - -int32_t DeviceManagerImpl::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) -{ - DMLOG(DM_LOG_INFO, "DeviceManager::GetAuthenticationParam start"); - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - if (ipcClientProxy_->SendRequest(SERVER_GET_AUTHENTCATION_INFO, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; - } - authParam = rsp->GetAuthParam(); - return DM_OK; -} - -int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action) -{ - DMLOG(DM_LOG_INFO, "DeviceManager::SetUserOperation start"); - 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) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; - } - int32_t ret = rsp->GetErrCode(); - if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "CheckAuthentication Failed with ret %d", ret); - return ret; - } - return DM_OK; -} - -int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback) -{ - DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDeviceManagerFaCallback start, pkgName: %s", packageName.c_str()); - if (packageName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DM_INVALID_VALUE; - } - DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(packageName, callback); - DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback completed, pkgName: %s", packageName.c_str()); - return DM_OK; -} - -int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(std::string &pkgName) -{ - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDeviceManagerFaCallback start, pkgName: %s", pkgName.c_str()); - if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DM_INVALID_VALUE; - } - DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); - 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 14959faea..7596377e9 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 @@ -262,7 +262,7 @@ ON_IPC_CMD(SERVER_DISCOVER_FINISH, IpcIo &reply) if (failedReason == DM_OK) { DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); } else { - DeviceManagerNotify::GetInstance().OnDiscoverFailed(pkgName, subscribeId, failedReason); + DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); } } 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 1813dc860..017960639 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 @@ -15,17 +15,18 @@ #include "ipc_client_manager.h" -#include "ipc_remote_broker.h" #include "iremote_object.h" #include "iservice_registry.h" #include "system_ability_definition.h" +#include "ipc_remote_broker.h" +#include "ipc_client_stub.h" +#include "ipc_register_listener_req.h" + #include "dm_constants.h" #include "dm_log.h" #include "device_manager_notify.h" -#include "ipc_register_listener_req.h" - namespace OHOS { namespace DistributedHardware { void DmDeathRecipient::OnRemoteDied(const wptr &remote) @@ -66,7 +67,7 @@ int32_t IpcClientManager::ClientInit() 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(); @@ -98,7 +99,7 @@ int32_t IpcClientManager::Init(std::string &pkgName) 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()); if (dmInterface_ == nullptr) { 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 8bb6fe9e5..f19aac43e 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 @@ -28,18 +28,18 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r sptr remote = Remote(); if (remote == nullptr) { DMLOG(DM_LOG_ERROR, "remote service null"); - return DEVICEMANAGER_NULLPTR; + return DM_POINT_NULL; } MessageParcel data; MessageParcel reply; MessageOption option; if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) { - return DEVICEMANAGER_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); - return DEVICEMANAGER_IPC_FAILED; + 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_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index 68938e08b..0a97b6826 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 @@ -18,6 +18,7 @@ #include "securec.h" #include "dm_constants.h" #include "dm_log.h" +#include "dm_device_info.h" #include "device_manager_notify.h" #include "ipc_def.h" @@ -271,7 +272,7 @@ ON_IPC_CMD(SERVER_DISCOVER_FINISH, MessageParcel &data, MessageParcel &reply) if (failedReason == DM_OK) { DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); } else { - DeviceManagerNotify::GetInstance().OnDiscoverFailed(pkgName, subscribeId, failedReason); + DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); } reply.WriteInt32(DM_OK); return DM_OK; @@ -281,11 +282,11 @@ 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); + DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, token, status, reason); reply.WriteInt32(DM_OK); return DM_OK; } @@ -296,7 +297,6 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) std::string deviceId = data.ReadString(); int32_t resultCode = data.ReadInt32(); int32_t flag = data.ReadInt32(); - DeviceManagerNotify::GetInstance().OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); reply.WriteInt32(DM_OK); return DM_OK; 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 2a324bd11..aedcc1252 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 @@ -50,23 +50,23 @@ void DeviceManagerNotify::UnRegisterDeviceStateCallback(const std::string &pkgNa deviceStateCallback_.erase(pkgName); } -void DeviceManagerNotify::RegisterDiscoverCallback(const 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(const 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); } } } @@ -96,13 +96,13 @@ 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_); verifyAuthCallback_[pkgName] = callback; @@ -122,7 +122,7 @@ void DeviceManagerNotify::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()); std::lock_guard autoLock(lock_); @@ -133,7 +133,7 @@ void DeviceManagerNotify::OnDeviceOnline(std::string &pkgName, const DmDeviceInf 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()); std::lock_guard autoLock(lock_); @@ -144,7 +144,7 @@ void DeviceManagerNotify::OnDeviceOffline(std::string &pkgName, const DmDeviceIn 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()); std::lock_guard autoLock(lock_); @@ -155,66 +155,66 @@ void DeviceManagerNotify::OnDeviceChanged(std::string &pkgName, const DmDeviceIn deviceStateCallback_[pkgName]->OnDeviceChanged(deviceInfo); } -void DeviceManagerNotify::OnDeviceFound(std::string &pkgName, uint16_t subscribeId, +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); 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) { + DMLOG(DM_LOG_ERROR, "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", + DMLOG(DM_LOG_ERROR, "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", + DMLOG(DM_LOG_INFO, "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) { + DMLOG(DM_LOG_ERROR, "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", + DMLOG(DM_LOG_ERROR, "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); 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) { + DMLOG(DM_LOG_ERROR, "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", + DMLOG(DM_LOG_ERROR, "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); @@ -229,37 +229,25 @@ void DeviceManagerNotify::OnAuthResult(std::string &pkgName, std::string &device DMLOG(DM_LOG_ERROR, "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); std::lock_guard autoLock(lock_); - if (checkauthcallback_.count(pkgName) == 0) { + if (verifyAuthCallback_.count(pkgName) == 0) { DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register authCallback for this package"); return; } - - checkauthcallback_[pkgName]->OnCheckAuthResult(deviceId, resultCode, flag); - checkauthcallback_.erase(pkgName); -} - -void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) -{ - DMLOG(DM_LOG_INFO, "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"); - return; - } - dmFaCallback_[pkgName]->OnCall(paramJson); + verifyAuthCallback_[pkgName]->OnVerifyAuthResult(deviceId, resultCode, flag); + verifyAuthCallback_.erase(pkgName); } } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index b5843f4a2..bcd79c508 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -25,6 +25,7 @@ ohos_shared_library("devicemanager") { "${common_path}/include", "${common_path}/include/ipc", "${common_path}/include/utils", + "${common_path}/include/constants", "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/standard", ] @@ -53,7 +54,7 @@ ohos_shared_library("devicemanager") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "distributedhardware" diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index c18853446..05b4aca07 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -80,12 +80,12 @@ 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(); @@ -100,7 +100,7 @@ class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::Authenticat 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; + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override; private: std::string bundleName_; @@ -110,7 +110,7 @@ class DmNapiVerifyAuthCallback : public OHOS::DistributedHardware::VerifyAuthCal public: explicit DmNapiVerifyAuthCallback(std::string &bundleName) : bundleName_(bundleName) {} virtual ~DmNapiVerifyAuthCallback() {}; - void OnVerifyAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) override; + void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) override; private: std::string bundleName_; @@ -133,7 +133,7 @@ public: 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 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); @@ -157,8 +157,8 @@ public: 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); +// static void JsToDmAppImageInfoAndDmExtra(const napi_env &env, const napi_value &object, +// OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, 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); @@ -170,11 +170,9 @@ public: void OnDeviceStateChange(DmNapiDevStateChangeAction action, 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); - static void DmAuthParamToJsAuthParamy(const napi_env &env, - const OHOS::DistributedHardware::DmAuthParam &authParam, napi_value ¶mResult); private: napi_env env_; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index b6e6d5bf4..622eac965 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -21,6 +21,7 @@ #include "device_manager.h" #include "dm_log.h" #include "dm_constants.h" +#include "dm_device_info.h" using namespace OHOS::DistributedHardware; @@ -34,10 +35,8 @@ namespace { 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 int32_t DM_NAPI_ARGS_ONE = 1; @@ -45,18 +44,17 @@ 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; +//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; } napi_ref DeviceManagerNapi::sConstructor_ = nullptr; @@ -113,7 +111,7 @@ void DmNapiDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) 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) { @@ -125,18 +123,18 @@ void DmNapiDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDevice 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()); + DMLOG(DM_LOG_ERROR, "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) { @@ -146,32 +144,32 @@ void DmNapiDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) DMLOG(DM_LOG_INFO, "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()); return; } - deviceManagerNapi->OnAuthResult(deviceId, pinToken, status, reason); + deviceManagerNapi->OnAuthResult(deviceId, token, status, reason); } -void DmNapiCheckAuthCallback::OnVerifyAuthResult(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) { @@ -236,9 +234,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); + DMLOG(DM_LOG_INFO, "OnDiscoveryFailed for subscribeId %d", (int32_t)subscribeId); napi_value result = nullptr; napi_create_object(env_, &result); SetValueInt32(env_, "subscribeId", (int)subscribeId, result); @@ -246,16 +244,7 @@ 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); napi_value thisVar = nullptr; @@ -267,9 +256,10 @@ void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, int32_t pinTok 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]); - } + //TODO: + //if (authAsyncCallbackInfo_.authType == DM_AUTH_TYPE_PINCODE) { + // SetValueInt32(env_, "pinTone", token, result[1]); + //} } else { DMLOG(DM_LOG_INFO, "OnAuthResult failed"); napi_create_object(env_, &result[0]); @@ -316,7 +306,7 @@ void DeviceManagerNapi::OnVerifyResult(const std::string &deviceId, int32_t resu } else { DMLOG(DM_LOG_ERROR, "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, @@ -352,55 +342,55 @@ void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, } } -void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, +void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam, napi_value ¶mResult) { - DMLOG(DM_LOG_INFO, "DmAuthParamToJsAuthParamy in"); + DMLOG(DM_LOG_INFO, "DmAuthParamToJsAuthParam 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, "authToken", authParam.authToken, extraInfo); if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; } - SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); - SetValueUtf8String(env, "appName", authParam.appName, extraInfo); - SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); - SetValueInt32(env, "business", authParam.business, extraInfo); - SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); - napi_set_named_property(env, paramResult, "extraInfo", extraInfo); - - size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); - if (appIconLen > 0) { - void *appIcon = nullptr; - 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) { - napi_value appIconArray = nullptr; - napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); - napi_set_named_property(env, paramResult, "appIcon", appIconArray); - } - } +// SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); +// SetValueUtf8String(env, "appName", authParam.appName, extraInfo); +// SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); +// SetValueInt32(env, "business", authParam.business, extraInfo); +// SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); +// napi_set_named_property(env, paramResult, "extraInfo", extraInfo); + +// size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); +// if (appIconLen > 0) { +// void *appIcon = nullptr; +// 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) { +// napi_value appIconArray = nullptr; +// napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); +// napi_set_named_property(env, paramResult, "appIcon", appIconArray); +// } +// } - size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); - if (appThumbnailLen > 0) { - void *appThumbnail = nullptr; - napi_value appThumbnailBuffer = nullptr; - napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); - if (appThumbnail != nullptr && - memcpy_s(appThumbnail, appThumbnailLen, - 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); - } - } +// size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); +// if (appThumbnailLen > 0) { +// void *appThumbnail = nullptr; +// napi_value appThumbnailBuffer = nullptr; +// napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); +// if (appThumbnail != nullptr && +// memcpy_s(appThumbnail, appThumbnailLen, +// 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); +// } +// } } void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, @@ -515,9 +505,9 @@ int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_v int32_t capability = -1; JsObjectToInt(env, object, "capability", capability); - if (capability == DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_NAPI_SUBSCRIBE_CAPABILITY_OSD) { - (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); - } +// if (capability == DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_NAPI_SUBSCRIBE_CAPABILITY_OSD) { +// (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); +// } return 0; } @@ -528,7 +518,7 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & 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, @@ -673,19 +663,20 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob 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; - } + //TODO: +// jsonObj[AUTH_TYPE] = authType; +// if (authType == DM_AUTH_TYPE_PINCODE) { +// jsonObj[PIN_TOKEN] = token; +// } else { +// jsonObj[TOKEN] = token; +// } JsToJsonObject(env, object, "extraInfo", jsonObj); extra = jsonObj.dump(); } 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()); + DMLOG(DM_LOG_ERROR, "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()) { @@ -701,18 +692,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; } } @@ -734,17 +725,17 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & 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; } @@ -773,7 +764,7 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & // } // // napi_create_object(env, &resultParam); -// DmAuthParamToJsAuthParamy(env, authParam, resultParam); +// DmAuthParamToJsAuthParam(env, authParam, resultParam); // return resultParam; //} @@ -828,25 +819,26 @@ 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); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); - return result; - } + //TODO: +// int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, +// subInfo, DiscoveryCallback); +// if (ret != 0) { +// DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery for bunderName %s failed, ret %d", +// deviceManagerWrapper->bundleName_.c_str(), ret); +// return result; +// } napi_get_undefined(env, &result); return result; @@ -917,16 +909,15 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf // DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); std::string extra; - JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], extra, authAsyncCallbackInfo_.authType); +// JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], extra, authAsyncCallbackInfo_.authType); //TODO:get real authType int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, extra, authCallback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice for bunderName %s failed, ret %d", + DMLOG(DM_LOG_ERROR, "AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } - napi_get_undefined(env, &result); return result; } @@ -951,10 +942,10 @@ napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info in napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); std::shared_ptr verifyCallback = nullptr; - auto iter = g_checkAuthCallbackMap.find(deviceManagerWrapper->bundleName_); - if (iter == g_checkAuthCallbackMap.end()) { + auto iter = g_verifyAuthCallbackMap.find(deviceManagerWrapper->bundleName_); + if (iter == g_verifyAuthCallbackMap.end()) { verifyCallback = std::make_shared(deviceManagerWrapper->bundleName_); - g_checkAuthCallbackMap[deviceManagerWrapper->bundleName_] = verifyCallback; + g_verifyAuthCallbackMap[deviceManagerWrapper->bundleName_] = verifyCallback; } else { verifyCallback = iter->second; } @@ -1071,9 +1062,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; } @@ -1197,8 +1188,8 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("stopDeviceDiscovery", StopDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("authenticateDevice", AuthenticateDevice), DECLARE_NAPI_FUNCTION("verifyAuthInfo", VerifyAuthInfo), - DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync), - DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync), +// DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync), +// DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync), DECLARE_NAPI_FUNCTION("on", JsOn), DECLARE_NAPI_FUNCTION("off", JsOff) }; diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 5a0969874..f31a5da96 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -112,7 +112,7 @@ if (defined(ohos_lite)) { "include/dependency/hichain", "include/dependency/softbus", "include/ipc", - "include/ipc/lite", + "include/ipc/standard", "${common_path}/include", "${common_path}/include/constants", "${common_path}/include/utils", @@ -167,7 +167,7 @@ if (defined(ohos_lite)) { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", "startup_l2:syspara", ] diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 0362fb88d..514dd85f3 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -37,12 +37,11 @@ public: int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authParam); private: - std::shared_ptr softbusSession_; + std::shared_ptr softbusConnector_; std::shared_ptr hiChainConnector_; std::shared_ptr listenerPtr_; std::shared_ptr adapterMgr_; - std::map authenticationMap_; - +// std::map authenticationMap_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 0a1b9d811..b376f7c71 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -19,10 +19,13 @@ #include #include #include +#include +#include #include "nlohmann/json.hpp" #include "device_auth.h" #include "single_instance.h" +#include "hichain_connector_callback.h" namespace OHOS { namespace DistributedHardware { @@ -48,9 +51,9 @@ public: public: HiChainConnector(); ~HiChainConnector(); - void RegisterHiChainCallback(const string &pkgName, const IHiChainConnectorCallback &callback); + void RegisterHiChainCallback(const std::string &pkgName, const IHiChainConnectorCallback &callback); int32_t CreateGroup(int64_t requestId, const std::string &groupName); - int32_t AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth); +// int32_t AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth); int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); private: @@ -59,13 +62,13 @@ private: 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::shared_ptr msgResponseAuth); - int32_t IsGroupCreated(std::string groupName, GroupInfo &groupInfo); +// std::string GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth); + bool IsGroupCreated(std::string groupName, GroupInfo &groupInfo); bool IsGroupInfoInvalid(GroupInfo &group); private: const DeviceGroupManager *deviceGroupManager_ = nullptr; DeviceAuthCallback deviceAuthCallback_ ; - std::map hichainConnectorCallback_; +// std::map hichainConnectorCallback_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 8117ab72f..43548b21b 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -32,8 +32,8 @@ public: public: SoftbusSession(); ~SoftbusSession(); - int32_t RegisterSessionCallback(const string &pkgName, ISoftbusSessionCallback callback); - int32_t UnRegisterSessionCallback(const string& pkgName); + int32_t RegisterSessionCallback(const std::string &pkgName, ISoftbusSessionCallback callback); + int32_t UnRegisterSessionCallback(const std::string& pkgName); int32_t OpenAuthSession(const char *deviceId); void CloseAuthSession(int32_t sessionId); // int32_t SendMessages(const char *deviceId, std::vector &messages); diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index ca049c1d2..a6c59e887 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -18,7 +18,6 @@ #include #include -#include #include "dm_auth_manager.h" #include "dm_device_info_manager.h" @@ -31,22 +30,21 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerService { -public: - static DeviceManagerService & GetInstance(); +DECLARE_SINGLE_INSTANCE(DeviceManagerService); public: int32_t Init(); - int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList, const std::string &extra,); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); int32_t GetLocalDeviceInfo(DmDeviceInfo &info); 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 &pkgName, const std::string &authParam); -private: - DeviceManagerService(const DeviceManagerService&) = delete; - DeviceManagerService& operator= (const DeviceManagerService&) = delete; - DeviceManagerService(DeviceManagerService&&) = delete; - DeviceManagerService& operator= (DeviceManagerService&&) = delete; +//private: +// DeviceManagerService(const DeviceManagerService&) = delete; +// DeviceManagerService& operator= (const DeviceManagerService&) = delete; +// DeviceManagerService(DeviceManagerService&&) = delete; +// DeviceManagerService& operator= (DeviceManagerService&&) = delete; private: bool intFlag_ = false; std::shared_ptr authMgrPtr_; diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index fa87a6a61..e4b6f73aa 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -25,15 +25,12 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerServiceListener { public: - int32_t OnDeviceOnline(const DmDeviceInfo &info); - int32_t OnDeviceOffline(const DmDeviceInfo &info); - int32_t OnDeviceReady(const DmDeviceInfo &info); - int32_t OnDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info); - int32_t OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &info); - int32_t OnDiscoveryFailed(uint16_t subscribeId, const std::string &failedReason); - int32_t OnDiscoverySuccess(int32_t subscribeId); - int32_t OnAuthenticateResult(const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason); - int32_t OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string &flag); + void OnDeviceStateChange(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, const std::string &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); private: IpcServerListener ipcServerListener_; }; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index b64213350..ca337cee6 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { DmAuthManager::DmAuthManager(std::shared_ptr softbusConnectorPtr, - std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) + std::shared_ptr listenerPtr) : softbusConnector_(softbusConnectorPtr), listenerPtr_(listenerPtr) { DMLOG(DM_LOG_INFO, "DmAuthManager constructor"); } @@ -31,19 +31,19 @@ DmAuthManager::~DmAuthManager() DMLOG(DM_LOG_INFO, "DmAuthManager destructor"); } -int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const string &deviceId, const std::string extra) +int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - return SUCCESS; + return DM_OK; } -int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const string &deviceId) +int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { - return SUCCESS; + return DM_OK; } int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) { - return SUCCESS; + return DM_OK; } } diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 1090459a8..208543408 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -38,7 +38,7 @@ namespace DistributedHardware { // 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 DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; // const std::string DEVICE_MANAGER_GROUPNAME = "DMPeerToPeerGroup"; // const int64_t MIN_REQUEST_ID = 1000000000; @@ -94,18 +94,18 @@ HiChainConnector::~HiChainConnector() //TODO:delete resource } -HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, const IHiChainConnectorCallback &callback) +void HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, const IHiChainConnectorCallback &callback) { - if (hichainConnectorCallback_.count(pkgName) == 0) { - hichainConnectorCallback[pkgName] = callback; - } +// if (hichainConnectorCallback_.count(pkgName) == 0) { +// hichainConnectorCallback[pkgName] = callback; +// } } 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; + return DM_INVALID_VALUE; } GroupInfo groupInfo; @@ -125,15 +125,15 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou 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()); + int32_t ret = deviceGroupManager_->createGroup(requestId, DM_PKG_NAME.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 DM_HICHAIN_GROUP_CREATE_FAILED; } - return SUCCESS; + return DM_OK; } -int32_t HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInfo) +bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInfo) { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); @@ -144,7 +144,6 @@ int32_t HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &group groupInfo = groupList[0]; return true; } - return false; } @@ -153,7 +152,7 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vectorgetGroupInfo(DEVICE_MANAGER_APP.c_str(), queryParams.c_str(), &groupVec, &num); + int32_t ret = deviceGroupManager_->getGroupInfo(DM_PKG_NAME.c_str(), queryParams.c_str(), &groupVec, &num); if (ret != 0) { DMLOG(DM_LOG_ERROR, "HiChainConnector::GetGroupInfo faild , ret: %d.", ret); return false; @@ -211,7 +210,7 @@ int32_t HiChainConnector::AddMemeber(std::string deviceId, std::shared_ptraddMemberToGroup(msgResponseAuth->GetRequestId(), DEVICE_MANAGER_APP.c_str(), + return deviceGroupManager_->addMemberToGroup(msgResponseAuth->GetRequestId(), DM_PKG_NAME.c_str(), tmpStr.c_str()); } @@ -226,16 +225,13 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const 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"); } @@ -252,16 +248,13 @@ void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t 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"); } @@ -270,25 +263,24 @@ void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams) { if (operationCode != GroupOperationCode::MEMBER_JOIN) { - DMLOG(DM_LOG_ERROR, "HichainAuthenCallBack::onRequest operationCode %d", operationCode); + DMLOG(DM_LOG_ERROR, "HiChainAuthCallBack::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; +// 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; } // void HiChainConnector::RegisterConnectorCallback(std::shared_ptr callback) @@ -344,44 +336,44 @@ int64_t HiChainConnector::GenRequestId() } -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(); -} +//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(), + int32_t ret = deviceGroupManager_->getRelatedGroups(DM_PKG_NAME.c_str(), deviceId.c_str(), &returnGroups, &groupNum); if (ret != 0) { DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups faild , ret: %d.", ret); @@ -410,9 +402,7 @@ void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList, std::vector &syncGroupList) @@ -433,7 +423,7 @@ void HiChainConnector::GetSyncGroupList(std::vector &groupList, std:: bool HiChainConnector::IsGroupInfoInvalid(GroupInfo &group) { if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC || - group.groupOwner != DEVICE_MANAGER_APP) { + group.groupOwner != DM_PKG_NAME) { return true; } return false; @@ -465,7 +455,7 @@ int32_t HiChainConnector::DelMemberFromGroup(std::string groupId, std::string de jsonObj[FIELD_DELETE_ID] = deviceId; std::string deleteParams = jsonObj.dump(); - int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DEVICE_MANAGER_APP.c_str(), + int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DM_PKG_NAME.c_str(), deleteParams.c_str()); if (ret != 0) { DMLOG(DM_LOG_ERROR, "HiChainConnector::DelMemberFromGroup faild , ret: %d.", ret); @@ -480,10 +470,9 @@ void HiChainConnector::DeleteGroup(std::string &groupId) 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()); + int32_t ret = deviceGroupManager_->deleteGroup(requestId, DM_PKG_NAME.c_str(), disbandParams.c_str()); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::DeleteGroup faild , ret: %d.", ret); + DMLOG(DM_LOG_ERROR, "HiChainConnector::DeleteGroup failed , ret: %d.", ret); } } } diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index abf7b2e89..3d190cb4c 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -35,7 +35,7 @@ SoftbusConnector::SoftbusConnector() }; softbusDiscoveryCallback_ = { .OnDeviceFound = SoftbusConnector::OnSoftbusDeviceFound, - .OnDiscoverFailed = SoftbusConnector::OnSoftbusDiscoverFailed, + .OnDiscoveryFailed = SoftbusConnector::OnSoftbusDiscoverFailed, .OnDiscoverySuccess = SoftbusConnector::OnSoftbusDiscoverySuccess }; softbusNodeStateCb_ = { @@ -71,7 +71,7 @@ int32_t SoftbusConnector::Init() publishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; publishInfo.medium = ExchanageMedium::AUTO; publishInfo.freq = ExchangeFreq::HIGH; - publishInfo.capability = DM_CAPABILITY_OSD; + publishInfo.capability = nullptr; publishInfo.capabilityData = nullptr; publishInfo.dataLen = 0; ret = PublishService(DM_PKG_NAME.c_str(), &publishInfo, &softbusPublishCallback_); @@ -458,7 +458,7 @@ void SoftbusConnector::OnSoftbusDiscoverFailed(int32_t subscribeId, DiscoveryFai // } // // uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); - // IpcServerListenerAdapter::GetInstance().OnDiscoverFailed(pkgName, originId, failReason); + // IpcServerListenerAdapter::GetInstance().OnDiscoveryFailed(pkgName, originId, failReason); } void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 608c3490a..dc293a680 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -21,24 +21,21 @@ namespace OHOS { namespace DistributedHardware { -DeviceManagerService& DeviceManagerService::GetInstance() -{ - static DeviceManagerService instance; - return instance; -} + +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); int32_t DeviceManagerService::Init() { if (intFlag_) { DMLOG(DM_LOG_ERROR, "Init failed, singleton cannot be initialized multiple times"); - return ERROR_INT_MULTIPLE; + return DM_INT_MULTIPLE; } if (softbusConnectorPtr_ == nullptr) { softbusConnectorPtr_ = std::make_shared(); if (softbusConnectorPtr_ == nullptr) { DMLOG(DM_LOG_ERROR, "Init failed, softbusConnectorPtr_ apply for failure"); - return ERROR_MAKE_SHARED_FAIL; + return DM_MAKE_SHARED_FAIL; } } @@ -46,15 +43,15 @@ int32_t DeviceManagerService::Init() listenerPtr_ = std::make_shared(); if (softbusConnectorPtr_ == nullptr) { DMLOG(DM_LOG_ERROR, "Init failed, listenerPtr_ apply for failure"); - return ERROR_MAKE_SHARED_FAIL; + return DM_MAKE_SHARED_FAIL; } } if (deviceInfoMgrPtr_ == nullptr) { - deviceInfoMgrPtr_ = std::make_shared(); + deviceInfoMgrPtr_ = std::make_shared(softbusConnectorPtr_); if (deviceInfoMgrPtr_ == nullptr) { DMLOG(DM_LOG_ERROR, "Init failed, deviceInfoMgrPtr_ apply for failure"); - return ERROR_MAKE_SHARED_FAIL; + return DM_MAKE_SHARED_FAIL; } } @@ -62,7 +59,7 @@ int32_t DeviceManagerService::Init() deviceStateMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); if (deviceStateMgrPtr_ == nullptr) { DMLOG(DM_LOG_ERROR, "Init failed, deviceStateMgrPtr_ apply for failure"); - return ERROR_MAKE_SHARED_FAIL; + return DM_MAKE_SHARED_FAIL; } } @@ -70,7 +67,7 @@ int32_t DeviceManagerService::Init() discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); if (discoveryMgrPtr_ == nullptr) { DMLOG(DM_LOG_ERROR, "Init failed, discoveryMgrPtr_ apply for failure"); - return ERROR_MAKE_SHARED_FAIL; + return DM_MAKE_SHARED_FAIL; } } @@ -78,7 +75,7 @@ int32_t DeviceManagerService::Init() authMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); if (authMgrPtr_ == nullptr) { DMLOG(DM_LOG_ERROR, "Init failed, authMgrPtr_ apply for failure"); - return ERROR_MAKE_SHARED_FAIL; + return DM_MAKE_SHARED_FAIL; } } @@ -87,7 +84,7 @@ int32_t DeviceManagerService::Init() return DM_OK; } -int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList, const std::string &extra) +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, singleton not init or init fail"); @@ -158,7 +155,7 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int return authMgrPtr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } -int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId); +int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { if (!intFlag_) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, singleton not init or init fail"); @@ -167,11 +164,11 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, pkgName is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } if (deviceId.empty()) { DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, deviceId is empty"); - return ERROR_INPUT_PARA_EMPTY; + return DM_INPUT_PARA_EMPTY; } return authMgrPtr_->UnAuthenticateDevice(pkgName, deviceId); } diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 85579b814..aa87dd8a2 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -31,58 +31,55 @@ namespace OHOS { namespace DistributedHardware { -void DeviceManagerServiceListener::OnDeviceStateChange(DmDeviceState state, DmDeviceInfo &deviceInfo) +void DeviceManagerServiceListener::OnDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info) { 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); + pReq->SetDeviceInfo(info); ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } -void DeviceManagerServiceListener::OnDeviceFound(std::string &pkgName, uint16_t originId, - DmDeviceInfo &deviceInfo) +void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) { DMLOG(DM_LOG_INFO, "call OnDeviceFound for %s, originId %d, deviceId %s", - pkgName.c_str(), originId, GetAnonyString(std::string(deviceInfo.deviceId)).c_str()); + 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(originId); - pReq->SetDeviceInfo(deviceInfo); + pReq->SetSubscribeId(subscribeId); + pReq->SetDeviceInfo(info); ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } -void DeviceManagerServiceListener::OnDiscoverFailed(std::string &pkgName, uint16_t originId, - DiscoveryFailReason failReason) +void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, const std::string &failedReason) { - DMLOG(DM_LOG_INFO, "OnDiscoverFailed"); + DMLOG(DM_LOG_INFO, "OnDiscoveryFailed"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); pReq->SetPkgName(pkgName); - pReq->SetSubscribeId(originId); - pReq->SetResult(failReason); + pReq->SetSubscribeId(subscribeId); +// pReq->SetResult(failReason); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnDiscoverySuccess(std::string &pkgName, uint16_t originId) +void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) { 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->SetSubscribeId(subscribeId); pReq->SetResult(DM_OK); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, - uint32_t status, uint32_t reason) +void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason) { DMLOG(DM_LOG_INFO, "%s, package: %s, deviceId: %s", __FUNCTION__, pkgName.c_str(), GetAnonyString(deviceId).c_str()); @@ -91,34 +88,23 @@ void DeviceManagerServiceListener::OnAuthResult(std::string &pkgName, std::strin pReq->SetPkgName(pkgName); pReq->SetDeviceId(deviceId); - pReq->SetPinToken(pinToken); + pReq->SetToken(token); pReq->SetStatus(status); - pReq->SetReason(reason); +// pReq->SetReason(reason); ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnCheckAuthResult(std::string &authParam, int32_t resultCode, int32_t flag) +void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode, const std::string &flag) { - DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", - GetAnonyString(authParam).c_str(), resultCode); +// 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->SetDeviceId(deviceId); pReq->SetResult(resultCode); - pReq->SetFlag(flag); - ipcServerListener_.SendAll(SERVER_CHECK_AUTH_RESULT, pReq, pRsp); -} - -void DeviceManagerServiceListener::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); +// pReq->SetFlag(flag); + ipcServerListener_.SendAll(SERVER_VERIFY_AUTH_RESULT, 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 index 45e0f5f7e..479669058 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -40,13 +40,13 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co return DM_POINT_NULL; } - IDecisionAdapter decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); - if (decisionAdapter != nullptr) { - decisionAdapter->FilterDeviceList(deviceList, extra); - } else { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList decisionAdapter is nullptr"); - return DM_POINT_NULL; - } +// IDecisionAdapter decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); +// if (decisionAdapter != nullptr) { +// decisionAdapter->FilterDeviceList(deviceList, extra); +// } else { +// DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList decisionAdapter is nullptr"); +// return DM_POINT_NULL; +// } } return DM_OK; diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 5d6734d32..caa43ecfc 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, - std::shared listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) + std::shared_ptr listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) { DMLOG(DM_LOG_INFO, "DmDeviceStateManager constructor"); } diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index a8fa30cf3..26539ea0e 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -35,7 +35,6 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con { //TODO:prevent reentration //TODO:save extra for later filter the found device - softbusConnectorPtr_->RegisterSoftbusDiscoveryCallback(pkgName, ); return softbusConnectorPtr_->StartDiscovery(subscribeInfo); } diff --git a/test/unittest/device_manager_impl_test.cpp b/test/unittest/device_manager_impl_test.cpp index d3c3dd2ae..24dd07e8e 100644 --- a/test/unittest/device_manager_impl_test.cpp +++ b/test/unittest/device_manager_impl_test.cpp @@ -132,7 +132,7 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery1, testing::ext::TestSize.Le { std::string packName = ""; DmSubscribeInfo subscribeInfo; - std::shared_ptr callback = nullptr; + std::shared_ptr callback = nullptr; int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, callback); ASSERT_EQ(ret, DM_INVALID_VALUE); } @@ -141,7 +141,7 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, testing::ext::TestSize.Le { std::string packName = "com.ohos.helloworld"; DmSubscribeInfo subscribeInfo; - test_callback_ = std::make_shared(); + test_callback_ = std::make_shared(); std::shared_ptr mockInstance = std::make_shared(); DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) @@ -155,7 +155,7 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Le { std::string packName = "com.ohos.helloworld"; DmSubscribeInfo subscribeInfo; - test_callback_ = std::make_shared(); + test_callback_ = std::make_shared(); std::shared_ptr mockInstance = std::make_shared(); DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) @@ -166,18 +166,18 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Le } } // namespace -void DeviceDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) +void DeviceDiscoveryCallback::OnDiscoverySuccess(uint16_t subscribeId) { (void)subscribeId; } -void DeviceDiscoverCallback::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) +void DeviceDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) { (void)subscribeId; (void)failedReason; } -void DeviceDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +void DeviceDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { (void)subscribeId; } diff --git a/test/unittest/device_manager_impl_test.h b/test/unittest/device_manager_impl_test.h index 91ef0863a..4bfd6b28a 100644 --- a/test/unittest/device_manager_impl_test.h +++ b/test/unittest/device_manager_impl_test.h @@ -33,15 +33,15 @@ public: virtual void SetUp() override; virtual void TearDown() override; private: - std::shared_ptr test_callback_ = nullptr; + std::shared_ptr test_callback_ = nullptr; }; -class DeviceDiscoverCallback : public DiscoverCallback { +class DeviceDiscoveryCallback : public DiscoveryCallback { public: - DeviceDiscoverCallback() : DiscoverCallback() {} - virtual ~DeviceDiscoverCallback() override {} + DeviceDiscoveryCallback() : DiscoveryCallback() {} + virtual ~DeviceDiscoveryCallback() override {} virtual void OnDiscoverySuccess(uint16_t subscribeId) override; - virtual void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) override; + virtual void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) override; }; } // namespace Vsync diff --git a/utils/BUILD.gn b/utils/BUILD.gn index a218e443f..adec2c8af 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -112,7 +112,7 @@ if (defined(ohos_lite)) { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", "startup_l2:syspara", ] -- Gitee From 1085f6a369f8d783badfac508599a110a49f50cd Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sun, 28 Nov 2021 10:20:16 +0800 Subject: [PATCH 015/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86int?= =?UTF-8?q?erface=E5=92=8Ccommon=E7=9B=AE=E5=BD=95=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ipc/model/ipc_check_authenticate_req.h | 40 ------------------ .../model/ipc_get_authenticationparam_rsp.h | 41 ------------------ .../ipc/model/ipc_get_localdevice_rsp.h | 42 ------------------- .../ipc/model/ipc_set_useroperation_req.h | 41 ------------------ .../native_cpp/include/device_manager.h | 3 +- .../native_cpp/include/device_manager_impl.h | 3 +- .../native_cpp/src/device_manager.cpp | 1 - .../native_cpp/src/device_manager_impl.cpp | 23 +++++++--- 8 files changed, 20 insertions(+), 174 deletions(-) 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_get_localdevice_rsp.h delete mode 100644 common/include/ipc/model/ipc_set_useroperation_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 0015534b3..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_DM_IPC_CHECK_AUTHENTICATE_REQ_H -#define OHOS_DM_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(const std::string &authPara) - { - authPara_ = authPara; - } -private: - std::string authPara_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_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 b2dd00214..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_DM_IPC_GET_AUTH_PARAM_RSP_H -#define OHOS_DM_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_DM_IPC_GET_AUTH_PARAM_RSP_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_get_localdevice_rsp.h b/common/include/ipc/model/ipc_get_localdevice_rsp.h deleted file mode 100644 index 81b4b0c7d..000000000 --- a/common/include/ipc/model/ipc_get_localdevice_rsp.h +++ /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. - */ - -#ifndef OHOS_DM_IPC_GET_LOCALDEVICE_RSP_H -#define OHOS_DM_IPC_GET_LOCALDEVICE_RSP_H - -#include "dm_device_info.h" - -#include "ipc_rsp.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcGetLocaldeviceRsp : public IpcRsp { -DECLARE_IPC_MODEL(IpcGetTrustdeviceRsp); -public: - DmDeviceInfo GetLocalDeviceInfo() const - { - return localDeviceInfo_; - } - - void SetLocalDeviceInfo(DmDeviceInfo deviceInfo) - { - localDeviceInfo_ = deviceInfo; - } -private: - DmDeviceInfo localDeviceInfo_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_GET_LOCALDEVICE_RSP_H diff --git a/common/include/ipc/model/ipc_set_useroperation_req.h b/common/include/ipc/model/ipc_set_useroperation_req.h deleted file mode 100644 index 5f56e27bf..000000000 --- a/common/include/ipc/model/ipc_set_useroperation_req.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_DM_IPC_GET_USER_OPERATION_REQ_H -#define OHOS_DM_IPC_GET_USER_OPERATION_REQ_H -#include "ipc_req.h" -#include "dm_device_info.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcGetOperationReq : public IpcReq { -DECLARE_IPC_MODEL(IpcGetOperationReq); -public: - int32_t GetOperation() const - { - return action_; - } - - void SetOperation(int32_t action) - { - action_ = action; - } - -private: - int32_t action_ {0}; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_GET_USER_OPERATION_REQ_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index c92edcd0e..cef97ab93 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -48,4 +48,5 @@ public: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_H + +#endif // DEVICE_MANAGER_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 5b2899d18..2f1d6425f 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -29,7 +29,7 @@ class DeviceManagerImpl : public DeviceManager { DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); public: virtual int32_t InitDeviceManager(const std::string &pkgName, - std::shared_ptr dmInitCallback) override; + 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; @@ -45,7 +45,6 @@ public: virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) override; virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback) override; - private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); diff --git a/interfaces/inner_kits/native_cpp/src/device_manager.cpp b/interfaces/inner_kits/native_cpp/src/device_manager.cpp index 4bedc0a57..b3cfbfcd5 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager.cpp @@ -14,7 +14,6 @@ */ #include "device_manager.h" - #include "device_manager_impl.h" namespace OHOS { diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 2b19918c0..d8556be56 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,12 +15,11 @@ #include "device_manager_impl.h" -#include "dm_constants.h" #include "dm_log.h" +#include "dm_constants.h" #include "device_manager_notify.h" #include "ipc_authenticate_device_req.h" -#include "ipc_check_authenticate_req.h" #include "ipc_get_trustdevice_req.h" #include "ipc_get_trustdevice_rsp.h" #include "ipc_rsp.h" @@ -28,7 +27,7 @@ #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.h" #include "ipc_get_authenticationparam_rsp.h" -#include "ipc_set_useroperation_req.h" + namespace OHOS { namespace DistributedHardware { @@ -46,6 +45,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh if (ret != DM_OK) { return ret; } + DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); DMLOG(DM_LOG_INFO, "success"); return DM_OK; @@ -63,6 +63,7 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) if (ret != DM_OK) { return ret; } + DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); DMLOG(DM_LOG_INFO, "DeviceManager::UnInitDeviceManager completed with errcode %d", ret); return DM_OK; @@ -91,9 +92,17 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons return DM_OK; } -int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) +virtual int32_t GetLocalDeviceInfo(DmDeviceInfo &info) { - return DM_OK; + DMLOG(DM_LOG_INFO, "DeviceManager::GetLocalDeviceInfo start"); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + if (ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + if (rsp->GetErrCode() == DEVICEMANAGER_OK) { + info = rsp->GetLocalDeviceInfo(); + } } int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, @@ -138,6 +147,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons 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) != DM_OK) { return DM_IPC_SEND_REQUEST_FAILED; @@ -187,11 +197,11 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ 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); if (ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { return DM_IPC_SEND_REQUEST_FAILED; @@ -208,6 +218,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ return DM_OK; } + int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { return DM_OK; -- Gitee From 6d8c8419b25cc09b9248d25a2ad8d22e05008bfb Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sun, 28 Nov 2021 16:24:03 +0800 Subject: [PATCH 016/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9native=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E4=B8=8B=E7=9A=84ipc=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/ipc/ipc_def.h | 1 - .../ipc/model/ipc_authenticate_device_req.h | 12 +- .../ipc/model/ipc_get_local_device_info_rsp.h | 42 +++++ ....h => ipc_notify_verify_auth_result_req.h} | 0 .../ipc/model/ipc_unauthenticate_device_req.h | 42 +++++ .../ipc/model/ipc_verify_authenticate_req.h | 41 +++++ .../native_cpp/include/device_manager.h | 8 +- .../native_cpp/include/device_manager_impl.h | 24 ++- .../native_cpp/src/device_manager_impl.cpp | 154 ++++++++++++------ .../src/ipc/lite/ipc_client_manager.cpp | 14 +- .../src/ipc/lite/ipc_client_server_proxy.cpp | 10 +- .../src/ipc/lite/ipc_client_stub.cpp | 4 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 19 +-- 13 files changed, 279 insertions(+), 92 deletions(-) create mode 100644 common/include/ipc/model/ipc_get_local_device_info_rsp.h rename common/include/ipc/model/{ipc_notify_check_auth_result_req.h => ipc_notify_verify_auth_result_req.h} (100%) create mode 100644 common/include/ipc/model/ipc_unauthenticate_device_req.h create mode 100644 common/include/ipc/model/ipc_verify_authenticate_req.h diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 059cc079b..3ab4cad23 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -44,7 +44,6 @@ enum IpcCmdID { AUTHENTICATE_DEVICE, UNAUTHENTICATE_DEVICE, VERIFY_AUTHENTICATE, - CHECK_AUTHENTICATION, SERVER_DEVICE_STATE_NOTIFY, SERVER_DEVICE_FOUND, SERVER_DISCOVER_FINISH, diff --git a/common/include/ipc/model/ipc_authenticate_device_req.h b/common/include/ipc/model/ipc_authenticate_device_req.h index e69b04976..3de3fa0f6 100644 --- a/common/include/ipc/model/ipc_authenticate_device_req.h +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -17,9 +17,7 @@ #define OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H #include "ipc_req.h" - #include "dm_device_info.h" -#include "dm_app_image_info.h" namespace OHOS { namespace DistributedHardware { @@ -36,14 +34,14 @@ public: deviceInfo_ = deviceInfo; } - const DmAppImageInfo& GetAppImageInfo() const + const int32_t GetAuthType() const { - return appImageInfo_; + return authType_; } - void SetAppImageInfo(const DmAppImageInfo &appImageInfo) + void SetAuthType(const int32_t& authType) { - appImageInfo_ = appImageInfo; + authType_ = authType; } const std::string& GetExtra() const @@ -57,7 +55,7 @@ public: } private: DmDeviceInfo deviceInfo_; - DmAppImageInfo appImageInfo_; + int32_t authType_; std::string extra_; }; } // namespace DistributedHardware 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..3f9854cbd --- /dev/null +++ b/common/include/ipc/model/ipc_get_local_device_info_rsp.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_GET_LOCAL_DEVICE_INFO_RSP_H +#define OHOS_DM_IPC_GET_LOCAL_DEVICE_INFO_RSP_H + +#include "ipc_rsp.h" +#include "dm_device_info.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_TRUSTDEVICE_RSP_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_notify_check_auth_result_req.h b/common/include/ipc/model/ipc_notify_verify_auth_result_req.h similarity index 100% rename from common/include/ipc/model/ipc_notify_check_auth_result_req.h rename to common/include/ipc/model/ipc_notify_verify_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..1b44b9336 --- /dev/null +++ b/common/include/ipc/model/ipc_unauthenticate_device_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_DM_IPC_UNAUTHENTICATE_DEVICE_REQ_H +#define OHOS_DM_IPC_UNAUTHENTICATE_DEVICE_REQ_H + +#include "ipc_req.h" +#include "dm_device_info.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..681ee9b6a --- /dev/null +++ b/common/include/ipc/model/ipc_verify_authenticate_req.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_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(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/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index cef97ab93..6f5cf498e 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef DEVICE_MANAGER_H -#define DEVICE_MANAGER_H +#ifndef OHOS_DEVICE_MANAGER_H +#define OHOS_DEVICE_MANAGER_H #include #include @@ -37,8 +37,8 @@ public: 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 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; 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 2f1d6425f..7659492c9 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -13,20 +13,18 @@ * limitations under the License. */ -#ifndef OHOS_DM_IMPL_H -#define OHOS_DM_IMPL_H +#ifndef OHOS_DEVICE_MANAGER_IMPL_H +#define OHOS_DEVICE_MANAGER_IMPL_H #include "device_manager.h" - #include "ipc_client_proxy.h" #include "ipc_client_manager.h" -#include "single_instance.h" - namespace OHOS { namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { -DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); +public: + static DeviceManagerImpl& GetInstance(); public: virtual int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) override; @@ -37,18 +35,26 @@ public: 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 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 DmDeviceInfo &deviceInfo) override; virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback) override; +private: + DeviceManagerImpl() = default; + ~DeviceManagerImpl() = default; + DeviceManagerImpl(const DeviceManagerImpl&) = delete; + DeviceManagerImpl& operator= (const DeviceManagerImpl&) = delete; + DeviceManagerImpl(DeviceManagerImpl&&) = delete; + DeviceManagerImpl& operator= (DeviceManagerImpl&&) = delete; private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IMPL_H + +#endif // OHOS_DEVICE_MANAGER_IMPL_H 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 d8556be56..f00994556 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -19,19 +19,23 @@ #include "dm_constants.h" #include "device_manager_notify.h" -#include "ipc_authenticate_device_req.h" -#include "ipc_get_trustdevice_req.h" -#include "ipc_get_trustdevice_rsp.h" #include "ipc_rsp.h" #include "ipc_req.h" +#include "ipc_get_local_device_info_rsp.h" +#include "ipc_get_trustdevice_req.h" +#include "ipc_get_trustdevice_rsp.h" #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.h" -#include "ipc_get_authenticationparam_rsp.h" - +#include "ipc_authenticate_device_req.h" +#include "ipc_verify_authenticate_req.h" namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); +DeviceManagerImpl & DeviceManagerImpl::GetInstance() +{ + static DeviceManagerImpl instance; + return instance; +} int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) { @@ -43,11 +47,12 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh int32_t ret = ipcClientProxy_->Init(pkgName); if (ret != DM_OK) { - return ret; + DMLOG(DM_LOG_ERROR, "InitDeviceManager error: proxy init failed ret: %d", ret); + return DM_INIT_FAILED; } DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); - DMLOG(DM_LOG_INFO, "success"); + DMLOG(DM_LOG_INFO, "InitDeviceManager success"); return DM_OK; } @@ -55,17 +60,18 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) { DMLOG(DM_LOG_INFO, "DeviceManager::UnInitDeviceManager start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager error: Invalid parameter"); + DMLOG(DM_LOG_ERROR, "UnInitDeviceManager error: Invalid parameter"); return DM_INVALID_VALUE; } int32_t ret = ipcClientProxy_->UnInit(pkgName); if (ret != DM_OK) { - return ret; + DMLOG(DM_LOG_ERROR, "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); + DMLOG(DM_LOG_INFO, "UnInitDeviceManager success"); return DM_OK; } @@ -74,7 +80,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons { DMLOG(DM_LOG_INFO, "DeviceManager::GetTrustedDeviceList start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList error: Invalid para"); return DM_INVALID_VALUE; } @@ -82,13 +88,20 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetExtra(extra); - if (ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp) != DM_OK) { + int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } - if (rsp->GetErrCode() == DM_OK) { - deviceList = rsp->GetDeviceVec(); + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + DMLOG(DM_LOG_INFO, "GetTrustedDeviceList error: failed ret: %d",ret); + return DM_IPC_RESPOND_ERROR; } - DMLOG(DM_LOG_INFO, "DeviceManager::GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); + + deviceList = rsp->GetDeviceVec(); + DMLOG(DM_LOG_INFO, "GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -97,12 +110,21 @@ virtual int32_t GetLocalDeviceInfo(DmDeviceInfo &info) DMLOG(DM_LOG_INFO, "DeviceManager::GetLocalDeviceInfo start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - if (ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp) != DEVICEMANAGER_OK) { - return DEVICEMANAGER_IPC_FAILED; + int32_t ret = ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "GetLocalDeviceInfo error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; } - if (rsp->GetErrCode() == DEVICEMANAGER_OK) { - info = rsp->GetLocalDeviceInfo(); + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + DMLOG(DM_LOG_INFO, "GetLocalDeviceInfo error: failed ret: %d",ret); + return DM_IPC_RESPOND_ERROR; } + + info = rsp->GetLocalDeviceInfo(); + DMLOG(DM_LOG_INFO, "GetLocalDeviceInfo completed"); + return DM_OK; } int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, @@ -110,12 +132,12 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, { DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); if (pkgName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "Invalid para"); + DMLOG(DM_LOG_ERROR, "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()); + DMLOG(DM_LOG_INFO, "RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -123,12 +145,12 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName { DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); + DMLOG(DM_LOG_ERROR, "UnRegisterDevStateCallback error: Invalid para"); return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + DMLOG(DM_LOG_INFO, "UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -137,7 +159,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons { DMLOG(DM_LOG_INFO, "DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); if (pkgName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "Invalid para"); + DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery error: Invalid para"); return DM_INVALID_VALUE; } @@ -149,15 +171,19 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons req->SetPkgName(pkgName); req->SetExtra(extra); req->SetSubscribeInfo(subscribeInfo); - if (ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp) != DM_OK) { + int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } - int32_t ret = rsp->GetErrCode(); + ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "DeviceManager StartDeviceDiscovery Failed with ret %d", ret); - return ret; + DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery error: Failed with ret %d", ret); + return DM_IPC_RESPOND_ERROR; } + + DMLOG(DM_LOG_INFO, "StartDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -165,7 +191,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint1 { DMLOG(DM_LOG_INFO, "DeviceManager::StopDeviceDiscovery start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); + DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery error: Invalid para"); return DM_INVALID_VALUE; } @@ -174,17 +200,20 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint1 std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetSubscribeId(subscribeId); - if (ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp) != DM_OK) { + int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } - int32_t ret = rsp->GetErrCode(); + ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery Failed with ret %d", ret); - return ret; + DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery error: Failed with ret %d", ret); + return DM_IPC_RESPOND_ERROR; } + DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); - DMLOG(DM_LOG_INFO, "DeviceManager::StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); + DMLOG(DM_LOG_INFO, "StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -193,7 +222,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ { DMLOG(DM_LOG_INFO, "DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); + DMLOG(DM_LOG_ERROR, "AuthenticateDevice error: Invalid para"); return DM_INVALID_VALUE; } @@ -203,15 +232,18 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ req->SetExtra(extra); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); - if (ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { + int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } - int32_t ret = rsp->GetErrCode(); + ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice Failed with ret %d", ret); - return ret; + DMLOG(DM_LOG_ERROR, "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()); @@ -221,33 +253,61 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { + DMLOG(DM_LOG_INFO, "DeviceManager::UnAuthenticateDevice start , pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice error: Invalid para"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetDeviceInfo(deviceInfo); + int32_t ret = ipcClientProxy_->SendRequest(UNAUTHENTICATE_DEVICE, req, rsp); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice error: Send Request failed ret: %d", ret); + return DM_IPC_SEND_REQUEST_FAILED; + } + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice error: Failed with ret %d", ret); + return DM_IPC_RESPOND_ERROR; + } + + std::string strDeviceId = deviceInfo.deviceId; + DeviceManagerNotify::GetInstance().UnRegisterAuthenticateCallback(pkgName, strDeviceId); + DMLOG(DM_LOG_INFO, "UnAuthenticateDevice 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) { - DMLOG(DM_LOG_INFO, "DeviceManager::CheckAuthentication start , pkgName: %s", pkgName.c_str()); + DMLOG(DM_LOG_INFO, "DeviceManager::VerifyAuthentication start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid para"); + DMLOG(DM_LOG_ERROR, "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(); + + 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) != DM_OK) { + int32_t ret = ipcClientProxy_->SendRequest(VERIFY_AUTHENTICATE, req, rsp); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "VerifyAuthentication error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "CheckAuthentication Failed with ret %d", ret); + DMLOG(DM_LOG_ERROR, "VerifyAuthentication error: Failed with ret %d", ret); return ret; } + DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); - DMLOG(DM_LOG_INFO, "DeviceManager::CheckAuthentication completed, pkgName: %s", pkgName.c_str()); + DMLOG(DM_LOG_INFO, "DeviceManager::VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); return DM_OK; } } // namespace DistributedHardware 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 34966d33a..e7a368a2e 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 @@ -23,7 +23,7 @@ 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"); @@ -31,11 +31,11 @@ int32_t IpcClientManager::Init(std::string &pkgName) } if (serverProxy_.Init() != DM_OK) { DMLOG(DM_LOG_ERROR, "server proxy init failed."); - return DEVICEMANAGER_INIT_FAILED; + return DM_INIT_FAILED; } if (IpcClientStub::GetInstance().Init() != DM_OK) { DMLOG(DM_LOG_ERROR, "ipcclientstub init failed."); - return DEVICEMANAGER_INIT_FAILED; + return DM_INIT_FAILED; } std::shared_ptr req = std::make_shared(); @@ -56,11 +56,11 @@ int32_t IpcClientManager::Init(std::string &pkgName) 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()); if (!IsInit(pkgName)) { - return DEVICEMANAGER_FAILED; + return DM_FAILED; } std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -79,12 +79,12 @@ int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr r { 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 1706784ef..20dd4464d 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 @@ -85,7 +85,7 @@ int IpcClientServerProxy::RegisterServerDeathCb(void) 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; + return DM_FAILED; } return DM_OK; } @@ -97,7 +97,7 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r IpcIo request; if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, request, data, MAX_DM_IPC_LEN) != DM_OK) { - return DEVICEMANAGER_FAILED; + return DM_FAILED; } { std::lock_guard autoLock(lock_); @@ -105,7 +105,7 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r if (serviceProxy_ != nullptr && serviceProxy_->Invoke(serviceProxy_, cmdCode, &request, &cmdCode, SendCmdResultCb) != 0) { DMLOG(DM_LOG_ERROR, "serviceProxy_ invoke failed."); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } } DMLOG(DM_LOG_INFO, "SendCmd:%d end", cmdCode); @@ -122,11 +122,11 @@ int32_t IpcClientServerProxy::Init(void) serviceProxy_ = GetServerProxy(); if (serviceProxy_ == nullptr) { DMLOG(DM_LOG_ERROR, "get ipc client proxy failed"); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } if (RegisterServerDeathCb() != DM_OK) { DMLOG(DM_LOG_ERROR, "register server death cb failed"); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } DMLOG(DM_LOG_INFO, "ServerProxyInit ok"); return DM_OK; 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 1eab12e20..d26a14a26 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 @@ -31,7 +31,7 @@ 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; + return DM_INPUT_PARA_INVALID; } uint32_t code = 0; @@ -52,7 +52,7 @@ int32_t IpcClientStub::Init() } if (RegisterIpcCallback(ClientIpcInterfaceMsgHandle, 0, IPC_WAIT_FOREVER, &clientIdentity_, nullptr) != 0) { DMLOG(DM_LOG_ERROR, "register ipc cb failed"); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } bInit = true; return DM_OK; 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 7596377e9..e5b72f260 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 @@ -27,12 +27,11 @@ #include "ipc_register_listener_req.h" #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.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_set_useroperation_req.h" +#include "ipc_verify_authenticate_req.h" namespace OHOS { namespace DistributedHardware { @@ -95,8 +94,8 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptrSetErrCode(DEVICEMANAGER_IPC_TRANSACTION_FAILED); - return DEVICEMANAGER_IPC_TRANSACTION_FAILED; + pRsp->SetErrCode(DM_IPC_TRANSACTION_FAILED); + return DM_IPC_TRANSACTION_FAILED; } for (int32_t i = 0; i < deviceNum; ++i) { pDmDeviceinfo = pDmDeviceinfo + i; @@ -117,9 +116,9 @@ ON_IPC_SET_REQUEST(GET_LOCAL_DEVICE_INFO, std::shared_ptr pBaseReq, IpcI ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, 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 size = 0; + uint32_t size = 0; DmDeviceInfo* dmDeviceInfo = (DmDeviceInfo *)IpcIoPopFlatObj(&reply, &size); if (dmDeviceInfo != nullptr) { pRsp->SetLocalDeviceInfo(*dmDeviceInfo); @@ -190,10 +189,10 @@ ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, IpcIo &reply, std::shared_ptr return DM_OK; } -ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, IpcIo &request, +ON_IPC_SET_REQUEST(VERIFY_AUTHENTICATE, 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); @@ -201,7 +200,7 @@ ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, IpcIo return DM_OK; } -ON_IPC_READ_RESPONSE(CHECK_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATE, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); return DM_OK; -- Gitee From 43f70c89cb6c2a7edb74c43ce0c3c17e491ee2aa Mon Sep 17 00:00:00 2001 From: puhui Date: Sun, 28 Nov 2021 19:57:25 +0800 Subject: [PATCH 017/110] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E9=80=82=E9=85=8D=EF=BC=8C=E7=BC=96=E8=AF=91=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- BUILD.gn | 6 +- common/BUILD.gn | 118 -------- common/include/constants/dm_constants.h | 209 ------------- common/include/dm_constants.h | 83 ++++++ common/include/ipc/ipc_def.h | 5 +- .../ipc/model/ipc_authenticate_device_req.h | 4 +- .../ipc/model/ipc_get_trustdevice_req.h | 4 +- .../ipc/model/ipc_get_trustdevice_rsp.h | 10 +- .../ipc/model/ipc_notify_dmfa_result_req.h | 42 --- .../model/ipc_notify_verify_auth_result_req.h | 4 +- .../ipc/model/ipc_verify_authenticate_req.h | 2 +- devicemanager.gni | 3 +- interfaces/inner_kits/native_cpp/BUILD.gn | 12 +- .../native_cpp/include/device_manager_impl.h | 4 +- .../include/ipc/lite/ipc_cmd_register.h | 113 ------- .../include/ipc/standard/ipc_cmd_register.h | 93 ------ .../native_cpp/src/device_manager_impl.cpp | 11 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 166 +++++------ .../src/ipc/standard/ipc_cmd_parser.cpp | 52 ++-- interfaces/kits/js/BUILD.gn | 16 +- ohos.build | 5 +- sa_profile/4802.xml | 8 +- services/devicemanagerservice/BUILD.gn | 22 +- .../include/adapter/decision_adapter.h | 2 + .../include/ipc/lite/ipc_cmd_register.h | 114 ------- .../include/ipc/standard/ipc_cmd_register.h | 94 ------ .../src/adapter/dm_adapter_manager.cpp | 4 +- .../dependency/softbus/softbus_session.cpp | 4 +- .../src/device_manager_service_listener.cpp | 5 +- .../src/deviceinfo/dm_device_info_manager.cpp | 2 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 22 +- .../src/ipc/lite/ipc_cmd_register.cpp | 68 ----- .../src/ipc/lite/ipc_server_listener.cpp | 6 +- .../src/ipc/lite/ipc_server_listenermgr.cpp | 6 +- .../src/ipc/lite/ipc_server_stub.cpp | 14 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 279 +++++++++--------- .../src/ipc/standard/ipc_cmd_register.cpp | 55 ---- .../ipc/standard/ipc_server_client_proxy.cpp | 6 +- .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 7 +- test/unittest/BUILD.gn | 7 +- test/unittest/device_manager_impl_test.cpp | 12 +- utils/BUILD.gn | 42 ++- utils/include/anonymous_string.h | 26 -- utils/include/cipher/encrypt_utils.h | 46 --- .../utils => utils/include}/dm_anonymous.h | 0 .../include/utils => utils/include}/dm_log.h | 17 +- .../utils => utils/include}/dm_random.h | 0 utils/include/ipc/lite/ipc_cmd_register.h | 7 +- utils/include/ipc/standard/ipc_cmd_register.h | 7 +- utils/include/log/dm_log.h | 31 -- utils/src/anonymous_string.cpp | 68 ----- utils/src/cipher/encrypt_utils.cpp | 152 ---------- .../src/utils => utils/src}/dm_anonymous.cpp | 0 {common/src/utils => utils/src}/dm_log.cpp | 0 {common/src/utils => utils/src}/dm_random.cpp | 0 utils/src/ipc/lite/ipc_cmd_register.cpp | 16 +- utils/src/ipc/standard/ipc_cmd_register.cpp | 10 +- utils/src/log/dm_log.cpp | 89 ------ 59 files changed, 484 insertions(+), 1728 deletions(-) delete mode 100644 common/BUILD.gn delete mode 100644 common/include/constants/dm_constants.h create mode 100644 common/include/dm_constants.h delete mode 100644 common/include/ipc/model/ipc_notify_dmfa_result_req.h delete mode 100644 interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h delete mode 100644 interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.h delete mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h delete mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h delete mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp delete mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp delete mode 100644 utils/include/anonymous_string.h delete mode 100644 utils/include/cipher/encrypt_utils.h rename {common/include/utils => utils/include}/dm_anonymous.h (100%) rename {common/include/utils => utils/include}/dm_log.h (60%) rename {common/include/utils => utils/include}/dm_random.h (100%) 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 rename {common/src/utils => utils/src}/dm_anonymous.cpp (100%) rename {common/src/utils => utils/src}/dm_log.cpp (100%) rename {common/src/utils => utils/src}/dm_random.cpp (100%) delete mode 100644 utils/src/log/dm_log.cpp diff --git a/BUILD.gn b/BUILD.gn index b4b2702f8..9a9e3a176 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -18,9 +18,9 @@ if (defined(ohos_lite)) { if (ohos_kernel_type == "liteos_m") { } else { features = [ - "common:devicemanagercommon", - #"services/devicemanagerservice:devicemanagerservice", - #"interfaces/inner_kits/native_cpp:devicemanagersdk", + "utils:devicemanagerutils", + "services/devicemanagerservice:devicemanagerservice", + "interfaces/inner_kits/native_cpp:devicemanagersdk", ] } } diff --git a/common/BUILD.gn b/common/BUILD.gn deleted file mode 100644 index 07d7ce0f9..000000000 --- a/common/BUILD.gn +++ /dev/null @@ -1,118 +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)) { - shared_library("devicemanagercommon") { - include_dirs = [ - "include", - "include/constants", - "include/ipc", - "include/ipc/model", - "include/utils", - ] - - 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/utils/dm_anonymous.cpp", - "src/utils/dm_log.cpp", - "src/utils/dm_random.cpp", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagercommon\"", - "LOG_DOMAIN=0xD004100", - ] - - 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", - "//utils/native/lite:utils", - ] - } -} else { - ohos_shared_library("devicemanagercommon") { - include_dirs = [ -# "//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", - "include", - "include/constants", - "include/ipc", - "include/ipc/model", - "include/utils", - ] - - sources = [ - "src/utils/dm_anonymous.cpp", - "src/utils/dm_log.cpp", - "src/utils/dm_random.cpp", - ] - - deps = [ - "//utils/native/base:utils", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagercommon\"", - "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/common/include/constants/dm_constants.h b/common/include/constants/dm_constants.h deleted file mode 100644 index 5c2e7e2af..000000000 --- a/common/include/constants/dm_constants.h +++ /dev/null @@ -1,209 +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_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 = "distributedhardware.devicemanager.resident"; - - 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; - - enum { - DM_FAILED = (-10000), - DM_NOT_INIT, - DM_POINT_NULL, - DM_INPUT_PARA_EMPTY, - DM_MALLOC_ERROR, - DM_INVALID_VALUE, - DM_IPC_TRANSACTION_FAILED, - DM_IPC_FLATTEN_OBJECT, - DM_IPC_COPY_FAILED, - DM_IPC_SEND_REQUEST_FAILED, - DM_SERVICE_NOT_READY, - DM_INT_MULTIPLE, - DM_MAKE_SHARED_FAIL, - DM_DEVICE_ALREADY_TRUSTED, - DM_HICHAIN_GROUP_CREATE_FAILED, - DM_HICHAIN_MEMBER_ADD_FAILED, - DM_HICHAIN_CREATE_CHANNEL_FAILED, - DM_OK = 0 - }; - - //Softbus - const std::string DM_CAPABILITY_OSD = "osdCapability"; - 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_DEVICEINFO_MAX_SIZE = 20; - - //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 FAIL = -1; - // const int32_t SUCCESS = 0; - // const int32_t ERROR_NOT_INIT = 1997; - // const int32_t ERROR_MAKE_SHARED_FAIL = 1998; - // const int32_t ERROR_INIT_MULTIPLE = 1999; - // 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 DEVICEMANAGER_FAILED = -10000; - // const int32_t DEVICEMANAGER_SERVICE_NOT_READY; - // const int32_t DEVICEMANAGER_DEVICE_ALREADY_TRUSTED; - // const int32_t DEVICEMANAGER_GET_TRUSTED_DEVICE_FAILED; - // const int32_t DEVICEMANAGER_ALREADY_INIT; - // const int32_t DEVICEMANAGER_INIT_FAILED; - // const int32_t DEVICEMANAGER_MALLOC_ERROR; - // const int32_t DEVICEMANAGER_LOCK_ERROR; - // const int32_t DEVICEMANAGER_INVALID_PARAM; - // const int32_t DEVICEMANAGER_COPY_FAILED; - // const int32_t DEVICEMANAGER_NULLPTR; - // const int32_t DEVICEMANAGER_DISCOVERY_FAILED; - // const int32_t DEVICEMANAGER_FLATTEN_OBJECT; - // const int32_t DEVICEMANAGER_WRITE_FAILED; - // const int32_t DEVICEMANAGER_IPC_FAILED; - // const int32_t DEVICEMANAGER_IPC_TRANSACTION_FAILED; - // const int32_t DEVICEMANAGER_IPC_NOT_REGISTER_FUNC; - // const int32_t HICHAIN_GROUP_CREATE_FAILED; - // const int32_t HICHAIN_MEMBER_ADD_FAILED; - // const int32_t HICHAIN_CREATE_CHANNEL_FAILED; - // const int32_t MSG_DECODE_PARA_FAILED; - // const int32_t ENCRYPT_UTILS_INVALID_PARAM; - // const int32_t ENCRYPT_UTILS_GCM_SETKEY_FAILED; - // const int32_t ENCRYPT_UTILS_GCM_CRYPT_FAILED; - // const int32_t ENCRYPT_UTILS_GCM_AUTH_DECRYPT_FAILED; - // const int32_t ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; - // const int32_t ENCRYPT_UTILS_AES_GCM_DECRYPT_FAILED; - // const int32_t ERR_GEN_RANDOM_PINTOKEN_FAILED; - // const int32_t PIN_CODE_CHECK_FAILED; - // const int32_t PIN_TOKEN_CHECK_FAILED; - // const int32_t DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; - // const int32_t DEVICEMANAGER_OPEN_SESSION_FAILED; - // const int32_t AUTH_PARA_INVALID; - // const int32_t ENCODE_DATA_ERROR; - // const int32_t DM_OK = 0; - - - - // 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; - - -} -} -#endif diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h new file mode 100644 index 000000000..1cfb2ec04 --- /dev/null +++ b/common/include/dm_constants.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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 = "distributedhardware.devicemanager.resident"; + + 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; + + enum { + DM_OK = 0, + DM_FAILED = 1000, + DM_NOT_INIT, + DM_INT_MULTIPLE, + DM_INIT_FAILED, + DM_UNINIT_FAILED, + DM_POINT_NULL, + DM_INPUT_PARA_EMPTY, + DM_INVALID_VALUE, + DM_FLATTEN_OBJECT, + DM_MALLOC_ERROR, + DM_COPY_FAILED, + DM_WRITE_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_SOFTBUS_FAILED = 3000, + + DM_HICHAIN_FAILED = 4000, + DM_HICHAIN_GROUP_CREATE_FAILED, + DM_HICHAIN_MEMBER_ADD_FAILED, + DM_HICHAIN_CREATE_CHANNEL_FAILED, + }; + + //Softbus + const std::string CAPABILITY_OSD = "osdCapability"; + 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_DEVICEINFO_MAX_SIZE = 20; + + //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; +} +} +#endif diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 3ab4cad23..477bc20f1 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -43,15 +43,12 @@ enum IpcCmdID { STOP_DEVICE_DISCOVER, AUTHENTICATE_DEVICE, UNAUTHENTICATE_DEVICE, - VERIFY_AUTHENTICATE, + VERIFY_AUTHENTICATION, SERVER_DEVICE_STATE_NOTIFY, SERVER_DEVICE_FOUND, SERVER_DISCOVER_FINISH, SERVER_AUTH_RESULT, SERVER_VERIFY_AUTH_RESULT, -// SERVER_GET_AUTHENTCATION_INFO, -// SERVER_USER_AUTHORIZATION_OPERATION, -// SERVER_DEVICEMANAGER_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 3de3fa0f6..931ec6abe 100644 --- a/common/include/ipc/model/ipc_authenticate_device_req.h +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -34,12 +34,12 @@ public: deviceInfo_ = deviceInfo; } - const int32_t GetAuthType() const + int32_t GetAuthType() { return authType_; } - void SetAuthType(const int32_t& authType) + void SetAuthType(int32_t authType) { authType_ = authType; } diff --git a/common/include/ipc/model/ipc_get_trustdevice_req.h b/common/include/ipc/model/ipc_get_trustdevice_req.h index 7d78e0fc8..7ac969c7c 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_req.h +++ b/common/include/ipc/model/ipc_get_trustdevice_req.h @@ -20,8 +20,8 @@ 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 { diff --git a/common/include/ipc/model/ipc_get_trustdevice_rsp.h b/common/include/ipc/model/ipc_get_trustdevice_rsp.h index b42e592b5..3ba8832de 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_rsp.h +++ b/common/include/ipc/model/ipc_get_trustdevice_rsp.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DM_IPC_GET_TRUSTDEVICE_RSP_H -#define OHOS_DM_IPC_GET_TRUSTDEVICE_RSP_H +#ifndef OHOS_DM_IPC_GET_TRUST_DEVICE_RSP_H +#define OHOS_DM_IPC_GET_TRUST_DEVICE_RSP_H #include @@ -24,8 +24,8 @@ 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 { @@ -41,4 +41,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IPC_GET_TRUSTDEVICE_RSP_H +#endif // OHOS_DM_IPC_GET_TRUST_DEVICE_RSP_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 deleted file mode 100644 index 741ba7e50..000000000 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ /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. - */ - -#ifndef OHOS_DM_IPC_NOTIFY_DMFA_RESULT_REQ_H -#define OHOS_DM_IPC_NOTIFY_DMFA_RESULT_REQ_H - -#include - -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcNotifyDMFAResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyDMFAResultReq); -public: - std::string GetJsonParam() const - { - return JsonParam_; - } - - void SetJsonParam(std::string& JsonParam) - { - JsonParam_ = JsonParam; - } -private: - std::string JsonParam_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_NOTIFY_AUTH_RESULT_REQ_H 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 index 9499bc0f7..233babfc6 100644 --- a/common/include/ipc/model/ipc_notify_verify_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_verify_auth_result_req.h @@ -22,8 +22,8 @@ namespace OHOS { namespace DistributedHardware { -class IpcNotifyCheckAuthResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyCheckAuthResultReq); +class IpcNotifyVerifyAuthResultReq : public IpcReq { +DECLARE_IPC_MODEL(IpcNotifyVerifyAuthResultReq); public: std::string GetDeviceId() const { diff --git a/common/include/ipc/model/ipc_verify_authenticate_req.h b/common/include/ipc/model/ipc_verify_authenticate_req.h index 681ee9b6a..da2b5472c 100644 --- a/common/include/ipc/model/ipc_verify_authenticate_req.h +++ b/common/include/ipc/model/ipc_verify_authenticate_req.h @@ -28,7 +28,7 @@ public: return authPara_; } - void SetAuthPara(std::string &authPara) + void SetAuthPara(const std::string &authPara) { authPara_ = authPara; } diff --git a/devicemanager.gni b/devicemanager.gni index e24d59514..b226ba5a8 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -14,10 +14,11 @@ #------------------------device manager------------------------------# devicemanager_path = "//foundation/distributedhardware/devicemanager" -ext_path = "${devicemanager_path}/ext" common_path = "${devicemanager_path}/common" +utils_path = "${devicemanager_path}/utils" services_path = "${devicemanager_path}/services" innerkits_path = "${devicemanager_path}/interfaces/inner_kits" +ext_path = "${devicemanager_path}/ext" #--------------------------softbus----------------------------------# diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index eb0422718..1afa35af8 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -26,10 +26,10 @@ if (defined(ohos_lite)) { "include/ipc/lite", "include/notify", "${common_path}/include", - "${common_path}/include/constants", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include/utils", + "${utils_path}/include", + "${utils_path}/include/ipc/lite", ] include_dirs += [ "//utils/native/lite/include", @@ -59,7 +59,7 @@ if (defined(ohos_lite)) { ] deps = [ - "${common_path}:devicemanagercommon", + "${utils_path}:devicemanagerutils", "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", "//foundation/communication/ipc_lite:liteipc_adapter", "//foundation/distributedschedule/samgr_lite/samgr:samgr", @@ -75,10 +75,10 @@ if (defined(ohos_lite)) { "include/ipc/standard", "include/notify", "${common_path}/include", - "${common_path}/include/constants", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include/utils", + "${utils_path}/include", + "${utils_path}/include/ipc/standard", "//third_party/json/include", "//utils/native/base/include", "//utils/system/safwk/native/include", @@ -96,7 +96,7 @@ if (defined(ohos_lite)) { ] deps = [ - "${common_path}:devicemanagercommon", + "${utils_path}:devicemanagerutils", "//utils/native/base:utils", ] 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 7659492c9..a718f44f2 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -47,9 +47,9 @@ private: DeviceManagerImpl() = default; ~DeviceManagerImpl() = default; DeviceManagerImpl(const DeviceManagerImpl&) = delete; - DeviceManagerImpl& operator= (const DeviceManagerImpl&) = delete; + DeviceManagerImpl& operator = (const DeviceManagerImpl&) = delete; DeviceManagerImpl(DeviceManagerImpl&&) = delete; - DeviceManagerImpl& operator= (DeviceManagerImpl&&) = delete; + DeviceManagerImpl& operator = (DeviceManagerImpl&&) = delete; private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); diff --git a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h deleted file mode 100644 index 36c20961f..000000000 --- a/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_cmd_register.h +++ /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. - */ - -#ifndef OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H - -#include -#include - -#include "liteipc_adapter.h" -#include "single_instance.h" - -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) - { - onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); - }; - 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_; - std::unordered_map onIpcCmdFuncMap_; - std::unordered_map onIpcServerCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.h deleted file mode 100644 index dc852f57e..000000000 --- a/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_cmd_register.h +++ /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. - */ - -#ifndef OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H -#define OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H - -#include -#include - -#include "iremote_broker.h" -#include "single_instance.h" - -#include "ipc_types.h" -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ - static int32_t IpcCmdProcess##cmdCode(paraA, paraB) - -using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); -using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); -using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); - -class IpcCmdRegister { -DECLARE_SINGLE_INSTANCE(IpcCmdRegister); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - int32_t SetRequest(int32_t cmdCode, 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_; - std::unordered_map onIpcCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_IPC_CMD_PARSER_H \ No newline at end of file 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 f00994556..e7c7808fc 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -27,6 +27,7 @@ #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.h" #include "ipc_authenticate_device_req.h" +#include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" namespace OHOS { @@ -84,8 +85,8 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons 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); int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); @@ -105,7 +106,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons return DM_OK; } -virtual int32_t GetLocalDeviceInfo(DmDeviceInfo &info) +int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &info) { DMLOG(DM_LOG_INFO, "DeviceManager::GetLocalDeviceInfo start"); std::shared_ptr req = std::make_shared(); @@ -294,13 +295,13 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetAuthPara(authPara); - int32_t ret = ipcClientProxy_->SendRequest(VERIFY_AUTHENTICATE, req, rsp); + int32_t ret = ipcClientProxy_->SendRequest(VERIFY_AUTHENTICATION, req, rsp); if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "VerifyAuthentication error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } - int32_t ret = rsp->GetErrCode(); + ret = rsp->GetErrCode(); if (ret != DM_OK) { DMLOG(DM_LOG_ERROR, "VerifyAuthentication error: Failed with ret %d", ret); return ret; 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 e5b72f260..406dad77a 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 @@ -73,7 +73,7 @@ ON_IPC_READ_RESPONSE(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &reply, std::shar 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(); @@ -85,7 +85,7 @@ ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, IpcI 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); @@ -189,7 +189,7 @@ ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, IpcIo &reply, std::shared_ptr return DM_OK; } -ON_IPC_SET_REQUEST(VERIFY_AUTHENTICATE, std::shared_ptr pBaseReq, IpcIo &request, +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); @@ -200,7 +200,7 @@ ON_IPC_SET_REQUEST(VERIFY_AUTHENTICATE, std::shared_ptr pBaseReq, IpcIo return DM_OK; } -ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATE, IpcIo &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); return DM_OK; @@ -271,7 +271,7 @@ 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); @@ -279,10 +279,10 @@ ON_IPC_CMD(SERVER_AUTH_RESULT, IpcIo &reply) DMLOG(DM_LOG_ERROR, "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); @@ -295,83 +295,83 @@ ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, IpcIo &reply) DMLOG(DM_LOG_ERROR, "OnAuthResult, get para failed"); return; } - DeviceManagerNotify::GetInstance().OnCheckAuthResult(pkgName, deviceId, resultCode, flag); + DeviceManagerNotify::GetInstance().OnVerifyAuthResult(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 DM_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 DM_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 DM_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 DM_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DM_OK; -} - -ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) -{ - size_t len = 0; - std::string packagename = (const char *)IpcIoPopString(&reply, &len); - size_t jsonLen = 0; - std::string paramJson = (const char *)IpcIoPopString(&reply, &jsonLen); - DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); -} +//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 DM_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 DM_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 DM_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 DM_OK; +//} +// +//ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) +//{ +// pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); +// return DM_OK; +//} +// +//ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) +//{ +// size_t len = 0; +// std::string packagename = (const char *)IpcIoPopString(&reply, &len); +// size_t jsonLen = 0; +// std::string paramJson = (const char *)IpcIoPopString(&reply, &jsonLen); +// DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); +//} } // 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 0a97b6826..c060ca056 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 @@ -28,9 +28,7 @@ #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" namespace OHOS { namespace DistributedHardware { @@ -74,7 +72,7 @@ ON_IPC_READ_RESPONSE(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &reply, s 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)) { @@ -90,7 +88,7 @@ ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, Mess 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) { @@ -161,7 +159,7 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag std::string pkgName = pReq->GetPkgName(); std::string extra = pReq->GetExtra(); DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); - DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); +// DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); @@ -175,24 +173,24 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag DMLOG(DM_LOG_ERROR, "write deviceInfo 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 DM_IPC_FLATTEN_OBJECT; - } - if (!data.WriteInt32(appThumbnailLen)) { - DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnailLen failed"); - return DM_IPC_FLATTEN_OBJECT; - } - if (appIconLen > 0 && !data.WriteRawData(imageInfo.GetAppIcon(), appIconLen)) { - DMLOG(DM_LOG_ERROR, "write imageinfo appIcon failed"); - return DM_IPC_FLATTEN_OBJECT; - } - if (appThumbnailLen > 0 && !data.WriteRawData(imageInfo.GetAppThumbnail(), appThumbnailLen)) { - DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnail 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 DM_IPC_FLATTEN_OBJECT; +// } +// if (!data.WriteInt32(appThumbnailLen)) { +// DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnailLen failed"); +// return DM_IPC_FLATTEN_OBJECT; +// } +// if (appIconLen > 0 && !data.WriteRawData(imageInfo.GetAppIcon(), appIconLen)) { +// DMLOG(DM_LOG_ERROR, "write imageinfo appIcon failed"); +// return DM_IPC_FLATTEN_OBJECT; +// } +// if (appThumbnailLen > 0 && !data.WriteRawData(imageInfo.GetAppThumbnail(), appThumbnailLen)) { +// DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnail failed"); +// return DM_IPC_FLATTEN_OBJECT; +// } return DM_OK; } @@ -202,9 +200,9 @@ ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr< 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 DM_IPC_FLATTEN_OBJECT; @@ -212,7 +210,7 @@ ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, Messa return DM_OK; } -ON_IPC_READ_RESPONSE(CHECK_AUTHENTICATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index bcd79c508..ca930a219 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -16,18 +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", "//foundation/ace/napi/native_engine", "//foundation/ace/napi/interfaces/kits", "//utils/native/base/include", - "include", - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/utils", - "${common_path}/include/constants", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/standard", ] sources = [ @@ -36,7 +36,7 @@ ohos_shared_library("devicemanager") { ] deps = [ - "${common_path}:devicemanagercommon", + "${utils_path}:devicemanagerutils", "//foundation/ace/napi:ace_napi", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//utils/native/base:utils", diff --git a/ohos.build b/ohos.build index beca5c3b1..b12a0744e 100644 --- a/ohos.build +++ b/ohos.build @@ -12,14 +12,13 @@ "device_manager.h", "device_manager_callback.h", "dm_device_info.h", - "dm_subscribe_info.h", - "dm_app_image_info.h" + "dm_subscribe_info.h" ] } } ], "module_list": [ - "//foundation/distributedhardware/devicemanager/common:devicemanagercommon", + "//foundation/distributedhardware/devicemanager/utils:devicemanagerutils", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager_native_js", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice:devicemanagerservice", 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 index f31a5da96..c769f7cc9 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -34,11 +34,12 @@ if (defined(ohos_lite)) { "include/ipc", "include/ipc/lite", "${common_path}/include", - "${common_path}/include/constants", - "${common_path}/include/utils", "${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", ] @@ -75,7 +76,6 @@ if (defined(ohos_lite)) { "src/ipc/lite/ipc_server_listenermgr.cpp", "src/ipc/lite/ipc_server_main.cpp", "src/ipc/lite/ipc_server_stub.cpp", - "src/ipc/lite/ipc_cmd_register.cpp", ] defines = [ @@ -87,7 +87,7 @@ if (defined(ohos_lite)) { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", - "${common_path}:devicemanagercommon", + "${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", @@ -114,12 +114,13 @@ if (defined(ohos_lite)) { "include/ipc", "include/ipc/standard", "${common_path}/include", - "${common_path}/include/constants", - "${common_path}/include/utils", "${common_path}/include/ipc", "${common_path}/include/ipc/model", + "${utils_path}/include", + "${utils_path}/include/ipc/standard", "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/ipc/lite", + "${innerkits_path}/native_cpp/include/ipc", + "${innerkits_path}/native_cpp/include/ipc/standard", "//utils/native/base/include", "//utils/system/safwk/native/include", "//base/security/deviceauth/interfaces/innerkits", @@ -135,17 +136,18 @@ if (defined(ohos_lite)) { "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", - "src/dependency/hichain/hichain_connector.cpp", +# "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", - "src/dependency/softbus/softbus_session.cpp", +# "src/dependency/softbus/softbus_session.cpp", "src/ipc/standard/ipc_cmd_parser.cpp", "src/ipc/standard/ipc_server_listener.cpp", "src/ipc/standard/ipc_server_client_proxy.cpp", "src/ipc/standard/ipc_server_stub.cpp", - "src/ipc/standard/ipc_cmd_register.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", diff --git a/services/devicemanagerservice/include/adapter/decision_adapter.h b/services/devicemanagerservice/include/adapter/decision_adapter.h index e62529e5e..a9c0f5daa 100644 --- a/services/devicemanagerservice/include/adapter/decision_adapter.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.h @@ -19,6 +19,8 @@ #include #include +#include "dm_device_info.h" + namespace OHOS { namespace DistributedHardware { class IDecisionAdapter { diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h b/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h deleted file mode 100644 index 615e07b91..000000000 --- a/services/devicemanagerservice/include/ipc/lite/ipc_cmd_register.h +++ /dev/null @@ -1,114 +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_IPC_CMD_PARSER_H -#define OHOS_DM_IPC_CMD_PARSER_H - -#include -#include -#include - -#include "liteipc_adapter.h" -#include "single_instance.h" - -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterServerCmdProcessFunc(cmdCode, IpcServerCmdProcess##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 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); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - void RegisterServerCmdProcessFunc(int32_t cmdCode, OnIpcServerCmdFunc onIpcServerCmdFunc) - { - onIpcServerCmdFuncMap_.emplace(cmdCode, onIpcServerCmdFunc); - }; - 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_; - std::unordered_map onIpcCmdFuncMap_; - std::unordered_map onIpcServerCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h b/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h deleted file mode 100644 index ce3123d25..000000000 --- a/services/devicemanagerservice/include/ipc/standard/ipc_cmd_register.h +++ /dev/null @@ -1,94 +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_IPC_CMD_PARSER_H -#define OHOS_DM_IPC_CMD_PARSER_H - -#include -#include -#include - -#include "iremote_broker.h" -#include "single_instance.h" - -#include "ipc_types.h" -#include "ipc_req.h" -#include "ipc_rsp.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() \ - { \ - IpcCmdRegister::GetInstance().RegisterSetRequestFunc(cmdCode, IpcSetRequest##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterReadResponseFunc(cmdCode, IpcReadResponse##cmdCode); \ - } \ - }; \ - 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() \ - { \ - IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ - } \ - }; \ - IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ - static int32_t IpcCmdProcess##cmdCode(paraA, paraB) - -using SetIpcRequestFunc = int32_t (*)(std::shared_ptr pBaseReq, MessageParcel &data); -using ReadResponseFunc = int32_t (*)(MessageParcel &reply, std::shared_ptr pBaseRsp); -using OnIpcCmdFunc = int32_t (*)(MessageParcel &data, MessageParcel &reply); - -class IpcCmdRegister { -DECLARE_SINGLE_INSTANCE(IpcCmdRegister); -public: - void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) - { - setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); - }; - void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) - { - readResponseFuncMap_.emplace(cmdCode, readResponseFunc); - }; - void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) - { - onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); - }; - int32_t SetRequest(int32_t cmdCode, 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_; - std::unordered_map onIpcCmdFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_CMD_PARSER_H \ No newline at end of file diff --git a/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp index e7b847994..fc1cce5ae 100644 --- a/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp @@ -35,12 +35,12 @@ std::shared_ptr DmAdapterManager::GetDecisionAdapter() return decisionAdapterPtr_; } -std::shared_ptr DmAdapterManager::GetProfileAdapter() +std::shared_ptr DmAdapterManager::GetProfileAdapter() { return profileAdapterPtr_; } -std::shared_ptr DmAdapterManager::GetCryptoAdapter() +std::shared_ptr DmAdapterManager::GetCryptoAdapter() { return cryptoAdapterPtr_; } diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 9e07c9a0d..0b5ec5240 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -32,7 +32,7 @@ SoftbusSession::SoftbusSession() : sessionIdSet_(), messages_() int32_t ret = CreateSessionServer(DM_PKG_NAME, DM_SESSION_NAME, &sessionListener); if (ret != DM_OK) { DMLOG(DM_LOG_DEBUG, "CreateSessionServer failed"); - return DEVICEMANAGER_CREATE_SESSION_SERVER_FAILED; + return DM_CREATE_SESSION_SERVER_FAILED; } } @@ -89,7 +89,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) 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; + return DM_MALLOC_ERROR; } int32_t outLen = 0; int32_t ret = EncryptUtils::MbedtlsEncrypt((const uint8_t *)message.c_str(), message.size(), buf, MSG_MAX_SIZE, diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index aa87dd8a2..7ac01c381 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -22,11 +22,10 @@ #include "dm_anonymous.h" #include "ipc_notify_auth_result_req.h" -#include "ipc_notify_check_auth_result_req.h" +#include "ipc_notify_verify_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 { @@ -98,7 +97,7 @@ void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName { // DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", // GetAnonyString(authParam).c_str(), resultCode); - std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); pReq->SetDeviceId(deviceId); diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 479669058..1350d7d48 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -29,7 +29,7 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co { int32_t ret = softbusConnectorPtr_->GetTrustedDeviceList(deviceList); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed"); + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed"); return ret; } diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 872c0eb24..be23c72d9 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -21,11 +21,10 @@ #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" -#include "ipc_notify_check_auth_result_req.h" +#include "ipc_notify_verify_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_stub.h" namespace OHOS { @@ -99,14 +98,14 @@ ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo & std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string deviceId = pReq->GetDeviceId(); - int32_t pinToken = pReq->GetPinToken(); + 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()); - IpcIoPushInt32(&request, pinToken); + IpcIoPushString(&request, token); IpcIoPushInt32(&request, status); IpcIoPushInt32(&request, reason); return DM_OK; @@ -118,7 +117,7 @@ ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr p return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, +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); @@ -135,7 +134,7 @@ ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, I return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); return DM_OK; @@ -220,7 +219,7 @@ ON_IPC_SERVER_CMD(UNAUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, ret); } -ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATE, IpcIo &req, IpcIo &reply) +ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATION, IpcIo &req, IpcIo &reply) { DMLOG(DM_LOG_INFO, "VerifyAuthentication service listener."); std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); @@ -230,15 +229,6 @@ ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATE, IpcIo &req, IpcIo &reply) 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 = DeviceManagerService::GetInstance().CheckAuthentication(authPara); -// IpcIoPushInt32(&reply, ret); -} - //ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) //{ // size_t len = 0; diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.cpp deleted file mode 100644 index 887337470..000000000 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_register.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 "ipc_cmd_register.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) -{ - 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; - } - return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); -} - -int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - 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; - } - return (readResponseMapIter->second)(reply, pBaseRsp); -} - -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; - } - (onIpcCmdMapIter->second)(reply); - 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; - } - (onIpcServerCmdMapIter->second)(req, reply); - 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 index 7a5083f4b..6961b8944 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -40,7 +40,7 @@ int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity * CommonSvcId svcId; if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DM_OK) { DMLOG(DM_LOG_ERROR, "get identity failed."); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } CommonSvcToIdentity(&svcId, svc); return DM_OK; @@ -52,14 +52,14 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { DMLOG(DM_LOG_ERROR, "ondevice found callback get listener failed."); - return DEVICEMANAGER_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) { DMLOG(DM_LOG_DEBUG, "SetRequest failed cmdCode:%d", cmdCode); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp index c54d83827..f172e47e6 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp @@ -26,7 +26,7 @@ int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const Commo { if (pkgName == "" || svcId == nullptr) { DMLOG(DM_LOG_ERROR, "invalid param"); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } DMLOG(DM_LOG_INFO, "new listener register:%s", pkgName.c_str()); std::lock_guard autoLock(lock_); @@ -38,13 +38,13 @@ int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonS { if (pkgName == "" || svcId == nullptr) { DMLOG(DM_LOG_ERROR, "invalid param"); - return DEVICEMANAGER_FAILED; + return DM_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; + return DM_FAILED; } *svcId = iter->second; return DM_OK; diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp index aeff02448..ffd711bc7 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -56,7 +56,7 @@ static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, voi (void)data; if (arg == NULL) { DMLOG(DM_LOG_ERROR, "package name is NULL."); - return DEVICEMANAGER_INVALID_PARAM; + return DM_INVALID_VALUE; } CommonSvcId svcId = {0}; std::string pkgName = (const char *)arg; @@ -64,7 +64,7 @@ static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, voi DMLOG(DM_LOG_ERROR, "not found client by package name."); free(arg); arg = NULL; - return DEVICEMANAGER_FAILED; + return DM_FAILED; } IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); free(arg); @@ -88,7 +88,7 @@ int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) SvcIdentity *svc = IpcIoPopSvc(req); if (name == NULL || svc == NULL || len == 0) { DMLOG(DM_LOG_ERROR, "get para failed"); - return DEVICEMANAGER_INVALID_PARAM; + return DM_INVALID_VALUE; } CommonSvcId svcId = {0}; @@ -106,12 +106,12 @@ int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) char *pkgName = (char *)malloc(len + 1); if (pkgName == NULL) { DMLOG(DM_LOG_ERROR, "malloc failed!"); - return DEVICEMANAGER_MALLOC_ERROR; + return DM_MALLOC_ERROR; } if (strcpy_s(pkgName, len + 1, (const char *)name) != DM_OK) { DMLOG(DM_LOG_ERROR, "strcpy_s failed!"); free(pkgName); - return DEVICEMANAGER_COPY_FAILED; + return DM_COPY_FAILED; } uint32_t cbId = 0; RegisterDeathCallback(NULL, sid, DeathCb, pkgName, &cbId); @@ -127,12 +127,12 @@ int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) std::string pkgName = (const char *)IpcIoPopString(req, &len); if (pkgName == "" || len == 0) { DMLOG(DM_LOG_ERROR, "get para failed"); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } CommonSvcId svcId; if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_OK) { DMLOG(DM_LOG_ERROR, "not found listener by package name."); - return DEVICEMANAGER_FAILED; + return DM_FAILED; } int32_t ret = IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); if (ret == DM_OK) { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 5e7d1a879..3cf7c0991 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -14,18 +14,20 @@ */ #include -#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_verify_auth_result_req.h" +#include "ipc_cmd_register.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_stub.h" -#include "ipc_notify_dmfa_result_req.h" #include "dm_constants.h" #include "dm_log.h" +#include "dm_subscribe_info.h" +#include "dm_device_info.h" +#include "device_manager_service.h" namespace OHOS { namespace DistributedHardware { @@ -37,15 +39,15 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(deviceState)) { DMLOG(DM_LOG_ERROR, "write state failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } return DM_OK; } @@ -64,15 +66,15 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, Messag DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteInt16(subscribeId)) { DMLOG(DM_LOG_ERROR, "write subscribeId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } return DM_OK; } @@ -91,15 +93,15 @@ ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, Mes int32_t result = pReq->GetResult(); if (!data.WriteString(pkgName)) { DMLOG(DM_LOG_ERROR, "write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteInt16(subscribeId)) { DMLOG(DM_LOG_ERROR, "write subscribeId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } return DM_OK; } @@ -115,28 +117,28 @@ ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, Message std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string deviceId = pReq->GetDeviceId(); - int32_t pinToken = pReq->GetPinToken(); + std::string token = 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; + return DM_FLATTEN_OBJECT; } if (!data.WriteString(deviceId)) { DMLOG(DM_LOG_ERROR, "write deviceId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } - if (!data.WriteInt32(pinToken)) { - DMLOG(DM_LOG_ERROR, "write pinToken failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + if (!data.WriteString(token)) { + DMLOG(DM_LOG_ERROR, "write token failed"); + return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(status)) { DMLOG(DM_LOG_ERROR, "write status failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(reason)) { DMLOG(DM_LOG_ERROR, "write reason failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } return DM_OK; } @@ -147,33 +149,33 @@ ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseReq, MessageParcel &data) +ON_IPC_SET_REQUEST(SERVER_VERIFY_AUTH_RESULT, 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 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; + return DM_FLATTEN_OBJECT; } if (!data.WriteString(deviceId)) { DMLOG(DM_LOG_ERROR, "write deviceId failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(flag)) { DMLOG(DM_LOG_ERROR, "write flag failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_FLATTEN_OBJECT; } return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; @@ -184,20 +186,21 @@ 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 = DeviceManagerService::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; - } + //TODO: +// DmDeviceInfo *info = nullptr; +// int32_t infoNum = 0; +// int32_t result = DeviceManagerService::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 DM_WRITE_FAILED; +// } return DM_OK; } @@ -208,7 +211,7 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; + return DM_WRITE_FAILED; } return DM_OK; } @@ -219,7 +222,7 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; + return DM_WRITE_FAILED; } return DM_OK; } @@ -229,7 +232,7 @@ 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 = DEVICEMANAGER_NULLPTR; + int32_t result = DM_POINT_NULL; if (subscribeInfo != nullptr) { DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); @@ -237,7 +240,7 @@ ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) } if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; + return DM_WRITE_FAILED; } return DM_OK; } @@ -247,10 +250,10 @@ 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 = DeviceManagerService::GetInstance().StopDiscovery(pkgName, subscribeId); + int32_t result = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; + return DM_WRITE_FAILED; } return DM_OK; } @@ -261,115 +264,107 @@ ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) std::string extra = data.ReadString(); std::string deviceId = data.ReadString();; int32_t authType = data.ReadInt32(); - 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 = DM_OK; - if (deviceInfo != nullptr) { - result = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); + result = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, nullptr, extra); } if (!reply.WriteInt32(result)) { DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; + return DM_WRITE_FAILED; } return DM_OK; } -ON_IPC_CMD(CHECK_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) { std::string authPara = data.ReadString(); - int32_t result = DeviceManagerService::GetInstance().CheckAuthentication(authPara); - if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); - return DEVICEMANAGER_WRITE_FAILED; - } +// int32_t result = DeviceManagerService::GetInstance().VerifyAuthentication(authPara); +// if (!reply.WriteInt32(result)) { +// DMLOG(DM_LOG_ERROR, "write result failed"); +// return DM_WRITE_FAILED; +// } return DM_OK; } -ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) -{ - std::string packName = data.ReadString(); - DmAuthParam authParam; - int32_t ret = DM_OK; - DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); - DeviceManagerService::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 DM_OK; -} - -ON_IPC_CMD(SERVER_USER_AUTHORIZATION_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)) { - 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 DM_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} +//ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) +//{ +// std::string packName = data.ReadString(); +// DmAuthParam authParam; +// int32_t ret = DM_OK; +// DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); +// DeviceManagerService::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 = DM_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 DM_WRITE_FAILED; +// } +// +// if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { +// if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { +// DMLOG(DM_LOG_ERROR, "write appIcon failed"); +// return DM_WRITE_FAILED; +// } +// } +// +// if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { +// if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { +// DMLOG(DM_LOG_ERROR, "write appThumbnail failed"); +// return DM_WRITE_FAILED; +// } +// } +// +// return DM_OK; +//} +// +//ON_IPC_CMD(SERVER_USER_AUTHORIZATION_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)) { +// DMLOG(DM_LOG_ERROR, "write result failed"); +// return DM_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 DM_FLATTEN_OBJECT; +// } +// if (!data.WriteString(paramJson)) { +// DMLOG(DM_LOG_ERROR, "write paramJson failed"); +// return DM_FLATTEN_OBJECT; +// } +// return DM_OK; +//} +// +//ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) +//{ +// pBaseRsp->SetErrCode(reply.ReadInt32()); +// return DM_OK; +//} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp deleted file mode 100644 index 741a250e2..000000000 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_register.cpp +++ /dev/null @@ -1,55 +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_cmd_register.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, MessageParcel &data) -{ - 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; - } - return (setRequestMapIter->second)(pBaseReq, data); -} - -int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - 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; - } - return (readResponseMapIter->second)(reply, pBaseRsp); -} - -int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &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; - } - return (onIpcCmdMapIter->second)(data, reply); -} -} // 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 index a5e959d17..bb9f1c9a2 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp @@ -29,18 +29,18 @@ int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr r sptr remote = Remote(); if (remote == nullptr) { DMLOG(DM_LOG_ERROR, "remote service null"); - return DEVICEMANAGER_NULLPTR; + return DM_POINT_NULL; } MessageParcel data; MessageParcel reply; MessageOption option; if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) { - return DEVICEMANAGER_FAILED; + return DM_IPC_FAILED; } if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_FAILED; } return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp index 6b282da4d..346ce2535 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp @@ -27,7 +27,7 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr 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 DM_POINT_NULL; } return listener->SendCmd(cmdCode, req, rsp); } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp index 0675cb8bc..81bb37d6a 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -27,6 +27,7 @@ #include "dm_constants.h" #include "dm_log.h" +#include "device_manager_service.h" // #include "ipc_server_adapter.h" #include "ipc_cmd_register.h" @@ -91,7 +92,7 @@ int32_t IpcServerStub::OnRemoteRequest(uint32_t code, DMLOG(DM_LOG_INFO, "code = %d, flags= %d.", code, option.GetFlags()); int32_t ret = DM_OK; ret = IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply); - if (ret == DEVICEMANAGER_IPC_NOT_REGISTER_FUNC) { + if (ret == DM_IPC_NOT_REGISTER_FUNC) { DMLOG(DM_LOG_WARN, "unsupport code: %d", code); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } @@ -112,7 +113,7 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< { if (pkgName.empty() || listener == nullptr) { DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); - return DEVICEMANAGER_NULLPTR; + return DM_POINT_NULL; } DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); @@ -136,7 +137,7 @@ int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) { if (pkgName.empty()) { DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); - return DEVICEMANAGER_NULLPTR; + return DM_POINT_NULL; } DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 515cf57f2..7a5cb96f7 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -43,11 +43,10 @@ config("device_manager_test_common_public_config") { "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/notify", "//third_party/json/include", "${common_path}/include", - "${common_path}/include/constants", "${common_path}/include/ipc", "${common_path}/include/ipc/model", - "${common_path}/include/utils", - + "${utils_path}/include", + "${utils_path}/include/ipc/standard", ] cflags = [ @@ -67,7 +66,7 @@ ohos_static_library("device_manager_test_common") { public_configs = [ ":device_manager_test_common_public_config" ] public_deps = [ - "${common_path}:devicemanagercommon", + "${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", diff --git a/test/unittest/device_manager_impl_test.cpp b/test/unittest/device_manager_impl_test.cpp index 24dd07e8e..b8c0fd08c 100644 --- a/test/unittest/device_manager_impl_test.cpp +++ b/test/unittest/device_manager_impl_test.cpp @@ -67,10 +67,10 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice2, testing::ext::TestSize.Leve 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)); + .Times(1).WillOnce(testing::Return(DM_FAILED)); int32_t ret= DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, dmAppImageInfo, extra, callback); - ASSERT_EQ(ret, DEVICEMANAGER_IPC_FAILED); + ASSERT_EQ(ret, DM_IPC_FAILED); DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; } @@ -108,9 +108,9 @@ HWTEST_F(DeviceManagerImplTest, CheckAuthentication2, testing::ext::TestSize.Lev 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)); + .Times(1).WillOnce(testing::Return(DM_FAILED)); int32_t ret= DeviceManager::GetInstance().CheckAuthentication(packName, authPara, callback); - ASSERT_EQ(ret, DEVICEMANAGER_IPC_FAILED); + ASSERT_EQ(ret, DM_IPC_FAILED); DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; } @@ -159,9 +159,9 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Le 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)); + .Times(1).WillOnce(testing::Return(DM_FAILED)); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, test_callback_); - ASSERT_EQ(ret, DEVICEMANAGER_IPC_FAILED); + ASSERT_EQ(ret, DM_IPC_FAILED); DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; } } // namespace diff --git a/utils/BUILD.gn b/utils/BUILD.gn index adec2c8af..86987ca90 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,11 +61,11 @@ 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", +# "//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", +# "//foundation/distributedschedule/samgr_lite/samgr:samgr", +# "//third_party/bounds_checking_function:libsec_shared", "//third_party/mbedtls:mbedtls_shared", "//utils/native/lite:utils", ] @@ -75,25 +73,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 = [ "//utils/native/base:utils" ] @@ -105,15 +101,15 @@ if (defined(ohos_lite)) { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", - "dsoftbus_standard:softbus_client", +# "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", +# "safwk:system_ability_fwk", +# "samgr_standard:samgr_proxy", +# "startup_l2:syspara", ] subsystem_name = "distributedhardware" 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/common/include/utils/dm_anonymous.h b/utils/include/dm_anonymous.h similarity index 100% rename from common/include/utils/dm_anonymous.h rename to utils/include/dm_anonymous.h diff --git a/common/include/utils/dm_log.h b/utils/include/dm_log.h similarity index 60% rename from common/include/utils/dm_log.h rename to utils/include/dm_log.h index 80822e790..1d32f22a4 100644 --- a/common/include/utils/dm_log.h +++ b/utils/include/dm_log.h @@ -16,8 +16,6 @@ #ifndef OHOS_DM_LOG_H #define OHOS_DM_LOG_H -#include - namespace OHOS { namespace DistributedHardware { @@ -31,8 +29,19 @@ typedef enum { void DMLog(DMLogLevel logLevel, const char *fmt, ...); #define DMLOG(level, fmt, ...) DMLog(level, \ - (std::string("[") + "DH_LOG_TAG" + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) + +#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/common/include/utils/dm_random.h b/utils/include/dm_random.h similarity index 100% rename from common/include/utils/dm_random.h rename to utils/include/dm_random.h diff --git a/utils/include/ipc/lite/ipc_cmd_register.h b/utils/include/ipc/lite/ipc_cmd_register.h index 36c20961f..615e07b91 100644 --- a/utils/include/ipc/lite/ipc_cmd_register.h +++ b/utils/include/ipc/lite/ipc_cmd_register.h @@ -13,11 +13,12 @@ * 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" @@ -110,4 +111,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 dc852f57e..ce3123d25 100644 --- a/utils/include/ipc/standard/ipc_cmd_register.h +++ b/utils/include/ipc/standard/ipc_cmd_register.h @@ -13,11 +13,12 @@ * 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 "iremote_broker.h" #include "single_instance.h" @@ -90,4 +91,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/common/src/utils/dm_anonymous.cpp b/utils/src/dm_anonymous.cpp similarity index 100% rename from common/src/utils/dm_anonymous.cpp rename to utils/src/dm_anonymous.cpp diff --git a/common/src/utils/dm_log.cpp b/utils/src/dm_log.cpp similarity index 100% rename from common/src/utils/dm_log.cpp rename to utils/src/dm_log.cpp diff --git a/common/src/utils/dm_random.cpp b/utils/src/dm_random.cpp similarity index 100% rename from common/src/utils/dm_random.cpp rename to utils/src/dm_random.cpp diff --git a/utils/src/ipc/lite/ipc_cmd_register.cpp b/utils/src/ipc/lite/ipc_cmd_register.cpp index 4fbab5a16..bc930d23d 100644 --- a/utils/src/ipc/lite/ipc_cmd_register.cpp +++ b/utils/src/ipc/lite/ipc_cmd_register.cpp @@ -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 { @@ -28,7 +28,7 @@ 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; + return DM_IPC_NOT_REGISTER_FUNC; } return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); } @@ -38,7 +38,7 @@ 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; + return DM_IPC_NOT_REGISTER_FUNC; } return (readResponseMapIter->second)(reply, pBaseRsp); } @@ -48,10 +48,10 @@ 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; + 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) @@ -59,10 +59,10 @@ 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; + 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..96a175d85 100644 --- a/utils/src/ipc/standard/ipc_cmd_register.cpp +++ b/utils/src/ipc/standard/ipc_cmd_register.cpp @@ -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 { @@ -27,7 +27,7 @@ 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; + return DM_IPC_NOT_REGISTER_FUNC; } return (setRequestMapIter->second)(pBaseReq, data); } @@ -37,7 +37,7 @@ 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; + return DM_IPC_NOT_REGISTER_FUNC; } return (readResponseMapIter->second)(reply, pBaseRsp); } @@ -47,7 +47,7 @@ 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; + 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 b62f903b080d695552e2827214b7a9f5ef0ddc08 Mon Sep 17 00:00:00 2001 From: skypuhui Date: Mon, 29 Nov 2021 00:39:12 +0800 Subject: [PATCH 018/110] =?UTF-8?q?=E6=9E=B6=E6=9E=84=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: skypuhui --- common/include/dm_constants.h | 2 +- .../native_cpp/include/dm_device_info.h | 2 +- services/devicemanagerservice/BUILD.gn | 4 +- .../dependency/softbus/softbus_connector.h | 2 +- .../dependency/softbus/softbus_session.h | 7 +- .../dependency/hichain/hichain_connector.cpp | 57 ++--- .../dependency/softbus/softbus_connector.cpp | 211 ++++++++++-------- .../dependency/softbus/softbus_session.cpp | 154 ++++++------- .../src/ipc/lite/ipc_cmd_parser.cpp | 11 +- .../src/ipc/lite/ipc_server_listener.cpp | 3 +- .../src/ipc/lite/ipc_server_main.cpp | 2 +- 11 files changed, 241 insertions(+), 214 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 1cfb2ec04..4ef70b600 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -56,7 +56,7 @@ namespace DistributedHardware { DM_IPC_NOT_REGISTER_FUNC, DM_IPC_RESPOND_ERROR, DM_SOFTBUS_FAILED = 3000, - + DM_SOFTBUS_CREATE_SESSION_SERVER_FAILED, DM_HICHAIN_FAILED = 4000, DM_HICHAIN_GROUP_CREATE_FAILED, DM_HICHAIN_MEMBER_ADD_FAILED, 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 961d5eca7..b27d11c01 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -46,7 +46,7 @@ typedef enum DmDeviceState { typedef struct DmDeviceInfo { char deviceId[DM_MAX_DEVICE_ID_LEN]; char deviceName[DM_MAX_DEVICE_NAME_LEN]; - int32_t deviceTypeId; + uint16_t deviceTypeId; } DmDeviceInfo; typedef struct DmAuthParam { diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index c769f7cc9..8df17c274 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -136,9 +136,9 @@ if (defined(ohos_lite)) { "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", -# "src/dependency/hichain/hichain_connector.cpp", + "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", -# "src/dependency/softbus/softbus_session.cpp", + "src/dependency/softbus/softbus_session.cpp", "src/ipc/standard/ipc_cmd_parser.cpp", "src/ipc/standard/ipc_server_listener.cpp", "src/ipc/standard/ipc_server_client_proxy.cpp", diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index d377211e4..9b74e5a25 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -38,7 +38,7 @@ public: 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 OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason); static void OnSoftbusDiscoverySuccess(int32_t subscribeId); public: SoftbusConnector(); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 43548b21b..0ecba444f 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -20,6 +20,9 @@ #include #include +#include "session.h" +#include "inner_session.h" + #include "softbus_session_callback.h" namespace OHOS { @@ -27,8 +30,8 @@ namespace DistributedHardware { class SoftbusSession { public: static int32_t OnSessionOpened(int32_t sessionId, int32_t result); - static int32_t OnSessionClosed(int32_t sessionId); - static int32_t OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + static void OnSessionClosed(int32_t sessionId); + static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); public: SoftbusSession(); ~SoftbusSession(); diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 208543408..3b5694c2b 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -23,10 +23,12 @@ #include "nlohmann/json.hpp" #include "parameter.h" +#include "hichain_connector_callback.h" #include "dm_anonymous.h" #include "dm_log.h" #include "dm_constants.h" -#include "hichain_connector_callback.h" +#include "dm_random.h" + namespace OHOS { namespace DistributedHardware { @@ -187,32 +189,32 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vector 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(), DM_PKG_NAME.c_str(), - tmpStr.c_str()); -} +//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(), DM_PKG_NAME.c_str(), +// tmpStr.c_str()); +//} void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) { @@ -281,6 +283,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, cons // std::string jsonStr = jsonObj.dump(); // char *buffer = strdup(jsonStr.c_str()); // return buffer; + return nullptr; } // void HiChainConnector::RegisterConnectorCallback(std::shared_ptr callback) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 3d190cb4c..db8606b1f 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -20,9 +20,12 @@ #include #include +#include "system_ability_definition.h" + #include "dm_log.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -35,7 +38,7 @@ SoftbusConnector::SoftbusConnector() }; softbusDiscoveryCallback_ = { .OnDeviceFound = SoftbusConnector::OnSoftbusDeviceFound, - .OnDiscoveryFailed = SoftbusConnector::OnSoftbusDiscoverFailed, + .OnDiscoverFailed = SoftbusConnector::OnSoftbusDiscoveryFailed, .OnDiscoverySuccess = SoftbusConnector::OnSoftbusDiscoverySuccess }; softbusNodeStateCb_ = { @@ -79,47 +82,67 @@ int32_t SoftbusConnector::Init() return ret; } +int32_t SoftbusConnector::RegisterSoftbusDiscoveryCallback(const std::string &pkgName, const ISoftbusDiscoveryCallback &callback) +{ + return DM_OK; +} + +int32_t SoftbusConnector::UnRegisterSoftbusDiscoveryCallback(const std::string &pkgName) +{ + return DM_OK; +} + +int32_t SoftbusConnector::RegisterSoftbusStateCallback(const std::string &pkgName, const ISoftbusStateCallback &callback) +{ + return DM_OK; +} + +int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgName) +{ + return DM_OK; +} + int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceInfoList) { DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices start"); - NodeBasicInfo *nodeInfo = nullptr; - int32_t *infoNum = 0; - int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeInfo, infoNum); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "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; - if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, - std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_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))) != DM_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; - deviceInfoList.push_back(*deviceInfo); - } - FreeNodeInfo(nodeInfo); - free(info); - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); +// NodeBasicInfo **nodeInfo = nullptr; +// int32_t *infoNum = 0; +// int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeInfo, infoNum); +// if (ret != 0) { +// DMLOG(DM_LOG_ERROR, "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; +// if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, +// std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_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))) != DM_OK) { +// DMLOG(DM_LOG_ERROR, "memcpy failed"); +// } +// deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; +// deviceInfoList.push_back(*deviceInfo); +// } +// FreeNodeInfo(nodeInfo); +// free(info); +// DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); return DM_OK; } int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) { DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo start"); - NodeBasicInfo *nodeInfo = nullptr; - int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeInfo); + NodeBasicInfo *nodeBasicInfo = nullptr; + int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeBasicInfo); if (ret != 0) { DMLOG(DM_LOG_ERROR, "GetLocalNodeDeviceInfo failed with ret %d", ret); return DM_FAILED; @@ -140,16 +163,16 @@ int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &subscribeInfo) { - 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; +// 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; //TODO:check these later // std::shared_ptr subinfo = nullptr; @@ -183,11 +206,11 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &subscribeInfo) // DMLOG(DM_LOG_DEBUG, "StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", // pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); // DMLOG(DM_LOG_DEBUG, "Capability: %s", subinfo->info.capability); - int32_t ret = StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); - if (ret != 0) { - DMLOG(DM_LOG_ERROR, "StartDiscovery failed with ret %d.", ret); - return DM_DISCOVERY_FAILED; - } +// int32_t ret = StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); +// if (ret != 0) { +// DMLOG(DM_LOG_ERROR, "StartDiscovery failed with ret %d.", ret); +// return DM_DISCOVERY_FAILED; +// } return DM_OK; } @@ -200,7 +223,7 @@ int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) // } DMLOG(DM_LOG_INFO, "StopDiscovery begin, subscribeId:%d", (int32_t)subscribeId); - int32_t ret = StopDiscovery(DM_PKG_NAME.c_str(), subscribeId); + int32_t ret = ::StopDiscovery(DM_PKG_NAME.c_str(), subscribeId); if (ret != 0) { DMLOG(DM_LOG_ERROR, "StopDiscovery failed with ret %d", ret); return ret; @@ -224,7 +247,7 @@ int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) return DM_OK; } -bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) +bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) { NodeBasicInfo *info = nullptr; int32_t infoNum = 0; @@ -303,44 +326,44 @@ bool SoftbusConnector::IsDeviceOnLine(std::string &deviceId) // return nullptr; //} -ConnectionAddr *SoftbusConnector::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; -} +//ConnectionAddr *SoftbusConnector::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 SoftbusConnector::NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo) { @@ -408,8 +431,8 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) DMLOG(DM_LOG_ERROR, "SoftbusConnector::OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); return; } - DmDeviceInfo dmDeviceInfo; - NodeBasicInfoCopyToDmDevice(dmDeviceInfo, *info); +// DmDeviceInfo dmDeviceInfo; +// NodeBasicInfoCopyToDmDevice(dmDeviceInfo, *info); // IpcServerListenerAdapter::GetInstance().OnDeviceStateChange(DmDeviceState::DEVICE_STATE_OFFLINE, dmDeviceInfo); } @@ -427,9 +450,9 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) } std::string deviceId = device->devId; DMLOG(DM_LOG_INFO, "SoftbusConnector::OnSoftbusDeviceFound device %s found.", GetAnonyString(deviceId).c_str()); - if (IsDeviceOnLine(deviceId)) { - return; - } +// if (IsDeviceOnLine(deviceId)) { +// return; +// } // SaveDiscoverDeviceInfo(device); // for (auto iter = subscribeInfos_.begin(); iter != subscribeInfos_.end(); ++iter) { // auto subInfovector = iter->second; @@ -448,7 +471,7 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) // } } -void SoftbusConnector::OnSoftbusDiscoverFailed(int32_t subscribeId, DiscoveryFailReason failReason) +void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason) { DMLOG(DM_LOG_INFO, "In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason); // std::string pkgName; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 0b5ec5240..65ff0c55c 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -15,6 +15,8 @@ #include "softbus_session.h" #include "dm_constants.h" +#include "dm_log.h" +#include "dm_anonymous.h" namespace OHOS { @@ -29,30 +31,29 @@ SoftbusSession::SoftbusSession() : sessionIdSet_(), messages_() .OnMessageReceived = nullptr, .OnStreamReceived = nullptr }; - int32_t ret = CreateSessionServer(DM_PKG_NAME, DM_SESSION_NAME, &sessionListener); + int32_t ret = CreateSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str(), &sessionListener); if (ret != DM_OK) { DMLOG(DM_LOG_DEBUG, "CreateSessionServer failed"); - return DM_CREATE_SESSION_SERVER_FAILED; } } SoftbusSession::~SoftbusSession() { - (void)RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME); + RemoveSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str()); } int32_t SoftbusSession::OpenAuthSession(const char *deviceId) { 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); +// messages_ = message; +// ConnectionAddr *addrInfo = SoftbusAdapter::GetConnectAddr(deviceId); +// if (addrInfo == nullptr) { +// DMLOG(DM_LOG_ERROR, "GetConnectAddr error"); +// return sessionId; +// } + + sessionId = ::OpenAuthSession(DM_SESSION_NAME.c_str(), nullptr, 1, nullptr); if (sessionId < 0) { DMLOG(DM_LOG_ERROR, "open session error, ret:%d", sessionId); return sessionId; @@ -65,7 +66,7 @@ int32_t SoftbusSession::OpenAuthSession(const char *deviceId) void SoftbusSession::CloseAuthSession(int32_t sessionId) { DMLOG(DM_LOG_INFO, "CloseSession in"); - ::CloseSession(sessionId); + CloseSession(sessionId); } void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) @@ -86,22 +87,22 @@ void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) int32_t SoftbusSession::SendData(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 DM_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 != DM_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; +// 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 DM_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 != DM_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 DM_OK; } // int32_t SoftbusSession::SendData(int32_t sessionId, const void *data, int32_t len) @@ -121,66 +122,65 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) { - if (result != DM_OK) { - DMLOG(DM_LOG_INFO, "session open failed, sessionId %d", sessionId); - if (sessionIdSet_.count(sessionId) > 0) { - sessionIdSet_.erase(sessionId); - messages_.clear(); - } - return DM_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 != DM_OK) { - DMLOG(DM_LOG_INFO, "send message failed"); - return ret; - } - } - } else { - sessionIdSet_.insert(sessionId); - } +// if (result != DM_OK) { +// DMLOG(DM_LOG_INFO, "session open failed, sessionId %d", sessionId); +// if (sessionIdSet_.count(sessionId) > 0) { +// sessionIdSet_.erase(sessionId); +// messages_.clear(); +// } +// return DM_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 != DM_OK) { +// DMLOG(DM_LOG_INFO, "send message failed"); +// return ret; +// } +// } +// } else { +// sessionIdSet_.insert(sessionId); +// } return DM_OK; } void SoftbusSession::OnSessionClosed(int32_t sessionId) { DMLOG(DM_LOG_INFO, "OnSessionClosed, sessionId:%d", sessionId); - if (sessionIdSet_.count(sessionId) > 0) { - sessionIdSet_.erase(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 != DM_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; +// 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 != DM_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"); } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index be23c72d9..2d2d431bf 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -105,7 +105,7 @@ ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo & IpcIoInit(&request, buffer, buffLen, 0); IpcIoPushString(&request, pkgName.c_str()); IpcIoPushString(&request, deviceId.c_str()); - IpcIoPushString(&request, token); + IpcIoPushString(&request, token.c_str()); IpcIoPushInt32(&request, status); IpcIoPushInt32(&request, reason); return DM_OK; @@ -120,7 +120,7 @@ ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr p 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::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string deviceId = pReq->GetDeviceId(); int32_t result = pReq->GetResult(); @@ -159,7 +159,7 @@ ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) std::string extra = (const char *)IpcIoPopString(&req, nullptr); std::vector deviceList; - int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList, extra); + 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()); @@ -171,7 +171,7 @@ ON_IPC_SERVER_CMD(GET_LOCAL_DEVICE_INFO, IpcIo &req, IpcIo &reply) { DMLOG(DM_LOG_INFO, "enter GetLocalDeviceInfo."); DmDeviceInfo dmDeviceInfo; - int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(&dmDeviceInfo); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo); IpcIoPushFlatObj(&reply, &dmDeviceInfo, sizeof(DmDeviceInfo)); IpcIoPushInt32(&reply, ret); } @@ -203,8 +203,7 @@ ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) 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 authType = IpcIoPopInt32(&req); int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); IpcIoPushInt32(&reply, ret); } diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp index 6961b8944..072f95974 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -21,7 +21,6 @@ #include "ipc_cmd_register.h" #include "ipc_def.h" #include "ipc_server_listenermgr.h" -#include "ipc_server_adapter.h" namespace OHOS { namespace DistributedHardware { @@ -51,7 +50,7 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr std::string pkgName = req->GetPkgName(); SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { - DMLOG(DM_LOG_ERROR, "ondevice found callback get listener failed."); + DMLOG(DM_LOG_ERROR, "OnDeviceFound callback get listener failed."); return DM_FAILED; } diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp index 7edf7eea4..2dd6c9311 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp @@ -20,7 +20,7 @@ #include "dm_constants.h" #include "ipc_server_stub.h" -#include "ipc_server_adapter.h" +#include "device_manager_service.h" using namespace OHOS::DistributedHardware; -- Gitee From 8a464835e45784a181273c53cb69e57d535f5366 Mon Sep 17 00:00:00 2001 From: skypuhui Date: Mon, 29 Nov 2021 01:17:02 +0800 Subject: [PATCH 019/110] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=95=B4=E6=94=B9?= =?UTF-8?q?=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: skypuhui --- .../native_cpp/src/device_manager_impl.cpp | 100 +++++------ .../native_cpp/src/ipc/ipc_client_proxy.cpp | 2 +- .../src/ipc/lite/ipc_client_manager.cpp | 16 +- .../src/ipc/lite/ipc_client_server_proxy.cpp | 24 +-- .../src/ipc/lite/ipc_client_stub.cpp | 8 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 14 +- .../src/ipc/standard/ipc_client_manager.cpp | 34 ++-- .../ipc/standard/ipc_client_server_proxy.cpp | 4 +- .../src/ipc/standard/ipc_client_stub.cpp | 6 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 36 ++-- .../src/notify/device_manager_notify.cpp | 42 ++--- interfaces/kits/js/src/dm_native_event.cpp | 20 +-- .../kits/js/src/native_devicemanager_js.cpp | 158 +++++++++--------- .../src/adapter/dm_adapter_manager.cpp | 4 +- .../src/authentication/dm_auth_manager.cpp | 4 +- .../dependency/hichain/hichain_connector.cpp | 100 +++++------ .../dependency/softbus/softbus_connector.cpp | 114 ++++++------- .../dependency/softbus/softbus_session.cpp | 44 ++--- .../src/device_manager_service.cpp | 46 ++--- .../src/device_manager_service_listener.cpp | 12 +- .../src/deviceinfo/dm_device_info_manager.cpp | 10 +- .../devicestate/dm_device_state_manager.cpp | 4 +- .../src/discovery/dm_discovery_manager.cpp | 4 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 18 +- .../src/ipc/lite/ipc_server_listener.cpp | 12 +- .../src/ipc/lite/ipc_server_listenermgr.cpp | 8 +- .../src/ipc/lite/ipc_server_main.cpp | 6 +- .../src/ipc/lite/ipc_server_stub.cpp | 31 ++-- .../src/ipc/standard/ipc_cmd_parser.cpp | 76 ++++----- .../ipc/standard/ipc_server_client_proxy.cpp | 4 +- .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 38 ++--- utils/include/dm_log.h | 3 - utils/src/ipc/lite/ipc_cmd_register.cpp | 8 +- utils/src/ipc/standard/ipc_cmd_register.cpp | 6 +- 35 files changed, 507 insertions(+), 511 deletions(-) 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 e7c7808fc..92d77eea1 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -40,48 +40,48 @@ DeviceManagerImpl & DeviceManagerImpl::GetInstance() int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) { - DMLOG(DM_LOG_INFO, "DeviceManager::InitDeviceManager start, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::InitDeviceManager start, pkgName: %s", pkgName.c_str()); if (pkgName.empty() || dmInitCallback == nullptr) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager error: Invalid parameter"); + LOGE("InitDeviceManager error: Invalid parameter"); return DM_INVALID_VALUE; } int32_t ret = ipcClientProxy_->Init(pkgName); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager error: proxy init failed ret: %d", ret); + LOGE("InitDeviceManager error: proxy init failed ret: %d", ret); return DM_INIT_FAILED; } DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); - DMLOG(DM_LOG_INFO, "InitDeviceManager success"); + LOGI("InitDeviceManager success"); return DM_OK; } 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 (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "UnInitDeviceManager error: Invalid parameter"); + LOGE("UnInitDeviceManager error: Invalid parameter"); return DM_INVALID_VALUE; } int32_t ret = ipcClientProxy_->UnInit(pkgName); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "UnInitDeviceManager error: proxy unInit failed ret: %d", ret); + LOGE("UnInitDeviceManager error: proxy unInit failed ret: %d", ret); return DM_UNINIT_FAILED; } DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); - DMLOG(DM_LOG_INFO, "UnInitDeviceManager success"); + LOGI("UnInitDeviceManager success"); return DM_OK; } 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 (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList error: Invalid para"); + LOGE("GetTrustedDeviceList error: Invalid para"); return DM_INVALID_VALUE; } @@ -91,80 +91,80 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons req->SetExtra(extra); int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList error: Send Request failed ret: %d", ret); + LOGE("GetTrustedDeviceList error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_INFO, "GetTrustedDeviceList error: failed ret: %d",ret); + LOGI("GetTrustedDeviceList error: failed ret: %d",ret); return DM_IPC_RESPOND_ERROR; } deviceList = rsp->GetDeviceVec(); - DMLOG(DM_LOG_INFO, "GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); + LOGI("GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &info) { - DMLOG(DM_LOG_INFO, "DeviceManager::GetLocalDeviceInfo start"); + LOGI("DeviceManager::GetLocalDeviceInfo start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); int32_t ret = ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "GetLocalDeviceInfo error: Send Request failed ret: %d", ret); + LOGE("GetLocalDeviceInfo error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_INFO, "GetLocalDeviceInfo error: failed ret: %d",ret); + LOGI("GetLocalDeviceInfo error: failed ret: %d",ret); return DM_IPC_RESPOND_ERROR; } info = rsp->GetLocalDeviceInfo(); - DMLOG(DM_LOG_INFO, "GetLocalDeviceInfo completed"); + LOGI("GetLocalDeviceInfo completed"); return DM_OK; } 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 (pkgName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "RegisterDevStateCallback error: Invalid para"); + LOGE("RegisterDevStateCallback error: Invalid para"); return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); - DMLOG(DM_LOG_INFO, "RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + LOGI("RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; } 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 (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "UnRegisterDevStateCallback error: Invalid para"); + LOGE("UnRegisterDevStateCallback error: Invalid para"); return DM_INVALID_VALUE; } DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); - DMLOG(DM_LOG_INFO, "UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + LOGI("UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra, std::shared_ptr callback) { - DMLOG(DM_LOG_INFO, "DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); if (pkgName.empty() || callback == nullptr) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery error: Invalid para"); + LOGE("StartDeviceDiscovery error: Invalid para"); return DM_INVALID_VALUE; } - DMLOG(DM_LOG_INFO, "DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); + LOGI("DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeInfo.subscribeId, callback); std::shared_ptr req = std::make_shared(); @@ -174,56 +174,56 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons req->SetSubscribeInfo(subscribeInfo); int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery error: Send Request failed ret: %d", ret); + LOGE("StartDeviceDiscovery error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery error: Failed with ret %d", ret); + LOGE("StartDeviceDiscovery error: Failed with ret %d", ret); return DM_IPC_RESPOND_ERROR; } - DMLOG(DM_LOG_INFO, "StartDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); + LOGI("StartDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); return DM_OK; } 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 (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery error: Invalid para"); + 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); int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery error: Send Request failed ret: %d", ret); + LOGE("StopDeviceDiscovery error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery error: Failed with ret %d", ret); + LOGE("StopDeviceDiscovery error: Failed with ret %d", ret); return DM_IPC_RESPOND_ERROR; } DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); - DMLOG(DM_LOG_INFO, "StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); + LOGI("StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, const DmDeviceInfo &deviceInfo, const std::string &extra, std::shared_ptr callback) { - DMLOG(DM_LOG_INFO, "DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice error: Invalid para"); + LOGE("AuthenticateDevice error: Invalid para"); return DM_INVALID_VALUE; } @@ -235,28 +235,28 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice error: Send Request failed ret: %d", ret); + LOGE("AuthenticateDevice error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice error: Failed with ret %d", ret); + 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()); + LOGI("DeviceManager::AuthenticateDevice completed, pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { - DMLOG(DM_LOG_INFO, "DeviceManager::UnAuthenticateDevice start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice error: Invalid para"); + LOGE("UnAuthenticateDevice error: Invalid para"); return DM_INVALID_VALUE; } @@ -266,28 +266,28 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(UNAUTHENTICATE_DEVICE, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice error: Send Request failed ret: %d", ret); + LOGE("UnAuthenticateDevice error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice error: Failed with ret %d", ret); + LOGE("UnAuthenticateDevice error: Failed with ret %d", ret); return DM_IPC_RESPOND_ERROR; } std::string strDeviceId = deviceInfo.deviceId; DeviceManagerNotify::GetInstance().UnRegisterAuthenticateCallback(pkgName, strDeviceId); - DMLOG(DM_LOG_INFO, "UnAuthenticateDevice completed, pkgName: %s", pkgName.c_str()); + LOGI("UnAuthenticateDevice 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) { - DMLOG(DM_LOG_INFO, "DeviceManager::VerifyAuthentication start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::VerifyAuthentication start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "VerifyAuthentication error: Invalid para"); + LOGE("VerifyAuthentication error: Invalid para"); return DM_INVALID_VALUE; } @@ -297,18 +297,18 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons req->SetAuthPara(authPara); int32_t ret = ipcClientProxy_->SendRequest(VERIFY_AUTHENTICATION, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "VerifyAuthentication error: Send Request failed ret: %d", ret); + LOGE("VerifyAuthentication error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "VerifyAuthentication error: Failed with ret %d", ret); + LOGE("VerifyAuthentication error: Failed with ret %d", ret); return ret; } DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); - DMLOG(DM_LOG_INFO, "DeviceManager::VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); return DM_OK; } } // namespace DistributedHardware 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 b261b2a6c..248812296 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 @@ -39,7 +39,7 @@ int32_t IpcClientProxy::UnInit(const 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"); + 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 e7a368a2e..93f693737 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 @@ -26,15 +26,15 @@ namespace DistributedHardware { int32_t IpcClientManager::Init(const std::string &pkgName) { if (IsInit(pkgName)) { - DMLOG(DM_LOG_INFO, "already init"); + LOGI("already init"); return DM_OK; } if (serverProxy_.Init() != DM_OK) { - DMLOG(DM_LOG_ERROR, "server proxy init failed."); + LOGE("server proxy init failed."); return DM_INIT_FAILED; } if (IpcClientStub::GetInstance().Init() != DM_OK) { - DMLOG(DM_LOG_ERROR, "ipcclientstub init failed."); + LOGE("ipcclientstub init failed."); return DM_INIT_FAILED; } @@ -44,12 +44,12 @@ int32_t IpcClientManager::Init(const std::string &pkgName) req->SetSvcIdentity(IpcClientStub::GetInstance().GetSvcIdentity()); int32_t ret = serverProxy_.SendCmd(REGISTER_DEVICE_MANAGER_LISTENER, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); + LOGE("InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); return ret; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "DeviceManager::InitDeviceManager completed, pkgName: %s, ret=%d", pkgName.c_str(), ret); + LOGE("DeviceManager::InitDeviceManager completed, pkgName: %s, ret=%d", pkgName.c_str(), ret); return ret; } packageInitSet_.emplace(pkgName); @@ -58,7 +58,7 @@ int32_t IpcClientManager::Init(const 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 DM_FAILED; } @@ -67,11 +67,11 @@ int32_t IpcClientManager::UnInit(const std::string &pkgName) req->SetPkgName(pkgName); int32_t ret = serverProxy_.SendCmd(UNREGISTER_DEVICE_MANAGER_LISTENER, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); + LOGE("UnRegisterDeviceManagerListener Failed with ret %d", ret); return ret; } packageInitSet_.erase(pkgName); - DMLOG(DM_LOG_INFO, "UnInitDeviceManager SUCCESS"); + LOGI("UnInitDeviceManager SUCCESS"); return DM_OK; } 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 20dd4464d..91d3ae92f 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 @@ -43,7 +43,7 @@ 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; @@ -57,7 +57,7 @@ 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 DM_OK; } @@ -67,14 +67,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) != DM_OK || clientProxy == nullptr) { - DMLOG(DM_LOG_ERROR, "QueryInterface failed"); + LOGE("QueryInterface failed"); } return clientProxy; } @@ -84,7 +84,7 @@ 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"); + LOGE("reg death callback failed"); return DM_FAILED; } return DM_OK; @@ -92,7 +92,7 @@ int IpcClientServerProxy::RegisterServerDeathCb(void) 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; @@ -104,31 +104,31 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r pCurRsp = rsp; if (serviceProxy_ != nullptr && serviceProxy_->Invoke(serviceProxy_, cmdCode, &request, &cmdCode, SendCmdResultCb) != 0) { - DMLOG(DM_LOG_ERROR, "serviceProxy_ invoke failed."); + LOGE("serviceProxy_ invoke failed."); return DM_FAILED; } } - DMLOG(DM_LOG_INFO, "SendCmd:%d end", cmdCode); + LOGI("SendCmd:%d end", cmdCode); return DM_OK; } int32_t IpcClientServerProxy::Init(void) { if (serviceProxy_ != nullptr) { - DMLOG(DM_LOG_INFO, "ServerProxy already Init"); + LOGI("ServerProxy already Init"); return DM_OK; } HOS_SystemInit(); serviceProxy_ = GetServerProxy(); if (serviceProxy_ == nullptr) { - DMLOG(DM_LOG_ERROR, "get ipc client proxy failed"); + LOGE("get ipc client proxy failed"); return DM_FAILED; } if (RegisterServerDeathCb() != DM_OK) { - DMLOG(DM_LOG_ERROR, "register server death cb failed"); + LOGE("register server death cb failed"); return DM_FAILED; } - DMLOG(DM_LOG_INFO, "ServerProxyInit ok"); + LOGI("ServerProxyInit ok"); return DM_OK; } } // namespace DistributedHardware 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 d26a14a26..e1b90089a 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 @@ -30,8 +30,8 @@ static int32_t ClientIpcInterfaceMsgHandle(const IpcContext *ctx, void *ipcMsg, { (void)arg; if (ipcMsg == nullptr || io == nullptr) { - DMLOG(DM_LOG_ERROR, "invalid param"); - return DM_INPUT_PARA_INVALID; + LOGE("invalid param"); + return DM_INPUT_PARA_EMPTY; } uint32_t code = 0; @@ -39,7 +39,7 @@ static int32_t ClientIpcInterfaceMsgHandle(const IpcContext *ctx, void *ipcMsg, 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; } @@ -51,7 +51,7 @@ int32_t IpcClientStub::Init() return DM_OK; } if (RegisterIpcCallback(ClientIpcInterfaceMsgHandle, 0, IPC_WAIT_FOREVER, &clientIdentity_, nullptr) != 0) { - DMLOG(DM_LOG_ERROR, "register ipc cb failed"); + LOGE("register ipc cb failed"); return DM_FAILED; } bInit = true; 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 406dad77a..95d5b9ba5 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 @@ -93,7 +93,7 @@ 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!"); + LOGE("GetTrustedDeviceList read node info failed!"); pRsp->SetErrCode(DM_IPC_TRANSACTION_FAILED); return DM_IPC_TRANSACTION_FAILED; } @@ -214,7 +214,7 @@ ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply) uint32_t 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) { @@ -228,7 +228,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; } } @@ -241,7 +241,7 @@ ON_IPC_CMD(SERVER_DEVICE_FOUND, IpcIo &reply) uint32_t 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); @@ -255,7 +255,7 @@ 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 == DM_OK) { @@ -276,7 +276,7 @@ ON_IPC_CMD(SERVER_AUTH_RESULT, IpcIo &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, nullptr, status, reason); @@ -292,7 +292,7 @@ ON_IPC_CMD(SERVER_VERIFY_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().OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); 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 017960639..6796a78b2 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 @@ -32,27 +32,27 @@ 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"); + LOGI("DeviceManagerService Already Init"); return DM_OK; } auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { - DMLOG(DM_LOG_ERROR, "Get SystemAbilityManager Failed"); + 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"); + LOGE("Get DeviceManager SystemAbility Failed"); return DM_SERVICE_NOT_READY; } @@ -60,10 +60,10 @@ int32_t IpcClientManager::ClientInit() 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"); + LOGI("DeviceManager::InitDeviceManagerService completed"); return DM_OK; } @@ -72,11 +72,11 @@ int32_t IpcClientManager::Init(const std::string &pkgName) std::lock_guard autoLock(lock_); int32_t ret = ClientInit(); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager Failed with ret %d", ret); + LOGE("InitDeviceManager Failed with ret %d", ret); return ret; } if (dmListener_.count(pkgName) > 0) { - DMLOG(DM_LOG_INFO, "dmListener_ Already Init"); + LOGI("dmListener_ Already Init"); return DM_OK; } @@ -87,7 +87,7 @@ int32_t IpcClientManager::Init(const std::string &pkgName) req->SetListener(listener); ret = dmInterface_->SendCmd(REGISTER_DEVICE_MANAGER_LISTENER, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); + LOGE("InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); return ret; } ret = rsp->GetErrCode(); @@ -95,15 +95,15 @@ int32_t IpcClientManager::Init(const std::string &pkgName) return ret; } dmListener_[pkgName] = listener; - DMLOG(DM_LOG_INFO, "completed, pkgName: %s", pkgName.c_str()); + LOGI("completed, pkgName: %s", pkgName.c_str()); return DM_OK; } 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"); + LOGE("DeviceManager not Init"); return DM_SERVICE_NOT_READY; } @@ -114,7 +114,7 @@ int32_t IpcClientManager::UnInit(const std::string &pkgName) req->SetPkgName(pkgName); int32_t ret = dmInterface_->SendCmd(UNREGISTER_DEVICE_MANAGER_LISTENER, req, rsp); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); + LOGE("UnRegisterDeviceManagerListener Failed with ret %d", ret); return ret; } dmListener_.erase(pkgName); @@ -123,7 +123,7 @@ int32_t IpcClientManager::UnInit(const std::string &pkgName) dmInterface_ = nullptr; dmRecipient_ = nullptr; } - DMLOG(DM_LOG_INFO, "completed, pkgName: %s", pkgName.c_str()); + LOGI("completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -139,12 +139,12 @@ int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr r bool IpcClientManager::IsInit(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 f19aac43e..23ffa8bd5 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 @@ -27,7 +27,7 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r { sptr remote = Remote(); if (remote == nullptr) { - DMLOG(DM_LOG_ERROR, "remote service null"); + LOGE("remote service null"); return DM_POINT_NULL; } @@ -38,7 +38,7 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r return DM_IPC_SEND_REQUEST_FAILED; } if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { - DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); + 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 ea2ad8f74..53bd6e82b 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 @@ -28,17 +28,17 @@ namespace DistributedHardware { int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - DMLOG(DM_LOG_INFO, "code = %d, flags= %d.", code, option.GetFlags()); + 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"); + LOGE("error"); return DM_OK; } } // namespace DistributedHardware diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index c060ca056..befc00671 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 @@ -38,11 +38,11 @@ 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"); + LOGE("write pkgName failed"); return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteRemoteObject(listener)) { - DMLOG(DM_LOG_ERROR, "write listener failed"); + LOGE("write listener failed"); return DM_IPC_TRANSACTION_FAILED; } return DM_OK; @@ -58,7 +58,7 @@ ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr p { std::string pkgName = pBaseReq->GetPkgName(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write papam failed"); + LOGE("write papam failed"); return DM_IPC_TRANSACTION_FAILED; } return DM_OK; @@ -76,11 +76,11 @@ ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, Mess std::string pkgName = pReq->GetPkgName(); std::string extra = pReq->GetExtra(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkg failed"); + LOGE("write pkg failed"); return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteString(extra)) { - DMLOG(DM_LOG_ERROR, "write extra failed"); + LOGE("write extra failed"); return DM_IPC_TRANSACTION_FAILED; } return DM_OK; @@ -95,7 +95,7 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, MessageParcel &reply, std::shared_pt std::vector deviceInfoVec; DmDeviceInfo *pDmDeviceinfo = (DmDeviceInfo *)reply.ReadRawData(deviceTotalSize); if (pDmDeviceinfo == nullptr) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList read node info failed!"); + LOGE("GetTrustedDeviceList read node info failed!"); pRsp->SetErrCode(DM_IPC_TRANSACTION_FAILED); return DM_IPC_TRANSACTION_FAILED; } @@ -115,11 +115,11 @@ 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"); + LOGE("write pkgName failed"); return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo))) { - DMLOG(DM_LOG_ERROR, "write subscribe info failed"); + LOGE("write subscribe info failed"); return DM_IPC_FLATTEN_OBJECT; } return DM_OK; @@ -137,11 +137,11 @@ 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"); + LOGE("write pkgName failed"); return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteInt16(subscribeId)) { - DMLOG(DM_LOG_ERROR, "write subscribeId failed"); + LOGE("write subscribeId failed"); return DM_IPC_FLATTEN_OBJECT; } return DM_OK; @@ -162,33 +162,33 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag // DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); + LOGE("write pkgName failed"); return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteString(extra)) { - DMLOG(DM_LOG_ERROR, "write extra failed"); + LOGE("write extra failed"); return DM_IPC_FLATTEN_OBJECT; } if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { - DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); + LOGE("write deviceInfo 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"); +// LOGE("write imageinfo appicon len failed"); // return DM_IPC_FLATTEN_OBJECT; // } // if (!data.WriteInt32(appThumbnailLen)) { -// DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnailLen failed"); +// LOGE("write imageinfo appThumbnailLen failed"); // return DM_IPC_FLATTEN_OBJECT; // } // if (appIconLen > 0 && !data.WriteRawData(imageInfo.GetAppIcon(), appIconLen)) { -// DMLOG(DM_LOG_ERROR, "write imageinfo appIcon failed"); +// LOGE("write imageinfo appIcon failed"); // return DM_IPC_FLATTEN_OBJECT; // } // if (appThumbnailLen > 0 && !data.WriteRawData(imageInfo.GetAppThumbnail(), appThumbnailLen)) { -// DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnail failed"); +// LOGE("write imageinfo appThumbnail failed"); // return DM_IPC_FLATTEN_OBJECT; // } return DM_OK; @@ -238,7 +238,7 @@ ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply DeviceManagerNotify::GetInstance().OnDeviceChanged(pkgName, dmDeviceInfo); break; default: - DMLOG(DM_LOG_ERROR, "unknown device state:%d", deviceState); + LOGE("unknown device state:%d", deviceState); break; } reply.WriteInt32(DM_OK); 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 aedcc1252..28e2f8db5 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 @@ -116,7 +116,7 @@ void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::stri void DeviceManagerNotify::OnRemoteDied() { - DMLOG(DM_LOG_WARN, "DeviceManager : OnRemoteDied"); + LOGW("DeviceManager : OnRemoteDied"); for (auto iter : dmInitCallback_) { iter.second->OnRemoteDied(); } @@ -124,10 +124,10 @@ void DeviceManagerNotify::OnRemoteDied() 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); @@ -135,10 +135,10 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev 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); @@ -146,10 +146,10 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe 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); @@ -158,17 +158,17 @@ void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDe 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(), + LOGI("DeviceManager OnDeviceFound pkgName:%s, subscribeId:%d.", pkgName.c_str(), (int32_t)subscribeId); std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceFound: no register DiscoveryCallback for this package"); + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for this package"); return; } std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceFound: no register DiscoveryCallback for subscribeId %d", + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } @@ -177,17 +177,17 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", + LOGI("DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", pkgName.c_str(), subscribeId, failedReason); std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for this package"); + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for this package"); return; } std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for subscribeId %d", + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } @@ -196,17 +196,17 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId) { - DMLOG(DM_LOG_INFO, "DeviceManager OnDiscoverySuccess pkgName:%s, subscribeId:%d.", pkgName.c_str(), + LOGI("DeviceManager OnDiscoverySuccess pkgName:%s, subscribeId:%d.", pkgName.c_str(), subscribeId); std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for this package"); + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for this package"); return; } std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for subscribeId %d", + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } @@ -216,17 +216,17 @@ void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_ 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", + 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, token, status, reason); @@ -239,11 +239,11 @@ void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::st 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", + LOGI("DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", pkgName.c_str(), resultCode, flag); std::lock_guard autoLock(lock_); if (verifyAuthCallback_.count(pkgName) == 0) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register authCallback for this package"); + LOGE("DeviceManager OnCheckAuthResult: no register authCallback for this package"); return; } verifyAuthCallback_[pkgName]->OnVerifyAuthResult(deviceId, resultCode, flag); diff --git a/interfaces/kits/js/src/dm_native_event.cpp b/interfaces/kits/js/src/dm_native_event.cpp index 3a8b7d16f..c0e627c89 100644 --- a/interfaces/kits/js/src/dm_native_event.cpp +++ b/interfaces/kits/js/src/dm_native_event.cpp @@ -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 622eac965..11ae6edaf 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -65,7 +65,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); @@ -75,7 +75,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); @@ -85,7 +85,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); @@ -95,7 +95,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); @@ -105,7 +105,7 @@ 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); @@ -115,11 +115,11 @@ void DmNapiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDevic { 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); } @@ -127,7 +127,7 @@ void DmNapiDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t fa { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - DMLOG(DM_LOG_ERROR, "OnDiscoveryFailed, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + LOGE("OnDiscoveryFailed, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } @@ -138,10 +138,10 @@ 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 DmNapiDiscoveryCallback::IncreaseRefCount() @@ -163,7 +163,7 @@ void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const { 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, token, status, reason); @@ -173,7 +173,7 @@ void DmNapiVerifyAuthCallback::OnVerifyAuthResult(const std::string &deviceId, i { 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); @@ -219,7 +219,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); @@ -236,7 +236,7 @@ void DeviceManagerNapi::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo & void DeviceManagerNapi::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) { - DMLOG(DM_LOG_INFO, "OnDiscoveryFailed 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); @@ -246,13 +246,13 @@ void DeviceManagerNapi::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedRe 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 }; 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]); @@ -261,7 +261,7 @@ void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, const std::str // SetValueInt32(env_, "pinTone", token, 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]); @@ -275,14 +275,14 @@ void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, const std::str 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 }; @@ -304,7 +304,7 @@ 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_verifyAuthCallbackMap.erase(bundleName_); } @@ -338,14 +338,14 @@ 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::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam, napi_value ¶mResult) { - DMLOG(DM_LOG_INFO, "DmAuthParamToJsAuthParam in"); + LOGI("DmAuthParamToJsAuthParam in"); SetValueInt32(env, "authType", authParam.authType, paramResult); napi_value extraInfo = nullptr; @@ -408,13 +408,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 ""; @@ -454,7 +454,7 @@ 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()); } } @@ -472,7 +472,7 @@ 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()); } } @@ -482,7 +482,7 @@ int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_v 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; } @@ -524,7 +524,7 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & //void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const napi_value &object, // DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) //{ -// DMLOG(DM_LOG_INFO, "JsToDmAppImageInfoAndDmExtra in."); +// LOGI("JsToDmAppImageInfoAndDmExtra in."); // int32_t authTypeTemp = -1; // JsObjectToInt(env, object, "authType", authTypeTemp); // authType = authTypeTemp; @@ -553,17 +553,17 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & // // 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) { - 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; } @@ -577,16 +577,16 @@ void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &obje 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); 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; @@ -597,11 +597,11 @@ void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &obje 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; } @@ -612,7 +612,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; @@ -624,29 +624,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; } } @@ -655,7 +655,7 @@ 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; @@ -676,7 +676,7 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &eventType) { - DMLOG(DM_LOG_ERROR, "CreateDmCallback for bundleName %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()) { @@ -684,7 +684,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; @@ -713,12 +713,12 @@ 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); @@ -743,7 +743,7 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & //napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_callback_info info) //{ -// DMLOG(DM_LOG_INFO, "GetAuthenticationParamSync in"); +// LOGI("GetAuthenticationParamSync in"); // size_t argc = 0; // napi_value thisVar = nullptr; // napi_value resultParam = nullptr; @@ -757,7 +757,7 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & // DmAuthParam authParam; // int32_t ret = DeviceManager::GetInstance().GetAuthenticationParam(deviceManagerWrapper->bundleName_, authParam); // if (ret != 0) { -// DMLOG(DM_LOG_ERROR, "GetAuthenticationParam for %s failed, ret %d", +// LOGE("GetAuthenticationParam for %s failed, ret %d", // deviceManagerWrapper->bundleName_.c_str(), ret); // napi_get_undefined(env, &resultParam); // return resultParam; @@ -770,7 +770,7 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "GetTrustedDeviceList in"); + LOGI("GetTrustedDeviceList in"); size_t argc = 0; napi_value thisVar = nullptr; napi_value array = nullptr; @@ -784,7 +784,7 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba 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", + LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); return array; } @@ -794,14 +794,14 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba napi_create_array(env, &array); napi_is_array(env, array, &isArray); if (isArray == false) { - DMLOG(DM_LOG_ERROR, "napi_create_array fail"); + LOGE("napi_create_array fail"); } for (size_t i = 0; i != devList.size(); ++i) { DeviceInfoToJsArray(env, devList, i, array); } } else { - DMLOG(DM_LOG_ERROR, "devList is null"); + LOGE("devList is null"); } return array; @@ -809,7 +809,7 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba 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; @@ -835,7 +835,7 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac // int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, // subInfo, DiscoveryCallback); // if (ret != 0) { -// DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery for bunderName %s failed, ret %d", +// LOGE("StartDeviceDiscovery for bunderName %s failed, ret %d", // deviceManagerWrapper->bundleName_.c_str(), ret); // return result; // } @@ -846,7 +846,7 @@ 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; @@ -862,7 +862,7 @@ napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback 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", + LOGE("StopDeviceDiscovery for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); return result; } @@ -875,7 +875,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; @@ -915,7 +915,7 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, extra, authCallback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice for bundleName %s failed, ret %d", + LOGE("AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } napi_get_undefined(env, &result); @@ -924,7 +924,7 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf 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; @@ -955,7 +955,7 @@ napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info in int32_t ret = DeviceManager::GetInstance().VerifyAuthentication(deviceManagerWrapper->bundleName_, authParam, verifyCallback); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "VerifyAuthInfo for bunderName %s failed, ret %d", + LOGE("VerifyAuthInfo for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } @@ -965,7 +965,7 @@ napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info in napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "JsOn in"); + 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"); @@ -989,7 +989,7 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - DMLOG(DM_LOG_INFO, "JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), + LOGI("JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); deviceManagerWrapper->On(eventType, argv[1]); CreateDmCallback(deviceManagerWrapper->bundleName_, eventType); @@ -1001,7 +1001,7 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) { - DMLOG(DM_LOG_INFO, "JsOff in"); + 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"); @@ -1028,7 +1028,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(), + LOGI("JsOff for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); deviceManagerWrapper->Off(eventType); ReleaseDmCallback(deviceManagerWrapper->bundleName_, eventType); @@ -1040,7 +1040,7 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) 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; @@ -1050,10 +1050,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", + LOGE("ReleaseDeviceManager for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); napi_create_uint32(env, ret, &result); return result; @@ -1081,7 +1081,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; @@ -1097,11 +1097,11 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac 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; @@ -1109,7 +1109,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); @@ -1124,7 +1124,7 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac 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"); @@ -1151,7 +1151,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"); @@ -1163,7 +1163,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) size_t typeLen = 0; napi_get_value_string_utf8(env, argv[0], bundleName, sizeof(bundleName), &typeLen); - 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; @@ -1198,14 +1198,14 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) DECLARE_NAPI_STATIC_FUNCTION("createDeviceManager", CreateDeviceManager), }; - DMLOG(DM_LOG_DEBUG, "DeviceManagerNapi::Init() is called!"); + 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; } @@ -1214,7 +1214,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; } @@ -1237,6 +1237,6 @@ static napi_module g_dmModule = { */ 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/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp index fc1cce5ae..881a3d181 100644 --- a/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp @@ -22,12 +22,12 @@ namespace DistributedHardware { DmAdapterManager::DmAdapterManager() { - DMLOG(DM_LOG_INFO, "DmAdapterManager constructor"); + LOGI("DmAdapterManager constructor"); } DmAdapterManager::~DmAdapterManager() { - DMLOG(DM_LOG_INFO, "DmAdapterManager destructor"); + LOGI("DmAdapterManager destructor"); } std::shared_ptr DmAdapterManager::GetDecisionAdapter() diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index ca337cee6..be569134c 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -23,12 +23,12 @@ namespace DistributedHardware { DmAuthManager::DmAuthManager(std::shared_ptr softbusConnectorPtr, std::shared_ptr listenerPtr) : softbusConnector_(softbusConnectorPtr), listenerPtr_(listenerPtr) { - DMLOG(DM_LOG_INFO, "DmAuthManager constructor"); + LOGI("DmAuthManager constructor"); } DmAuthManager::~DmAuthManager() { - DMLOG(DM_LOG_INFO, "DmAuthManager destructor"); + LOGI("DmAuthManager destructor"); } int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 3b5694c2b..d4900e5a9 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -73,7 +73,7 @@ void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) HiChainConnector::HiChainConnector() { - DMLOG(DM_LOG_INFO, "HiChainConnector::constructor"); + LOGI("HiChainConnector::constructor"); deviceAuthCallback_ = { .onTransmit = nullptr, .onFinish = HiChainConnector::onFinish, @@ -83,16 +83,16 @@ HiChainConnector::HiChainConnector() InitDeviceAuthService(); deviceGroupManager_ = GetGmInstance(); if (deviceGroupManager_ == nullptr) { - DMLOG(DM_LOG_INFO, "HiChainConnector::constructor, failed to init group manager!"); + LOGI("HiChainConnector::constructor, failed to init group manager!"); return; } deviceGroupManager_->regCallback(DM_PKG_NAME.c_str(), &deviceAuthCallback_); - DMLOG(DM_LOG_INFO, "HiChainConnector::constructor success."); + LOGI("HiChainConnector::constructor success."); } HiChainConnector::~HiChainConnector() { - DMLOG(DM_LOG_INFO, "HiChainConnector::destructor."); + LOGI("HiChainConnector::destructor."); //TODO:delete resource } @@ -106,7 +106,7 @@ void HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, const 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); + LOGE("HiChainConnector::CreateGroup group manager is null, requestId %lld.", requestId); return DM_INVALID_VALUE; } @@ -115,7 +115,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou DeleteGroup(groupInfo.groupId); } - DMLOG(DM_LOG_INFO, "HiChainConnector::CreateGroup requestId %lld", requestId); + LOGI("HiChainConnector::CreateGroup requestId %lld", requestId); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; @@ -129,7 +129,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou 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) { - DMLOG(DM_LOG_ERROR, "Faild to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); + LOGE("Faild to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); return DM_HICHAIN_GROUP_CREATE_FAILED; } return DM_OK; @@ -156,32 +156,32 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vectorgetGroupInfo(DM_PKG_NAME.c_str(), queryParams.c_str(), &groupVec, &num); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::GetGroupInfo faild , ret: %d.", ret); + LOGE("HiChainConnector::GetGroupInfo faild , ret: %d.", ret); return false; } if (groupVec == nullptr) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::GetGroupInfo faild , returnGroups is nullptr"); + LOGE("HiChainConnector::GetGroupInfo faild , returnGroups is nullptr"); return false; } if (num == 0) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::GetGroupInfo group failed, groupNum is 0."); + LOGE("HiChainConnector::GetGroupInfo group failed, groupNum is 0."); return false; } - DMLOG(DM_LOG_INFO, "HiChainConnector::GetGroupInfo group(%s), groupNum(%d)", groupVec, num); + 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()) { - DMLOG(DM_LOG_ERROR, "returnGroups parse error"); + LOGE("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."); + LOGE("HiChainConnector::GetGroupInfo group failed, groupInfos is empty."); return false; } @@ -191,9 +191,9 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vector msgResponseAuth) //{ -// DMLOG(DM_LOG_INFO, "HiChainConnector::AddMemeber"); +// LOGI("HiChainConnector::AddMemeber"); // if (deviceGroupManager_ == nullptr) { -// DMLOG(DM_LOG_INFO, "HiChainConnector::AddMemeber group manager is null."); +// LOGI("HiChainConnector::AddMemeber group manager is null."); // return -1; // } // @@ -211,7 +211,7 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vectoraddMemberToGroup(msgResponseAuth->GetRequestId(), DM_PKG_NAME.c_str(), // tmpStr.c_str()); //} @@ -222,20 +222,20 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const if (returnData != nullptr) { data = std::string(returnData); } - DMLOG(DM_LOG_INFO, "HiChainConnector::onFinish reqId:%lld, operation:%d", requestId, operationCode); + LOGI("HiChainConnector::onFinish reqId:%lld, operation:%d", requestId, operationCode); if (operationCode == GroupOperationCode::MEMBER_JOIN) { - DMLOG(DM_LOG_INFO, "Add Member To Group success"); + LOGI("Add Member To Group success"); // HichainConnector::GetInstance().OnMemberJoin(requestId, SUCCESS); } if (operationCode == GroupOperationCode::GROUP_CREATE) { - DMLOG(DM_LOG_INFO, "Create group success"); + LOGI("Create group success"); // HichainConnector::GetInstance().OnGroupCreated(requestId, data); } if (operationCode == GroupOperationCode::MEMBER_DELETE) { - DMLOG(DM_LOG_INFO, "Delete Member from group success"); + LOGI("Delete Member from group success"); } if (operationCode == GroupOperationCode::GROUP_DISBAND) { - DMLOG(DM_LOG_INFO, "Disband group success"); + LOGI("Disband group success"); } } @@ -243,29 +243,29 @@ void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t const char *errorReturn) { (void)errorReturn; - DMLOG(DM_LOG_INFO, "HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", + LOGI("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"); + LOGE("Add Member To Group failed"); // HichainConnector::GetInstance().OnMemberJoin(requestId, FAIL); } if (operationCode == GroupOperationCode::GROUP_CREATE) { - DMLOG(DM_LOG_ERROR, "Create group failed"); + LOGE("Create group failed"); // HichainConnector::GetInstance().OnGroupCreated(requestId, "{}"); } if (operationCode == GroupOperationCode::MEMBER_DELETE) { - DMLOG(DM_LOG_ERROR, "Delete Member from group failed"); + LOGE("Delete Member from group failed"); } if (operationCode == GroupOperationCode::GROUP_DISBAND) { - DMLOG(DM_LOG_ERROR, "Disband group failed"); + LOGE("Disband group failed"); } } char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams) { if (operationCode != GroupOperationCode::MEMBER_JOIN) { - DMLOG(DM_LOG_ERROR, "HiChainAuthCallBack::onRequest operationCode %d", operationCode); + LOGE("HiChainAuthCallBack::onRequest operationCode %d", operationCode); return nullptr; } // int32_t pinCode = AuthManager::GetInstance().GetPincode(requestId); @@ -294,32 +294,32 @@ char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, cons // void HiChainConnector::OnGroupCreated(int64_t requestId, const std::string &returnData) // { // if (HiChainConnectorCallback_ == nullptr) { -// DMLOG(DM_LOG_ERROR, "HiChainConnector::OnGroupCreated HiChainConnectorCallback_ not registe."); +// LOGE("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."); +// LOGE("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."); +// LOGE("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()); +// LOGI("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); +// LOGI("HiChainConnector::OnMemberJoin:: role = %d", (int32_t)role); // if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { // AuthManager::GetInstance().NotifyHostOnCheckAuthResult(requestId, status); @@ -327,7 +327,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, cons // } // if (HiChainConnectorCallback_ == nullptr) { -// DMLOG(DM_LOG_ERROR, "HiChainConnector::OnMemberJoin HiChainConnectorCallback_ not registe."); +// LOGE("HiChainConnector::OnMemberJoin HiChainConnectorCallback_ not registe."); // return; // } // HiChainConnectorCallback_->OnMemberJoin(requestId, status); @@ -343,29 +343,29 @@ int64_t HiChainConnector::GenRequestId() //{ // ConnectionAddr *addrInfo = SoftbusAdapter::GetConnectAddr(deviceId); // if (addrInfo == nullptr) { -// DMLOG(DM_LOG_ERROR, "HiChainConnector::GetConnectPara addrInfo error"); +// LOGE("HiChainConnector::GetConnectPara addrInfo error"); // return ""; // } // -// DMLOG(DM_LOG_ERROR, "HiChainConnector::GetConnectPara get addrInfo"); +// LOGE("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"); +// LOGI("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"); +// LOGI("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"); +// LOGI("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"); +// LOGI("HiChainConnector::AddMemeber addr type is ble"); // jsonPara[BLE_MAC] = addrInfo->info.ble.bleMac; // } else { -// DMLOG(DM_LOG_ERROR, "HiChainConnector::AddMemeber addrInfo not right"); +// LOGE("HiChainConnector::AddMemeber addrInfo not right"); // return ""; // } // return jsonPara.dump(); @@ -373,36 +373,36 @@ int64_t HiChainConnector::GenRequestId() void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList) { - DMLOG(DM_LOG_INFO, "HiChainConnector::GetRelatedGroups Start to get local related groups."); + 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) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups faild , ret: %d.", ret); + LOGE("HiChainConnector::GetRelatedGroups faild , ret: %d.", ret); return; } if (returnGroups == nullptr) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups faild , returnGroups is nullptr"); + LOGE("HiChainConnector::GetRelatedGroups faild , returnGroups is nullptr"); return; } if (groupNum == 0) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups group failed, groupNum is 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()) { - DMLOG(DM_LOG_ERROR, "returnGroups parse error"); + LOGE("returnGroups parse error"); return; } std::vector groupInfos = jsonObject.get>(); if (groupInfos.size() == 0) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::GetRelatedGroups group failed, groupInfos is empty."); + LOGE("HiChainConnector::GetRelatedGroups group failed, groupInfos is empty."); return; } groupList = groupInfos; @@ -411,7 +411,7 @@ void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList, std::vector &syncGroupList) { if (groupList.empty()) { - DMLOG(DM_LOG_ERROR, "groupList is empty."); + LOGE("groupList is empty."); return; } @@ -451,7 +451,7 @@ void HiChainConnector::SyncGroups(std::string deviceId, std::vector 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", + 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; @@ -461,7 +461,7 @@ int32_t HiChainConnector::DelMemberFromGroup(std::string groupId, std::string de int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DM_PKG_NAME.c_str(), deleteParams.c_str()); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::DelMemberFromGroup faild , ret: %d.", ret); + LOGE("HiChainConnector::DelMemberFromGroup faild , ret: %d.", ret); return ret; } return 0; @@ -475,7 +475,7 @@ void HiChainConnector::DeleteGroup(std::string &groupId) std::string disbandParams = jsonObj.dump(); int32_t ret = deviceGroupManager_->deleteGroup(requestId, DM_PKG_NAME.c_str(), disbandParams.c_str()); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "HiChainConnector::DeleteGroup failed , ret: %d.", ret); + LOGE("HiChainConnector::DeleteGroup failed , ret: %d.", ret); } } } diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index db8606b1f..85ec37dc6 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -31,7 +31,7 @@ namespace OHOS { namespace DistributedHardware { SoftbusConnector::SoftbusConnector() { - DMLOG(DM_LOG_INFO,"SoftbusConnector constructor"); + LOGI("SoftbusConnector constructor"); softbusPublishCallback_ = { .OnPublishSuccess = SoftbusConnector::OnPublishSuccess, .OnPublishFail = SoftbusConnector::OnPublishFail @@ -51,7 +51,7 @@ SoftbusConnector::SoftbusConnector() } SoftbusConnector::~SoftbusConnector() { - DMLOG(DM_LOG_INFO,"SoftbusConnector destructor"); + LOGI("SoftbusConnector destructor"); } int32_t SoftbusConnector::Init() @@ -63,11 +63,11 @@ int32_t SoftbusConnector::Init() ret = RegNodeDeviceStateCb(DM_PKG_NAME.c_str(), &softbusNodeStateCb_); if (ret != DM_OK) { ++retryTimes; - DMLOG(DM_LOG_ERROR, "RegNodeDeviceStateCb failed with ret %d, retryTimes %d", ret, retryTimes); + LOGE("RegNodeDeviceStateCb failed with ret %d, retryTimes %d", ret, retryTimes); usleep(SOFTBUS_CHECK_INTERVAL); } } while (ret != DM_OK); - DMLOG(DM_LOG_INFO, "RegNodeDeviceStateCb success."); + LOGI("RegNodeDeviceStateCb success."); //TODO:check system properties first PublishInfo publishInfo; publishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; @@ -78,7 +78,7 @@ int32_t SoftbusConnector::Init() publishInfo.capabilityData = nullptr; publishInfo.dataLen = 0; ret = PublishService(DM_PKG_NAME.c_str(), &publishInfo, &softbusPublishCallback_); - DMLOG(DM_LOG_INFO, "service publish result is : %d", ret); + LOGI("service publish result is : %d", ret); return ret; } @@ -104,12 +104,12 @@ int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgN int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceInfoList) { - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices start"); + LOGD("SoftbusConnector::GetTrustDevices start"); // NodeBasicInfo **nodeInfo = nullptr; // int32_t *infoNum = 0; // int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeInfo, infoNum); // if (ret != 0) { -// DMLOG(DM_LOG_ERROR, "GetAllNodeDeviceInfo failed with ret %d", ret); +// LOGE("GetAllNodeDeviceInfo failed with ret %d", ret); // return DM_FAILED; // } // DmDeviceInfo *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (*infoNum)); @@ -123,41 +123,41 @@ int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceI // DmDeviceInfo *deviceInfo = *pInfoList + i; // if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, // std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { -// DMLOG(DM_LOG_ERROR, "memcpy failed"); +// LOGE("memcpy failed"); // } // if (memcpy_s(deviceInfo->deviceName, sizeof(deviceInfo->deviceName), nodeBasicInfo->deviceName, // std::min(sizeof(deviceInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { -// DMLOG(DM_LOG_ERROR, "memcpy failed"); +// LOGE("memcpy failed"); // } // deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; // deviceInfoList.push_back(*deviceInfo); // } // FreeNodeInfo(nodeInfo); // free(info); -// DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); +// LOGD("SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); return DM_OK; } int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) { - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo start"); + LOGD("SoftbusConnector::GetLocalDeviceInfo start"); NodeBasicInfo *nodeBasicInfo = nullptr; int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeBasicInfo); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "GetLocalNodeDeviceInfo failed with ret %d", ret); + LOGE("GetLocalNodeDeviceInfo failed with ret %d", ret); return DM_FAILED; } DmDeviceInfo *pInfo = &deviceInfo; if (memcpy_s(pInfo->deviceId, sizeof(pInfo->deviceId), nodeBasicInfo->networkId, std::min(sizeof(pInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); + LOGE("memcpy failed"); } if (memcpy_s(pInfo->deviceName, sizeof(pInfo->deviceName), nodeBasicInfo->deviceName, std::min(sizeof(pInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); + LOGE("memcpy failed"); } pInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; - DMLOG(DM_LOG_DEBUG, "SoftbusConnector::GetLocalDeviceInfo success"); + LOGD("SoftbusConnector::GetLocalDeviceInfo success"); return DM_OK; } @@ -203,12 +203,12 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &subscribeInfo) // if (vectorIter == subinfoVector.end()) { // subinfoVector.push_back(subinfo); // } - // DMLOG(DM_LOG_DEBUG, "StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", + // LOGD("StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", // pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); - // DMLOG(DM_LOG_DEBUG, "Capability: %s", subinfo->info.capability); + // LOGD("Capability: %s", subinfo->info.capability); // int32_t ret = StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); // if (ret != 0) { -// DMLOG(DM_LOG_ERROR, "StartDiscovery failed with ret %d.", ret); +// LOGE("StartDiscovery failed with ret %d.", ret); // return DM_DISCOVERY_FAILED; // } return DM_OK; @@ -218,14 +218,14 @@ int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) { // int32_t subscribeIdAdapter = -1; // if (!GetsubscribeIdAdapter(pkgName, subscribeId, subscribeIdAdapter)) { - // DMLOG(DM_LOG_ERROR, "StopDiscovery failed, subscribeId not match"); + // LOGE("StopDiscovery failed, subscribeId not match"); // return DEVICEMANAGER_FAILED; // } - DMLOG(DM_LOG_INFO, "StopDiscovery begin, subscribeId:%d", (int32_t)subscribeId); + LOGI("StopDiscovery begin, subscribeId:%d", (int32_t)subscribeId); int32_t ret = ::StopDiscovery(DM_PKG_NAME.c_str(), subscribeId); if (ret != 0) { - DMLOG(DM_LOG_ERROR, "StopDiscovery failed with ret %d", ret); + LOGE("StopDiscovery failed with ret %d", ret); return ret; } @@ -243,7 +243,7 @@ int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) // if (subinfoVector.empty()) { // subscribeInfos_.erase(pkgName); // } - DMLOG(DM_LOG_INFO, "SoftbusConnector::StopDiscovery completed"); + LOGI("SoftbusConnector::StopDiscovery completed"); return DM_OK; } @@ -252,19 +252,19 @@ 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) { - DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine DM_GetSoftbusTrustDevices failed"); + LOGE("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); + LOGE("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()); + LOGI("DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str()); bDeviceOnline = true; break; } @@ -272,11 +272,11 @@ bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) int32_t ret = GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId.c_str(), NodeDeivceInfoKey::NODE_KEY_UDID, udid, sizeof(udid)); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine GetNodeKeyInfo failed"); + LOGE("DM_IsDeviceOnLine GetNodeKeyInfo failed"); break; } if (strcmp((char *)udid, deviceId.c_str()) == 0) { - DMLOG(DM_LOG_INFO, "DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str()); + LOGI("DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str()); bDeviceOnline = true; break; } @@ -289,13 +289,13 @@ bool SoftbusConnector::IsDeviceOnLine(const 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()); +// LOGE("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); +// LOGE("deviceInfo addrNum not valid, addrNum %d", deviceInfo->addrNum); // return DEVICEMANAGER_FAILED; // } // @@ -306,10 +306,10 @@ bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) // continue; // } // ipAddr = deviceInfo->addr[i].info.ip.ip; -// DMLOG(DM_LOG_INFO, "DM_GetConnectionIpAddr get ip ok."); +// LOGI("DM_GetConnectionIpAddr get ip ok."); // return DM_OK; // } -// DMLOG(DM_LOG_ERROR, "failed to get ipAddr for deviceId %s", GetAnonyString(deviceId).c_str()); +// LOGE("failed to get ipAddr for deviceId %s", GetAnonyString(deviceId).c_str()); // return DM_FAILED; //} @@ -330,38 +330,38 @@ bool SoftbusConnector::IsDeviceOnLine(const 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()); +// 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) { -// DMLOG(DM_LOG_ERROR, "deviceInfo addrNum not valid, addrNum %d", deviceInfo->addrNum); +// LOGE("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()); +// LOGI("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()); +// LOGI("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()); +// LOGI("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()); +// LOGI("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()); +// LOGE("failed to get ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); // return nullptr; //} @@ -370,11 +370,11 @@ void SoftbusConnector::NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, N (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) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); + LOGE("memcpy failed"); } if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DM_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); + LOGE("memcpy failed"); } dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId; } @@ -384,29 +384,29 @@ void SoftbusConnector::DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, cons (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) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); + LOGE("memcpy failed"); } if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); + LOGE("memcpy failed"); } dmDeviceInfo.deviceTypeId = deviceInfo.devType; } void SoftbusConnector::OnPublishSuccess(int32_t publishId) { - DMLOG(DM_LOG_INFO, "SoftbusConnector::OnPublishSuccess, publishId: %d", publishId); + LOGI("SoftbusConnector::OnPublishSuccess, publishId: %d", publishId); } void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason) { - DMLOG(DM_LOG_INFO, "SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason); + LOGI("SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason); } void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) { if (info == nullptr) { - DMLOG(DM_LOG_ERROR, "SoftbusConnector::OnSoftBusDeviceOnline NodeBasicInfo is nullptr"); + LOGE("SoftbusConnector::OnSoftBusDeviceOnline NodeBasicInfo is nullptr"); return; } // DmDeviceInfo dmDeviceInfo; @@ -417,18 +417,18 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) // int32_t ret = GetNodeKeyInfo(DEVICE_MANAGER_PACKAGE_NAME.c_str(), info->networkId, // NodeDeivceInfoKey::NODE_KEY_UDID, udid, sizeof(udid)); // if (ret != DM_OK) { - // DMLOG(DM_LOG_ERROR, "GetNodeKeyInfo failed"); + // LOGE("GetNodeKeyInfo failed"); // return; // } // std::string deviceId = (char *)udid; - // DMLOG(DM_LOG_INFO, "device online, deviceId: %s", GetAnonyString(deviceId).c_str()); + // LOGI("device online, deviceId: %s", GetAnonyString(deviceId).c_str()); // RemoveDiscoveryDeviceInfo(deviceId); } void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) { if (info == nullptr) { - DMLOG(DM_LOG_ERROR, "SoftbusConnector::OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); + LOGE("SoftbusConnector::OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); return; } // DmDeviceInfo dmDeviceInfo; @@ -438,18 +438,18 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) { - DMLOG(DM_LOG_INFO, "SoftbusConnector::OnSoftbusDeviceInfoChanged."); + LOGI("SoftbusConnector::OnSoftbusDeviceInfoChanged."); //TODO: } void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) { if (device == nullptr) { - DMLOG(DM_LOG_ERROR, "device is null"); + LOGE("device is null"); return; } std::string deviceId = device->devId; - DMLOG(DM_LOG_INFO, "SoftbusConnector::OnSoftbusDeviceFound device %s found.", GetAnonyString(deviceId).c_str()); + LOGI("SoftbusConnector::OnSoftbusDeviceFound device %s found.", GetAnonyString(deviceId).c_str()); // if (IsDeviceOnLine(deviceId)) { // return; // } @@ -458,9 +458,9 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) // 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); +// LOGI("subscribe info capability:%s.", info->info.capability); // if (strcmp(DM_CAPABILITY_OSD, info->info.capability) != 0) { -// DMLOG(DM_LOG_ERROR, "subscribe info capability invalid."); +// LOGE("subscribe info capability invalid."); // } // uint16_t originId = (uint16_t)(((uint32_t)info->info.subscribeId) & SUBSCRIBE_ID_MASK); // std::string strPkgName = iter->first; @@ -473,10 +473,10 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason) { - DMLOG(DM_LOG_INFO, "In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason); + LOGI("In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason); // std::string pkgName; // if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { -// DMLOG(DM_LOG_ERROR, "SoftbusConnector::OnSoftbusDiscoverFailed: pkgName not found"); +// LOGE("SoftbusConnector::OnSoftbusDiscoverFailed: pkgName not found"); // return; // } // @@ -486,10 +486,10 @@ void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFa void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) { - DMLOG(DM_LOG_INFO, "In, subscribeId %d", subscribeId); + LOGI("In, subscribeId %d", subscribeId); // std::string pkgName; // if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { -// DMLOG(DM_LOG_ERROR, "OnSoftbusDiscoverySuccess: pkgName not found"); +// LOGE("OnSoftbusDiscoverySuccess: pkgName not found"); // return; // } // uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 65ff0c55c..22dfafa1d 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -33,7 +33,7 @@ SoftbusSession::SoftbusSession() : sessionIdSet_(), messages_() }; int32_t ret = CreateSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str(), &sessionListener); if (ret != DM_OK) { - DMLOG(DM_LOG_DEBUG, "CreateSessionServer failed"); + LOGD("CreateSessionServer failed"); } } @@ -44,28 +44,28 @@ SoftbusSession::~SoftbusSession() int32_t SoftbusSession::OpenAuthSession(const char *deviceId) { - DMLOG(DM_LOG_ERROR, "open channel and start SendMsg"); + LOGE("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"); +// LOGE("GetConnectAddr error"); // return sessionId; // } sessionId = ::OpenAuthSession(DM_SESSION_NAME.c_str(), nullptr, 1, nullptr); if (sessionId < 0) { - DMLOG(DM_LOG_ERROR, "open session error, ret:%d", sessionId); + LOGE("open session error, ret:%d", sessionId); return sessionId; } sessionIdSet_.insert(sessionId); - DMLOG(DM_LOG_INFO, "opened auth session is:%d", sessionId); + LOGI("opened auth session is:%d", sessionId); return sessionId; } void SoftbusSession::CloseAuthSession(int32_t sessionId) { - DMLOG(DM_LOG_INFO, "CloseSession in"); + LOGI("CloseSession in"); CloseSession(sessionId); } @@ -75,28 +75,28 @@ void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) 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, + LOGI("GetPeerDeviceId success for session:%d, peerDeviceId:%s", sessionId, GetAnonyString(peerDevId).c_str()); return; } - DMLOG(DM_LOG_ERROR, "GetPeerDeviceId failed for session:%d", sessionId); + LOGE("GetPeerDeviceId failed for session:%d", sessionId); peerDevId = ""; } int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) { - DMLOG(DM_LOG_ERROR, "start SendMsg"); + LOGE("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"); +// LOGE("SendMsg: malloc memory failed"); // return DM_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 != DM_OK || outLen > MSG_MAX_SIZE) { -// DMLOG(DM_LOG_ERROR, "MbedtlsEncrypt data failed"); +// LOGE("MbedtlsEncrypt data failed"); // free(buf); // return ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; // } @@ -107,7 +107,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) // int32_t SoftbusSession::SendData(int32_t sessionId, const void *data, int32_t len) // { -// DMLOG(DM_LOG_INFO, "in, datalen:%d", len); +// LOGI("in, datalen:%d", len); // int32_t ret = DEVICEMANAGER_FAILED; // if (sessionIdSet_.count(sessionId) > 0) { // ret = SendBytes(sessionId, data, len); @@ -115,7 +115,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) // return DEVICEMANAGER_FAILED; // } // } else { -// DMLOG(DM_LOG_INFO, "in, datalen:%d", len); +// LOGI("in, datalen:%d", len); // } // return ret; // } @@ -123,7 +123,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) { // if (result != DM_OK) { -// DMLOG(DM_LOG_INFO, "session open failed, sessionId %d", sessionId); +// LOGI("session open failed, sessionId %d", sessionId); // if (sessionIdSet_.count(sessionId) > 0) { // sessionIdSet_.erase(sessionId); // messages_.clear(); @@ -132,12 +132,12 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) // } // // int32_t sessionSide = GetSessionSide(sessionId); -// DMLOG(DM_LOG_INFO, "session open succeed, sessionId %d, sessionSide %d", sessionId, sessionSide); +// LOGI("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 != DM_OK) { -// DMLOG(DM_LOG_INFO, "send message failed"); +// LOGI("send message failed"); // return ret; // } // } @@ -149,7 +149,7 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) void SoftbusSession::OnSessionClosed(int32_t sessionId) { - DMLOG(DM_LOG_INFO, "OnSessionClosed, sessionId:%d", sessionId); + LOGI("OnSessionClosed, sessionId:%d", sessionId); // if (sessionIdSet_.count(sessionId) > 0) { // sessionIdSet_.erase(sessionId); // } @@ -157,22 +157,22 @@ void SoftbusSession::OnSessionClosed(int32_t sessionId) void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) { - DMLOG(DM_LOG_INFO, "OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen); + LOGI("OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen); // if (sessionId < 0 || data == nullptr || dataLen <= 0) { -// DMLOG(DM_LOG_INFO, "OnBytesReceived param check failed"); +// LOGI("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"); +// LOGE("SendMsg: malloc memory failed"); // return; // } // // int32_t outLen = 0; // int32_t ret = EncryptUtils::MbedtlsDecrypt((const uint8_t*)data, dataLen, buf, dataLen, &outLen); // if (ret != DM_OK || outLen > (int32_t)dataLen) { -// DMLOG(DM_LOG_ERROR, "MbedtlsDecrypt data failed"); +// LOGE("MbedtlsDecrypt data failed"); // free(buf); // return; // } @@ -180,7 +180,7 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 // std::string message = (char *)buf; // AuthManager::GetInstance().OnReceiveMsg(sessionId, message); // free(buf); -// DMLOG(DM_LOG_INFO, "OnBytesReceived completed"); +// LOGI("OnBytesReceived completed"); } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index dc293a680..a4025b7ac 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -27,14 +27,14 @@ IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); int32_t DeviceManagerService::Init() { if (intFlag_) { - DMLOG(DM_LOG_ERROR, "Init failed, singleton cannot be initialized multiple times"); + LOGE("Init failed, singleton cannot be initialized multiple times"); return DM_INT_MULTIPLE; } if (softbusConnectorPtr_ == nullptr) { softbusConnectorPtr_ = std::make_shared(); if (softbusConnectorPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "Init failed, softbusConnectorPtr_ apply for failure"); + LOGE("Init failed, softbusConnectorPtr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } @@ -42,7 +42,7 @@ int32_t DeviceManagerService::Init() if (listenerPtr_ == nullptr) { listenerPtr_ = std::make_shared(); if (softbusConnectorPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "Init failed, listenerPtr_ apply for failure"); + LOGE("Init failed, listenerPtr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } @@ -50,7 +50,7 @@ int32_t DeviceManagerService::Init() if (deviceInfoMgrPtr_ == nullptr) { deviceInfoMgrPtr_ = std::make_shared(softbusConnectorPtr_); if (deviceInfoMgrPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "Init failed, deviceInfoMgrPtr_ apply for failure"); + LOGE("Init failed, deviceInfoMgrPtr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } @@ -58,7 +58,7 @@ int32_t DeviceManagerService::Init() if (deviceStateMgrPtr_ == nullptr) { deviceStateMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); if (deviceStateMgrPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "Init failed, deviceStateMgrPtr_ apply for failure"); + LOGE("Init failed, deviceStateMgrPtr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } @@ -66,7 +66,7 @@ int32_t DeviceManagerService::Init() if (discoveryMgrPtr_ == nullptr) { discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); if (discoveryMgrPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "Init failed, discoveryMgrPtr_ apply for failure"); + LOGE("Init failed, discoveryMgrPtr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } @@ -74,12 +74,12 @@ int32_t DeviceManagerService::Init() if(authMgrPtr_ == nullptr) { authMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); if (authMgrPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "Init failed, authMgrPtr_ apply for failure"); + LOGE("Init failed, authMgrPtr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } - DMLOG(DM_LOG_INFO, "Init success, singleton initialized"); + LOGI("Init success, singleton initialized"); intFlag_ = true; return DM_OK; } @@ -87,12 +87,12 @@ int32_t DeviceManagerService::Init() int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { if (!intFlag_) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, singleton not init or init fail"); + LOGE("GetTrustedDeviceList failed, singleton not init or init fail"); return DM_NOT_INIT; } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed, pkgName is empty"); + LOGE("GetTrustedDeviceList failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } return deviceInfoMgrPtr_->GetTrustedDeviceList(pkgName, extra, deviceList); @@ -101,7 +101,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { if (!intFlag_) { - DMLOG(DM_LOG_ERROR, "GetLocalDeviceInfo failed, singleton not init or init fail"); + LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); return DM_NOT_INIT; } @@ -111,12 +111,12 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { if (!intFlag_) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, singleton not init or init fail"); + LOGE("StartDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery failed, pkgName is empty"); + LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } return discoveryMgrPtr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); @@ -125,12 +125,12 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { if (!intFlag_) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, singleton not init or init fail"); + LOGE("StopDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery failed, pkgName is empty"); + LOGE("StopDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } return discoveryMgrPtr_->StopDeviceDiscovery(pkgName, subscribeId); @@ -139,17 +139,17 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { if (!intFlag_) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, singleton not init or init fail"); + LOGE("AuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, pkgName is empty"); + LOGE("AuthenticateDevice failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } if (deviceId.empty()) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice failed, deviceId is empty"); + LOGE("AuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } return authMgrPtr_->AuthenticateDevice(pkgName, authType, deviceId, extra); @@ -158,16 +158,16 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { if (!intFlag_) { - DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, singleton not init or init fail"); + LOGE("UnAuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, pkgName is empty"); + LOGE("UnAuthenticateDevice failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } if (deviceId.empty()) { - DMLOG(DM_LOG_ERROR, "UnAuthenticateDevice failed, deviceId is empty"); + LOGE("UnAuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } return authMgrPtr_->UnAuthenticateDevice(pkgName, deviceId); @@ -176,12 +176,12 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) { if (!intFlag_) { - DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, singleton not init or init fail"); + LOGE("VerifyAuthentication failed, singleton not init or init fail"); return DM_NOT_INIT; } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "VerifyAuthentication failed, pkgName is empty"); + LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 7ac01c381..d1b3938e2 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -32,7 +32,7 @@ namespace DistributedHardware { void DeviceManagerServiceListener::OnDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info) { - DMLOG(DM_LOG_INFO, "OnDeviceStateChange"); + LOGI("OnDeviceStateChange"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); @@ -43,7 +43,7 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const DmDeviceState &stat void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) { - DMLOG(DM_LOG_INFO, "call OnDeviceFound for %s, originId %d, deviceId %s", + 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(); @@ -56,7 +56,7 @@ void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uin void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, const std::string &failedReason) { - DMLOG(DM_LOG_INFO, "OnDiscoveryFailed"); + LOGI("OnDiscoveryFailed"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); @@ -68,7 +68,7 @@ void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) { - DMLOG(DM_LOG_INFO, "OnDiscoverySuccess"); + LOGI("OnDiscoverySuccess"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); @@ -80,7 +80,7 @@ void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, const std::string &reason) { - DMLOG(DM_LOG_INFO, "%s, package: %s, deviceId: %s", __FUNCTION__, pkgName.c_str(), + 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(); @@ -95,7 +95,7 @@ void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, cons void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode, const std::string &flag) { -// DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", +// LOGI("OnCheckResult, authParam: %s, errorCode: %d", // GetAnonyString(authParam).c_str(), resultCode); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 1350d7d48..c4801010f 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -22,21 +22,21 @@ namespace OHOS { namespace DistributedHardware { DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr& softbusConnectorPtr) : softbusConnectorPtr_(softbusConnectorPtr) { - DMLOG(DM_LOG_INFO,"DmDeviceInfoManager constructor"); + LOGI("DmDeviceInfoManager constructor"); } int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { int32_t ret = softbusConnectorPtr_->GetTrustedDeviceList(deviceList); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList failed"); + LOGE("GetTrustedDeviceList failed"); return ret; } if (!extra.empty() && !deviceList.empty()) { adapterMgrPtr_ = std::make_shared(); if (adapterMgrPtr_ == nullptr) { - DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList adapterMgrPtr_ is nullptr"); + LOGE("GetTrustedDeviceList adapterMgrPtr_ is nullptr"); return DM_POINT_NULL; } @@ -44,7 +44,7 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co // if (decisionAdapter != nullptr) { // decisionAdapter->FilterDeviceList(deviceList, extra); // } else { -// DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList decisionAdapter is nullptr"); +// LOGE("GetTrustedDeviceList decisionAdapter is nullptr"); // return DM_POINT_NULL; // } } @@ -56,7 +56,7 @@ int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info) { int32_t ret = softbusConnectorPtr_->GetLocalDeviceInfo(info); if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "GetLocalDeviceInfo failed"); + LOGE("GetLocalDeviceInfo failed"); return ret; } return DM_OK; diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index caa43ecfc..80a6b11d7 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -23,12 +23,12 @@ namespace DistributedHardware { DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, std::shared_ptr listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) { - DMLOG(DM_LOG_INFO, "DmDeviceStateManager constructor"); + LOGI("DmDeviceStateManager constructor"); } DmDeviceStateManager::~DmDeviceStateManager() { - DMLOG(DM_LOG_INFO,"DmDeviceStateManager destructor"); + LOGI("DmDeviceStateManager destructor"); } } diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 26539ea0e..946bb4d49 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -23,12 +23,12 @@ namespace DistributedHardware { DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, std::shared_ptr listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) { - DMLOG(DM_LOG_INFO, "DmDiscoveryManager constructor"); + LOGI("DmDiscoveryManager constructor"); } DmDiscoveryManager::~DmDiscoveryManager() { - DMLOG(DM_LOG_INFO, "DmDiscoveryManager destructor"); + LOGI("DmDiscoveryManager destructor"); } int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 2d2d431bf..cbf4ebf0d 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -154,7 +154,7 @@ ON_IPC_SERVER_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) { - DMLOG(DM_LOG_INFO, "enter GetTrustedDeviceList."); + LOGI("enter GetTrustedDeviceList."); std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); std::string extra = (const char *)IpcIoPopString(&req, nullptr); @@ -169,7 +169,7 @@ ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) ON_IPC_SERVER_CMD(GET_LOCAL_DEVICE_INFO, IpcIo &req, IpcIo &reply) { - DMLOG(DM_LOG_INFO, "enter GetLocalDeviceInfo."); + LOGI("enter GetLocalDeviceInfo."); DmDeviceInfo dmDeviceInfo; int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo); IpcIoPushFlatObj(&reply, &dmDeviceInfo, sizeof(DmDeviceInfo)); @@ -178,7 +178,7 @@ ON_IPC_SERVER_CMD(GET_LOCAL_DEVICE_INFO, IpcIo &req, IpcIo &reply) ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) { - DMLOG(DM_LOG_INFO, "StartDeviceDiscovery service listener."); + LOGI("StartDeviceDiscovery service listener."); std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); std::string extra = (const char *)IpcIoPopString(&req, nullptr); @@ -190,7 +190,7 @@ ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) { - DMLOG(DM_LOG_INFO, "StopDeviceDiscovery service listener."); + 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); @@ -199,7 +199,7 @@ ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) { - DMLOG(DM_LOG_INFO, "AuthenticateDevice service listener."); + 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); @@ -210,7 +210,7 @@ ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) ON_IPC_SERVER_CMD(UNAUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) { - DMLOG(DM_LOG_INFO, "UnAuthenticateDevice service listener."); + LOGI("UnAuthenticateDevice service listener."); std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); std::string deviceId = (const char *)IpcIoPopString(&req, nullptr); @@ -220,7 +220,7 @@ ON_IPC_SERVER_CMD(UNAUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATION, IpcIo &req, IpcIo &reply) { - DMLOG(DM_LOG_INFO, "VerifyAuthentication service listener."); + LOGI("VerifyAuthentication service listener."); std::string pkgName = (const char *)IpcIoPopString(&req, nullptr); std::string authParam = (const char *)IpcIoPopString(&req, nullptr); @@ -233,13 +233,13 @@ ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATION, 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()); +// LOGE("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); // DeviceManagerService::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"); +// LOGD("DeviceManagerStub::is Client so just return direction"); // return; // } // diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp index 072f95974..26745fc2c 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -38,7 +38,7 @@ int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity * { CommonSvcId svcId; if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DM_OK) { - DMLOG(DM_LOG_ERROR, "get identity failed."); + LOGE("get identity failed."); return DM_FAILED; } CommonSvcToIdentity(&svcId, svc); @@ -50,18 +50,18 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr std::string pkgName = req->GetPkgName(); SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { - DMLOG(DM_LOG_ERROR, "OnDeviceFound callback get listener failed."); + 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) { - DMLOG(DM_LOG_DEBUG, "SetRequest failed cmdCode:%d", cmdCode); + LOGD("SetRequest failed cmdCode:%d", cmdCode); return DM_FAILED; } if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { - DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); + LOGD("SendRequest failed cmdCode:%d", cmdCode); } return DM_OK; } @@ -77,13 +77,13 @@ int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, req->SetPkgName(pkgName); if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) { - DMLOG(DM_LOG_DEBUG, "SetRequest failed cmdCode:%d", cmdCode); + 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) { - DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); + LOGD("SendRequest failed cmdCode:%d", cmdCode); } } return DM_OK; diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp index f172e47e6..e9fbed7b3 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp @@ -25,10 +25,10 @@ IMPLEMENT_SINGLE_INSTANCE(IpcServerListenermgr); int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const CommonSvcId *svcId) { if (pkgName == "" || svcId == nullptr) { - DMLOG(DM_LOG_ERROR, "invalid param"); + LOGE("invalid param"); return DM_FAILED; } - DMLOG(DM_LOG_INFO, "new listener register:%s", pkgName.c_str()); + LOGI("new listener register:%s", pkgName.c_str()); std::lock_guard autoLock(lock_); dmListenerMap_[pkgName] = *svcId; return DM_OK; @@ -37,13 +37,13 @@ int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const Commo int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId) { if (pkgName == "" || svcId == nullptr) { - DMLOG(DM_LOG_ERROR, "invalid param"); + LOGE("invalid param"); return DM_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()); + LOGE("listener not found for pkg:%s", pkgName.c_str()); return DM_FAILED; } *svcId = iter->second; diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp index 2dd6c9311..7bb471cf0 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp @@ -30,14 +30,14 @@ static void InitAll() sleep(DM_SERVICE_INIT_DELAY); if (IpcServerStubInit() != DM_OK) { - DMLOG(DM_LOG_ERROR, "IpcServerStubInit failed"); + LOGE("IpcServerStubInit failed"); return; } if (DeviceManagerService::GetInstance().Init() != DM_OK) { - DMLOG(DM_LOG_ERROR, "module init failed"); + LOGE("module init failed"); return; } - DMLOG(DM_LOG_INFO, "DM ipc server Init success"); + LOGI("DM ipc server Init success"); } int32_t main(int32_t argc, char *argv[]) diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp index ffd711bc7..bb7030e20 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -29,7 +29,6 @@ #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; @@ -55,13 +54,13 @@ static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, voi (void)ipcMsg; (void)data; if (arg == NULL) { - DMLOG(DM_LOG_ERROR, "package name is 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) { - DMLOG(DM_LOG_ERROR, "not found client by package name."); + LOGE("not found client by package name."); free(arg); arg = NULL; return DM_FAILED; @@ -82,12 +81,12 @@ static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, voi int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) { - DMLOG(DM_LOG_INFO, "register service listener."); + 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) { - DMLOG(DM_LOG_ERROR, "get para failed"); + LOGE("get para failed"); return DM_INVALID_VALUE; } @@ -105,11 +104,11 @@ int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) #endif char *pkgName = (char *)malloc(len + 1); if (pkgName == NULL) { - DMLOG(DM_LOG_ERROR, "malloc failed!"); + LOGE("malloc failed!"); return DM_MALLOC_ERROR; } if (strcpy_s(pkgName, len + 1, (const char *)name) != DM_OK) { - DMLOG(DM_LOG_ERROR, "strcpy_s failed!"); + LOGE("strcpy_s failed!"); free(pkgName); return DM_COPY_FAILED; } @@ -122,16 +121,16 @@ int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) { - DMLOG(DM_LOG_INFO, "unregister service listener."); + LOGI("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"); + LOGE("get para failed"); return DM_FAILED; } CommonSvcId svcId; if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_OK) { - DMLOG(DM_LOG_ERROR, "not found listener by package name."); + LOGE("not found listener by package name."); return DM_FAILED; } int32_t ret = IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); @@ -157,7 +156,7 @@ static const char *GetName(Service *service) static BOOL Initialize(Service *service, Identity identity) { if (service == NULL) { - DMLOG(DM_LOG_WARN, "invalid param"); + LOGW("invalid param"); return FALSE; } @@ -169,7 +168,7 @@ static BOOL Initialize(Service *service, Identity identity) static BOOL MessageHandle(Service *service, Request *request) { if ((service == NULL) || (request == NULL)) { - DMLOG(DM_LOG_WARN, "invalid param"); + LOGW("invalid param"); return FALSE; } return TRUE; @@ -185,7 +184,7 @@ static TaskConfig GetTaskConfig(Service *service) static int32_t OnRemoteRequest(IServerProxy *iProxy, int32_t funcId, void *origin, IpcIo *req, IpcIo *reply) { - DMLOG(DM_LOG_INFO, "Receive funcId:%d", funcId); + LOGI("Receive funcId:%d", funcId); (void)origin; return IpcCmdRegister::GetInstance().OnIpcServerCmd(funcId, *req, *reply); } @@ -216,13 +215,13 @@ static void DevMgrSvcInit(void) }; if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) { - DMLOG(DM_LOG_ERROR, "%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME); + LOGE("%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); + LOGE("%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME); return; } - DMLOG(DM_LOG_INFO, "%s, init success", DEVICE_MANAGER_SERVICE_NAME); + 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 index 3cf7c0991..4a4c602c1 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -38,15 +38,15 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, int32_t deviceState = pReq->GetDeviceState(); DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); + LOGE("write pkgName failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(deviceState)) { - DMLOG(DM_LOG_ERROR, "write state failed"); + LOGE("write state failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { - DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); + LOGE("write deviceInfo failed"); return DM_FLATTEN_OBJECT; } return DM_OK; @@ -65,15 +65,15 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, Messag uint16_t subscribeId = pReq->GetSubscribeId(); DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); + LOGE("write pkgName failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt16(subscribeId)) { - DMLOG(DM_LOG_ERROR, "write subscribeId failed"); + LOGE("write subscribeId failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { - DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); + LOGE("write deviceInfo failed"); return DM_FLATTEN_OBJECT; } return DM_OK; @@ -92,15 +92,15 @@ ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, Mes uint16_t subscribeId = pReq->GetSubscribeId(); int32_t result = pReq->GetResult(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); + LOGE("write pkgName failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt16(subscribeId)) { - DMLOG(DM_LOG_ERROR, "write subscribeId failed"); + LOGE("write subscribeId failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); + LOGE("write result failed"); return DM_FLATTEN_OBJECT; } return DM_OK; @@ -121,23 +121,23 @@ ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, Message int32_t status = pReq->GetStatus(); int32_t reason = pReq->GetReason(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); + LOGE("write pkgName failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteString(deviceId)) { - DMLOG(DM_LOG_ERROR, "write deviceId failed"); + LOGE("write deviceId failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteString(token)) { - DMLOG(DM_LOG_ERROR, "write token failed"); + LOGE("write token failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(status)) { - DMLOG(DM_LOG_ERROR, "write status failed"); + LOGE("write status failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(reason)) { - DMLOG(DM_LOG_ERROR, "write reason failed"); + LOGE("write reason failed"); return DM_FLATTEN_OBJECT; } return DM_OK; @@ -157,19 +157,19 @@ ON_IPC_SET_REQUEST(SERVER_VERIFY_AUTH_RESULT, std::shared_ptr pBaseReq, int32_t result = pReq->GetResult(); int32_t flag = pReq->GetFlag(); if (!data.WriteString(pkgName)) { - DMLOG(DM_LOG_ERROR, "write pkgName failed"); + LOGE("write pkgName failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteString(deviceId)) { - DMLOG(DM_LOG_ERROR, "write deviceId failed"); + LOGE("write deviceId failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); + LOGE("write result failed"); return DM_FLATTEN_OBJECT; } if (!data.WriteInt32(flag)) { - DMLOG(DM_LOG_ERROR, "write flag failed"); + LOGE("write flag failed"); return DM_FLATTEN_OBJECT; } return DM_OK; @@ -185,7 +185,7 @@ 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()); + LOGI("pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str()); //TODO: // DmDeviceInfo *info = nullptr; // int32_t infoNum = 0; @@ -193,12 +193,12 @@ ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) // reply.WriteInt32(infoNum); // if (infoNum > 0 && info != nullptr) { // if (!reply.WriteRawData(info, sizeof(DmDeviceInfo) * infoNum)) { -// DMLOG(DM_LOG_ERROR, "write subscribeInfo failed"); +// LOGE("write subscribeInfo failed"); // } // free(info); // } // if (!reply.WriteInt32(result)) { -// DMLOG(DM_LOG_ERROR, "write result failed"); +// LOGE("write result failed"); // return DM_WRITE_FAILED; // } return DM_OK; @@ -210,7 +210,7 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel sptr listener = data.ReadRemoteObject(); int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); + LOGE("write result failed"); return DM_WRITE_FAILED; } return DM_OK; @@ -221,7 +221,7 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce std::string pkgName = data.ReadString(); int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); + LOGE("write result failed"); return DM_WRITE_FAILED; } return DM_OK; @@ -235,11 +235,11 @@ ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) int32_t result = DM_POINT_NULL; if (subscribeInfo != nullptr) { - DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); + LOGI("pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo, extra); } if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); + LOGE("write result failed"); return DM_WRITE_FAILED; } return DM_OK; @@ -249,10 +249,10 @@ 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); + LOGI("pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeId); int32_t result = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); + LOGE("write result failed"); return DM_WRITE_FAILED; } return DM_OK; @@ -270,7 +270,7 @@ ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) result = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, nullptr, extra); } if (!reply.WriteInt32(result)) { - DMLOG(DM_LOG_ERROR, "write result failed"); + LOGE("write result failed"); return DM_WRITE_FAILED; } return DM_OK; @@ -281,7 +281,7 @@ ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) std::string authPara = data.ReadString(); // int32_t result = DeviceManagerService::GetInstance().VerifyAuthentication(authPara); // if (!reply.WriteInt32(result)) { -// DMLOG(DM_LOG_ERROR, "write result failed"); +// LOGE("write result failed"); // return DM_WRITE_FAILED; // } return DM_OK; @@ -292,12 +292,12 @@ ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) // std::string packName = data.ReadString(); // DmAuthParam authParam; // int32_t ret = DM_OK; -// DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); +// LOGE("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); // DeviceManagerService::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"); +// LOGE("DeviceManagerStub::wirte client fail"); // ret = DM_WRITE_FAILED; // } // return ret; @@ -310,20 +310,20 @@ ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) // !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"); +// LOGE("write reply failed"); // return DM_WRITE_FAILED; // } // // if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { // if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { -// DMLOG(DM_LOG_ERROR, "write appIcon failed"); +// LOGE("write appIcon failed"); // return DM_WRITE_FAILED; // } // } // // if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { // if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { -// DMLOG(DM_LOG_ERROR, "write appThumbnail failed"); +// LOGE("write appThumbnail failed"); // return DM_WRITE_FAILED; // } // } @@ -338,7 +338,7 @@ ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) // int result = DeviceManagerService::GetInstance().SetUserOperation(packageName, action); // // if (!reply.WriteInt32(action)) { -// DMLOG(DM_LOG_ERROR, "write result failed"); +// LOGE("write result failed"); // return DM_WRITE_FAILED; // } // return result; @@ -346,16 +346,16 @@ ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) //ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) //{ -// DMLOG(DM_LOG_INFO, "OnFaCallBack"); +// LOGI("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"); +// LOGE("write pkgName failed"); // return DM_FLATTEN_OBJECT; // } // if (!data.WriteString(paramJson)) { -// DMLOG(DM_LOG_ERROR, "write paramJson failed"); +// LOGE("write paramJson failed"); // return DM_FLATTEN_OBJECT; // } // return DM_OK; diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp index bb9f1c9a2..2f3eb73dc 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp @@ -28,7 +28,7 @@ int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr r { sptr remote = Remote(); if (remote == nullptr) { - DMLOG(DM_LOG_ERROR, "remote service null"); + LOGE("remote service null"); return DM_POINT_NULL; } @@ -39,7 +39,7 @@ int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr r return DM_IPC_FAILED; } if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) { - DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); + LOGE("SendRequest fail, cmd:%d", cmdCode); return DM_IPC_FAILED; } return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp index 346ce2535..597f07487 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp @@ -26,7 +26,7 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr 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()); + LOGI("cannot get listener for package:%s.", pkgName.c_str()); return DM_POINT_NULL; } return listener->SendCmd(cmdCode, req, rsp); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp index 81bb37d6a..10043dfa7 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -47,13 +47,13 @@ IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGE void IpcServerStub::OnStart() { - DMLOG(DM_LOG_INFO, "IpcServerStub::OnStart start"); + LOGI("IpcServerStub::OnStart start"); if (state_ == ServiceRunningState::STATE_RUNNING) { - DMLOG(DM_LOG_DEBUG, "IpcServerStub has already started."); + LOGD("IpcServerStub has already started."); return; } if (!Init()) { - DMLOG(DM_LOG_ERROR, "failed to init IpcServerStub"); + LOGE("failed to init IpcServerStub"); return; } state_ = ServiceRunningState::STATE_RUNNING; @@ -61,11 +61,11 @@ void IpcServerStub::OnStart() bool IpcServerStub::Init() { - DMLOG(DM_LOG_INFO, "IpcServerStub::Init ready to init."); + LOGI("IpcServerStub::Init ready to init."); if (!registerToService_) { bool ret = Publish(this); if (!ret) { - DMLOG(DM_LOG_ERROR, "IpcServerStub::Init Publish failed!"); + LOGE("IpcServerStub::Init Publish failed!"); return false; } registerToService_ = true; @@ -81,7 +81,7 @@ bool IpcServerStub::Init() void IpcServerStub::OnStop() { - DMLOG(DM_LOG_INFO, "IpcServerStub::OnStop ready to stop service."); + LOGI("IpcServerStub::OnStop ready to stop service."); state_ = ServiceRunningState::STATE_NOT_START; registerToService_ = false; } @@ -89,11 +89,11 @@ void IpcServerStub::OnStop() int32_t IpcServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - DMLOG(DM_LOG_INFO, "code = %d, flags= %d.", code, option.GetFlags()); + 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) { - DMLOG(DM_LOG_WARN, "unsupport code: %d", code); + LOGW("unsupport code: %d", code); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } return ret; @@ -112,21 +112,21 @@ ServiceRunningState IpcServerStub::QueryServiceState() const int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr listener) { if (pkgName.empty() || listener == nullptr) { - DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); + LOGE("Error: parameter invalid"); return DM_POINT_NULL; } - DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); + LOGI("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"); + LOGI("RegisterDeviceManagerListener: listener already exists"); return DM_OK; } sptr appRecipient = sptr(new AppDeathRecipient()); if (!listener->AddDeathRecipient(appRecipient)) { - DMLOG(DM_LOG_ERROR, "RegisterDeviceManagerListener: AddDeathRecipient Failed"); + LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); } dmListener_[pkgName] = listener; appRecipient_[pkgName] = appRecipient; @@ -136,21 +136,21 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) { if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); + LOGE("Error: parameter invalid"); return DM_POINT_NULL; } - DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); + LOGI("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"); + LOGI("UnRegisterDeviceManagerListener: listener not exists"); return DM_OK; } auto recipientIter = appRecipient_.find(pkgName); if (recipientIter == appRecipient_.end()) { - DMLOG(DM_LOG_INFO, "UnRegisterDeviceManagerListener: appRecipient not exists"); + LOGI("UnRegisterDeviceManagerListener: appRecipient not exists"); dmListener_.erase(pkgName); return DM_OK; } @@ -181,7 +181,7 @@ const sptr IpcServerStub::GetDmListener(std::string pkgName) co void AppDeathRecipient::OnRemoteDied(const wptr &remote) { - DMLOG(DM_LOG_WARN, "AppDeathRecipient: OnRemoteDied"); + LOGW("AppDeathRecipient: OnRemoteDied"); std::map> listeners = IpcServerStub::GetInstance().GetDmListener(); std::string pkgName; for (auto iter : listeners) { @@ -191,10 +191,10 @@ void AppDeathRecipient::OnRemoteDied(const wptr &remote) } } if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "AppDeathRecipient: OnRemoteDied, no pkgName matched"); + LOGE("AppDeathRecipient: OnRemoteDied, no pkgName matched"); return; } - DMLOG(DM_LOG_INFO, "AppDeathRecipient: OnRemoteDied for %s", pkgName.c_str()); + LOGI("AppDeathRecipient: OnRemoteDied for %s", pkgName.c_str()); IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); } } // namespace DistributedHardware diff --git a/utils/include/dm_log.h b/utils/include/dm_log.h index 1d32f22a4..452261707 100644 --- a/utils/include/dm_log.h +++ b/utils/include/dm_log.h @@ -28,9 +28,6 @@ typedef enum { void DMLog(DMLogLevel logLevel, const char *fmt, ...); -#define DMLOG(level, fmt, ...) DMLog(level, \ - (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) - #define LOGD(fmt, ...) DMLog(DM_LOG_DEBUG, \ (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) diff --git a/utils/src/ipc/lite/ipc_cmd_register.cpp b/utils/src/ipc/lite/ipc_cmd_register.cpp index bc930d23d..9d094af27 100644 --- a/utils/src/ipc/lite/ipc_cmd_register.cpp +++ b/utils/src/ipc/lite/ipc_cmd_register.cpp @@ -27,7 +27,7 @@ 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); + LOGE("cmdCode:%d not register SetRequestFunc", cmdCode); return DM_IPC_NOT_REGISTER_FUNC; } return (setRequestMapIter->second)(pBaseReq, request, buffer, buffLen); @@ -37,7 +37,7 @@ 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); + LOGE("cmdCode:%d not register ReadResponseFunc", cmdCode); return DM_IPC_NOT_REGISTER_FUNC; } return (readResponseMapIter->second)(reply, pBaseRsp); @@ -47,7 +47,7 @@ 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); + LOGE("cmdCode:%d not register OnIpcCmdFunc", cmdCode); return DM_IPC_NOT_REGISTER_FUNC; } (onIpcCmdMapIter->second)(reply); @@ -58,7 +58,7 @@ 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); + LOGE("cmdCode:%d not register OnIpcCmdFunc", cmdCode); return DM_IPC_NOT_REGISTER_FUNC; } (onIpcServerCmdMapIter->second)(req, reply); diff --git a/utils/src/ipc/standard/ipc_cmd_register.cpp b/utils/src/ipc/standard/ipc_cmd_register.cpp index 96a175d85..a1949d07d 100644 --- a/utils/src/ipc/standard/ipc_cmd_register.cpp +++ b/utils/src/ipc/standard/ipc_cmd_register.cpp @@ -26,7 +26,7 @@ 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); + LOGE("cmdCode:%d not register SetRequestFunc", cmdCode); return DM_IPC_NOT_REGISTER_FUNC; } return (setRequestMapIter->second)(pBaseReq, data); @@ -36,7 +36,7 @@ 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); + LOGE("cmdCode:%d not register ReadResponseFunc", cmdCode); return DM_IPC_NOT_REGISTER_FUNC; } return (readResponseMapIter->second)(reply, pBaseRsp); @@ -46,7 +46,7 @@ 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); + LOGE("cmdCode:%d not register OnIpcCmdFunc", cmdCode); return DM_IPC_NOT_REGISTER_FUNC; } return (onIpcCmdMapIter->second)(data, reply); -- Gitee From 0fc94d3290c4687115b38a980cad3ef779c86bea Mon Sep 17 00:00:00 2001 From: skypuhui Date: Mon, 29 Nov 2021 02:27:11 +0800 Subject: [PATCH 020/110] =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: skypuhui --- .../native_cpp/include/ipc/lite/ipc_client_manager.h | 6 +++--- .../native_cpp/src/ipc/standard/ipc_client_manager.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) 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 8144399cf..efe32e78c 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 @@ -28,11 +28,11 @@ namespace DistributedHardware { class IpcClientManager : public IpcClient { 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_; 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 6796a78b2..e06705763 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 @@ -136,7 +136,7 @@ int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr r return dmInterface_->SendCmd(cmdCode, req, rsp); } -bool IpcClientManager::IsInit(std::string &pkgName) +bool IpcClientManager::IsInit(const std::string &pkgName) { if (dmInterface_ == nullptr) { LOGE("DeviceManager not Init"); -- Gitee From 9083c82790f7df1a22efe950538718d4ca9e3e88 Mon Sep 17 00:00:00 2001 From: puhui Date: Mon, 29 Nov 2021 09:23:03 +0800 Subject: [PATCH 021/110] =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=80=82=E9=85=8D?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- .../native_cpp/include/ipc/standard/ipc_client_manager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 548686e9c..fee6ac52a 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 @@ -45,7 +45,7 @@ public: 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_; -- Gitee From cc927c39faffcca81f0a45e5d9031c5e82c011f9 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sat, 4 Dec 2021 17:27:36 +0800 Subject: [PATCH 022/110] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=80=82=E9=85=8D?= =?UTF-8?q?=E5=B1=82=E7=9A=84=E7=9B=B8=E5=85=B3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 11 +- .../include/adapter/crypto_adapter.h | 5 + .../include/adapter/decision_adapter.h | 5 + .../include/adapter/dm_adapter_manager.h | 13 +- .../include/adapter/profile_adapter.h | 5 +- .../adapter/{ => ipc}/dm_adapter_manager.cpp | 0 .../adapter/standard/dm_adapter_manager.cpp | 155 ++++++++++++++++++ 7 files changed, 188 insertions(+), 6 deletions(-) rename services/devicemanagerservice/src/adapter/{ => ipc}/dm_adapter_manager.cpp (100%) create mode 100644 services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 4ef70b600..6c4f9eb3f 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -23,8 +23,15 @@ namespace OHOS { namespace DistributedHardware { const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; - - const int32_t LOG_MAX_LEN = 512; + + const std::string DS_SO_NAME = "libdevicemanagerservice_ds_adapter.z.so"; + const std::string DP_SO_NAME = "libdevicemanagerservice_dp_adapter.z.so"; + const std::string CRYPTO_SO_NAME = "ibdevicemanagerservice_crypto_adapter.z.so"; + const std::string CREATE_IDECISION = "CreateIDecisionAdapter"; + const std::string CREATE_IPROFILE = "CreateIProfileAdapter"; + const std::string CREATE_ICRYPTO = "CreateICryptoAdapterFuncPtr"; + + 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; diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h index ea1fc3146..342dfdba0 100644 --- a/services/devicemanagerservice/include/adapter/crypto_adapter.h +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.h @@ -17,6 +17,7 @@ #define OHOS_DM_CRYPTO_ADAPTER_H #include +#include namespace OHOS { namespace DistributedHardware { @@ -28,6 +29,10 @@ public: virtual int32_t MbedTlsDecrypt(const uint8_t *cipherText, int32_t cipherTextLen, uint8_t *plainText, int32_t plainTextLen, int32_t *outLen) = 0; }; + +using CreateICryptoAdapterFuncPtr = std::shared_ptr (*)(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 index a9c0f5daa..9a353f863 100644 --- a/services/devicemanagerservice/include/adapter/decision_adapter.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.h @@ -18,6 +18,7 @@ #include #include +#include #include "dm_device_info.h" @@ -29,6 +30,10 @@ public: 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 = std::shared_ptr (*)(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 index 1297b694e..915e91483 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -22,16 +22,22 @@ #include "profile_adapter.h" #include "crypto_adapter.h" - namespace OHOS { namespace DistributedHardware { class DmAdapterManager { public: - DmAdapterManager(); - ~DmAdapterManager(); + static DmAdapterManager& GetInstance(); +public: std::shared_ptr GetDecisionAdapter(); std::shared_ptr GetProfileAdapter(); std::shared_ptr GetCryptoAdapter(); +private: + DmAdapterManager() = default; + ~DmAdapterManager(); + DmAdapterManager(const DmAdapterManager&) = delete; + DmAdapterManager& operator= (const DmAdapterManager&) = delete; + DmAdapterManager(DmAdapterManager&&) = delete; + DmAdapterManager& operator= (DmAdapterManager&&) = delete; private: std::shared_ptr decisionAdapterPtr_; std::shared_ptr profileAdapterPtr_; @@ -39,4 +45,5 @@ private: }; } // namespace DistributedHardware } // namespace OHOS + #endif // OHOS_DM_DEVICE_STATE_MAGANGER_H diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index f63d8f842..b41c056eb 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -16,7 +16,6 @@ #ifndef OHOS_DM_PROFILE_ADAPTER_H #define OHOS_DM_PROFILE_ADAPTER_H - namespace OHOS { namespace DistributedHardware { class IProfileAdapter { @@ -25,6 +24,10 @@ public: virtual int32_t RegisterProfileListener() = 0; virtual int32_t UnRegisterProfileListener() = 0; }; + +using CreateIProfileAdapterFuncPtr = std::shared_ptr (*)(void); + } // namespace DistributedHardware } // namespace OHOS + #endif // OHOS_DM_PROFILE_ADAPTER_H diff --git a/services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/ipc/dm_adapter_manager.cpp similarity index 100% rename from services/devicemanagerservice/src/adapter/dm_adapter_manager.cpp rename to services/devicemanagerservice/src/adapter/ipc/dm_adapter_manager.cpp 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..7ec23d2cb --- /dev/null +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "dm_adapter_manager.h" +#include "dm_log.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +static DmAdapterManager& DmAdapterManager::GetInstance() +{ + static DmAdapterManager instance; + return instance; +} + +DmAdapterManager::~DmAdapterManager() +{ + void *so_handle = nullptr; + so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (handler != nullptr) { + dlclose(so_handle); + } + + so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (handler != nullptr) { + dlclose(so_handle); + } + + so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (handler != nullptr) { + dlclose(so_handle); + } + LOGI("DmAdapterManager destructor"); +} + +std::shared_ptr DmAdapterManager::GetDecisionAdapter() +{ + void *so_handle = nullptr; + so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle != nullptr) + { + LOGI("GetDecisionAdapter: %s has been loaded\n", ds_so_name.c_str()); + if (decisionAdapterPtr_ != nullptr) { + return decisionAdapterPtr_; + } + + CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_IDECISION.c_str()); + if (dlerror() == nullptr || ptr == nullptr) { + LOGE("GetDecisionAdapter:Create function is not exist"); + return nullptr; + } + decisionAdapterPtr_ = func(); + return decisionAdapterPtr_; + } else { + void *so_handle = dlopen("DS_SO_NAME.c_str() ", RTLD_NOW); + if (so_handle == nullptr) { + LOGE( "GetDecisionAdapter:load so %s failed.\n", soname); + return nullptr; + } + + CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_IDECISION.c_str()); + if (dlerror() == nullptr || ptr == nullptr) { + LOGE("GetDecisionAdapter:Create function is not exist"); + return nullptr; + } + decisionAdapterPtr_ = func(); + return decisionAdapterPtr_; + } +} + +std::shared_ptr DmAdapterManager::GetProfileAdapter() +{ + void *so_handle = nullptr; + so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle != nullptr) + { + LOGI("GetProfileAdapter: %s has been loaded\n", ds_so_name.c_str()); + if (profileAdapterPtr_ != nullptr) { + return profileAdapterPtr_; + } + + CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr*)dlsym(so_handle, CREATE_IPROFILE.c_str()); + if (dlerror() == nullptr || ptr == nullptr) { + LOGE("GetProfileAdapter:Create function is not exist"); + return nullptr; + } + profileAdapterPtr_ = func(); + return profileAdapterPtr_; + } else { + void *so_handle = dlopen("DP_SO_NAME.c_str() ", RTLD_NOW); + if (so_handle == nullptr) { + LOGE( "GetProfileAdapter:load so %s failed.\n", soname); + return nullptr; + } + + CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr*)dlsym(so_handle, CREATE_IPROFILE.c_str()); + if (dlerror() == nullptr || ptr == nullptr) { + LOGE("GetProfileAdapter:Create function is not exist"); + return nullptr; + } + profileAdapterPtr_ = func(); + return profileAdapterPtr_; + } +} + +std::shared_ptr DmAdapterManager::GetCryptoAdapter() +{ + void *so_handle = nullptr; + so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); + if (so_handle != nullptr) + { + LOGI("GetCryptoAdapter: %s has been loaded\n", ds_so_name.c_str()); + if (cryptoAdapterPtr_ != nullptr) { + return cryptoAdapterPtr_; + } + + CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_ICRYPTO.c_str()); + if (dlerror() == nullptr || ptr == nullptr) { + LOGE("GetCryptoAdapter:Create function is not exist"); + return nullptr; + } + cryptoAdapterPtr_ = func(); + return cryptoAdapterPtr_; + } else { + void *so_handle = dlopen("CRYPTO_SO_NAME.c_str() ", RTLD_NOW); + if (so_handle == nullptr) { + LOGE( "GetCryptoAdapter:load so %s failed.\n", soname); + return nullptr; + } + + CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_ICRYPTO.c_str); + if (dlerror() == nullptr || ptr == nullptr) { + LOGE("GetCryptoAdapter:Create function is not exist"); + return nullptr; + } + cryptoAdapterPtr_ = func(); + return cryptoAdapterPtr_; + } +} +} +} -- Gitee From 9e4b5adff5b9b888d6ab72a585665bd073a19bcf Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Tue, 7 Dec 2021 10:16:56 +0800 Subject: [PATCH 023/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=80=82=E9=85=8D?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E7=BC=96=E8=AF=91=E5=A4=B1=E8=B4=A5=E7=9A=84?= =?UTF-8?q?bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/devicemanagerservice/BUILD.gn | 2 +- .../adapter/standard/dm_adapter_manager.cpp | 50 +++++++++---------- .../src/deviceinfo/dm_device_info_manager.cpp | 19 +++---- 3 files changed, 33 insertions(+), 38 deletions(-) diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 8df17c274..103263ffa 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -131,7 +131,7 @@ if (defined(ohos_lite)) { sources = [ "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", - "src/adapter/dm_adapter_manager.cpp", + "src/adapter/standard/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", diff --git a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp index 7ec23d2cb..cdbb332be 100644 --- a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { -static DmAdapterManager& DmAdapterManager::GetInstance() +DmAdapterManager& DmAdapterManager::GetInstance() { static DmAdapterManager instance; return instance; @@ -31,17 +31,17 @@ DmAdapterManager::~DmAdapterManager() { void *so_handle = nullptr; so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (handler != nullptr) { + if (so_handle != nullptr) { dlclose(so_handle); } so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (handler != nullptr) { + if (so_handle != nullptr) { dlclose(so_handle); } so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (handler != nullptr) { + if (so_handle != nullptr) { dlclose(so_handle); } LOGI("DmAdapterManager destructor"); @@ -53,27 +53,27 @@ std::shared_ptr DmAdapterManager::GetDecisionAdapter() so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { - LOGI("GetDecisionAdapter: %s has been loaded\n", ds_so_name.c_str()); + LOGI("GetDecisionAdapter: %s has been loaded\n", DS_SO_NAME.c_str()); if (decisionAdapterPtr_ != nullptr) { return decisionAdapterPtr_; } - CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_IDECISION.c_str()); - if (dlerror() == nullptr || ptr == nullptr) { + CreateIDecisionAdapterFuncPtr func = (CreateIDecisionAdapterFuncPtr)dlsym(so_handle, CREATE_IDECISION.c_str()); + if (dlerror() == nullptr || func == nullptr) { LOGE("GetDecisionAdapter:Create function is not exist"); return nullptr; } decisionAdapterPtr_ = func(); return decisionAdapterPtr_; } else { - void *so_handle = dlopen("DS_SO_NAME.c_str() ", RTLD_NOW); + void *so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW); if (so_handle == nullptr) { - LOGE( "GetDecisionAdapter:load so %s failed.\n", soname); + LOGE( "GetDecisionAdapter:load so %s failed.\n", DS_SO_NAME.c_str()); return nullptr; } - CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_IDECISION.c_str()); - if (dlerror() == nullptr || ptr == nullptr) { + CreateIDecisionAdapterFuncPtr func = (CreateIDecisionAdapterFuncPtr)dlsym(so_handle, CREATE_IDECISION.c_str()); + if (dlerror() == nullptr || func == nullptr) { LOGE("GetDecisionAdapter:Create function is not exist"); return nullptr; } @@ -88,27 +88,27 @@ std::shared_ptr DmAdapterManager::GetProfileAdapter() so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { - LOGI("GetProfileAdapter: %s has been loaded\n", ds_so_name.c_str()); + LOGI("GetProfileAdapter: %s has been loaded\n", DP_SO_NAME.c_str()); if (profileAdapterPtr_ != nullptr) { return profileAdapterPtr_; } - CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr*)dlsym(so_handle, CREATE_IPROFILE.c_str()); - if (dlerror() == nullptr || ptr == nullptr) { + CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr)dlsym(so_handle, CREATE_IPROFILE.c_str()); + if (dlerror() == nullptr || func == nullptr) { LOGE("GetProfileAdapter:Create function is not exist"); return nullptr; } profileAdapterPtr_ = func(); return profileAdapterPtr_; } else { - void *so_handle = dlopen("DP_SO_NAME.c_str() ", RTLD_NOW); + void *so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW); if (so_handle == nullptr) { - LOGE( "GetProfileAdapter:load so %s failed.\n", soname); + LOGE( "GetProfileAdapter:load so %s failed.\n", DP_SO_NAME.c_str()); return nullptr; } - CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr*)dlsym(so_handle, CREATE_IPROFILE.c_str()); - if (dlerror() == nullptr || ptr == nullptr) { + CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr)dlsym(so_handle, CREATE_IPROFILE.c_str()); + if (dlerror() == nullptr || func == nullptr) { LOGE("GetProfileAdapter:Create function is not exist"); return nullptr; } @@ -123,27 +123,27 @@ std::shared_ptr DmAdapterManager::GetCryptoAdapter() so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { - LOGI("GetCryptoAdapter: %s has been loaded\n", ds_so_name.c_str()); + LOGI("GetCryptoAdapter: %s has been loaded\n", CRYPTO_SO_NAME.c_str()); if (cryptoAdapterPtr_ != nullptr) { return cryptoAdapterPtr_; } - CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_ICRYPTO.c_str()); - if (dlerror() == nullptr || ptr == nullptr) { + CreateICryptoAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr)dlsym(so_handle, CREATE_ICRYPTO.c_str()); + if (dlerror() == nullptr || func == nullptr) { LOGE("GetCryptoAdapter:Create function is not exist"); return nullptr; } cryptoAdapterPtr_ = func(); return cryptoAdapterPtr_; } else { - void *so_handle = dlopen("CRYPTO_SO_NAME.c_str() ", RTLD_NOW); + void *so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW); if (so_handle == nullptr) { - LOGE( "GetCryptoAdapter:load so %s failed.\n", soname); + LOGE( "GetCryptoAdapter:load so %s failed.\n", CRYPTO_SO_NAME.c_str()); return nullptr; } - CreateIDecisionAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr*)dlsym(so_handle, CREATE_ICRYPTO.c_str); - if (dlerror() == nullptr || ptr == nullptr) { + CreateICryptoAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr)dlsym(so_handle, CREATE_ICRYPTO.c_str()); + if (dlerror() == nullptr || func == nullptr) { LOGE("GetCryptoAdapter:Create function is not exist"); return nullptr; } diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index c4801010f..672d83184 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -34,19 +34,14 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co } if (!extra.empty() && !deviceList.empty()) { - adapterMgrPtr_ = std::make_shared(); - if (adapterMgrPtr_ == nullptr) { - LOGE("GetTrustedDeviceList adapterMgrPtr_ is nullptr"); - return DM_POINT_NULL; + DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(); + if (decisionAdapter != nullptr) { + //decisionAdapter->FilterDeviceList(deviceList, extra); + } else { + //LOGE("GetTrustedDeviceList decisionAdapter is nullptr"); + //return DM_POINT_NULL; } - -// IDecisionAdapter decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); -// if (decisionAdapter != nullptr) { -// decisionAdapter->FilterDeviceList(deviceList, extra); -// } else { -// LOGE("GetTrustedDeviceList decisionAdapter is nullptr"); -// return DM_POINT_NULL; -// } } return DM_OK; -- Gitee From 0adf72455a886558dde1e34ac99f9c99e7e6bced Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Tue, 7 Dec 2021 18:39:38 +0800 Subject: [PATCH 024/110] JSAPI --- common/include/dm_constants.h | 51 +- .../kits/js/include/native_devicemanager_js.h | 38 +- .../kits/js/src/native_devicemanager_js.cpp | 502 ++++++++++++++---- 3 files changed, 488 insertions(+), 103 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 6c4f9eb3f..13df174b8 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -21,6 +21,8 @@ namespace OHOS { namespace DistributedHardware { + const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; + const std::string HOST_PKG_NAME_KEY = "hostPackageName"; const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; @@ -32,10 +34,10 @@ namespace DistributedHardware { const std::string CREATE_ICRYPTO = "CreateICryptoAdapterFuncPtr"; 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 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; enum { @@ -52,6 +54,7 @@ namespace DistributedHardware { DM_MALLOC_ERROR, DM_COPY_FAILED, DM_WRITE_FAILED, + DM_DISCOVERY_FAILED, DM_MAKE_SHARED_FAIL, DM_SERVICE_NOT_READY, DM_DEVICE_ALREADY_TRUSTED, @@ -69,7 +72,47 @@ namespace DistributedHardware { DM_HICHAIN_MEMBER_ADD_FAILED, DM_HICHAIN_CREATE_CHANNEL_FAILED, }; + 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"; + 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 int32_t MSG_MAX_SIZE = 45 * 1024; + //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 DEFAULT_PIN_CODE = 0; + const int32_t DEFAULT_PIN_TOKEN = 0; //Softbus const std::string CAPABILITY_OSD = "osdCapability"; const int32_t SOFTBUS_CHECK_INTERVAL = 100000; // 100ms diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 05b4aca07..4a9e32484 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -26,7 +26,7 @@ #include "dm_device_info.h" #include "dm_subscribe_info.h" #include "dm_device_info.h" - +#include "dm_app_image_info.h" #define DM_NAPI_BUF_LENGTH (256) struct AsyncCallbackInfo { @@ -40,6 +40,20 @@ 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; + // OHOS::DistributedHardware::DmFilterOptions filter; + napi_ref callback = nullptr; + napi_value thisVar = nullptr; + napi_deferred deferred = nullptr; + int32_t status = -1; +}; struct AuthAsyncCallbackInfo { napi_env env = nullptr; @@ -124,14 +138,16 @@ 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 GetTrustedDeviceListSync(napi_env env, napi_callback_info info); + static napi_value SetUserOperationSync(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 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); @@ -167,13 +183,27 @@ public: 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); void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); 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); - +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); private: napi_env env_; napi_ref wrapper_; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 11ae6edaf..833f4acbe 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -201,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); @@ -521,41 +522,6 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & info.deviceTypeId = (DmDeviceType)deviceType; } -//void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const napi_value &object, -// DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) -//{ -// LOGI("JsToDmAppImageInfoAndDmExtra in."); -// int32_t authTypeTemp = -1; -// JsObjectToInt(env, object, "authType", authTypeTemp); -// authType = authTypeTemp; -// -// uint8_t *appIconBufferPtr = nullptr; -// int32_t appIconBufferLen = 0; -// JsToDmBuffer(env, object, "appIcon", &appIconBufferPtr, appIconBufferLen); -// -// uint8_t *appThumbnailBufferPtr = nullptr; -// int32_t appThumbnailBufferLen = 0; -// JsToDmBuffer(env, object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); -// -// appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); -// if (appIconBufferPtr != nullptr) { -// free(appIconBufferPtr); -// appIconBufferPtr = nullptr; -// } -// if (appThumbnailBufferPtr != nullptr) { -// free(appThumbnailBufferPtr); -// appThumbnailBufferPtr = nullptr; -// } -// -// nlohmann::json jsonObj; -// jsonObj[AUTH_TYPE] = authType; -// std::string extraInfo = "extraInfo"; -// -// JsToJsonObject(env, object, "extraInfo", jsonObj); -// extra = jsonObj.dump(); -// 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) { @@ -674,6 +640,27 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob extra = jsonObj.dump(); } +// void DeviceManagerNapi::JsToDmFilterOptions(const napi_env &env, const napi_value &object, +// DmFilterOptions &filterOptions) +// { +// JsObjectToString(env, object, "targetPkgName", filterOptions.targetPkgName, sizeof(filterOptions.targetPkgName)); +// int32_t sortType = -1; +// JsObjectToInt(env, object, "sortType", sortType); +// filterOptions.sortType = (DmDeviceSortType)sortType; +// JsObjectToString(env, object, "filter", filterOptions.filter, sizeof(filterOptions.filter)); +// } + + +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) { LOGE("CreateDmCallback for bundleName %s eventType %s", bundleName.c_str(), eventType.c_str()); @@ -768,43 +755,299 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & // return resultParam; //} -napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callback_info info) +napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_info info) +{ + LOGI("SetUserOperationSync in"); + GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Object expected."); + + int32_t action = 0; + napi_get_value_int32(env, argv[0], &action); + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + // int32_t ret = DeviceManager::GetInstance().SetUserOperation(deviceManagerWrapper->bundleName_, action); + // if (ret != 0) { + // LOGE("SetUserOperation for bunderName %s failed, ret %d", + // deviceManagerWrapper->bundleName_.c_str(), ret); + // } + napi_value result = nullptr; + napi_get_undefined(env, &result); + return result; +} + +void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(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 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]); + } +} + +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"); + } + + 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::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 = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + // deviceInfoAsyncCallbackInfo->filter, deviceInfoAsyncCallbackInfo->devList); + // 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; + CallGetTrustedDeviceListStatusSync(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 = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + // deviceInfoAsyncCallbackInfo->filter, deviceInfoAsyncCallbackInfo->devList); + // 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; + CallGetTrustedDeviceListStatus(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; + // DmFilterOptions filterOptions; + // memset_s(filterOptions.targetPkgName, sizeof(filterOptions.targetPkgName), 0, sizeof(filterOptions.targetPkgName)); + // int32_t sortType = -1; + // filterOptions.sortType = (DmDeviceSortType)sortType; + // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); + // deviceInfoAsyncCallbackInfo->filter = filterOptions; + GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[0], &eventHandleType); + if (eventHandleType == napi_function) { + LOGE("GetLocalDeviceInfo 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("GetLocalDeviceInfo 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; + // JsToDmFilterOptions(env, argv[0], filterOptions); + // deviceInfoAsyncCallbackInfo->filter = filterOptions; + CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); + return promise; + } +} + +napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_info info) { LOGI("GetTrustedDeviceList in"); - size_t argc = 0; + napi_value result = nullptr; napi_value thisVar = nullptr; - napi_value array = nullptr; - + size_t argc = 0; + std::vector devList; 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)); - std::string extra = ""; - std::vector devList; - int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceManagerWrapper->bundleName_, extra, devList); + auto *deviceInfoAsyncCallbackInfo = new DeviceInfoAsyncCallbackInfo(); + deviceInfoAsyncCallbackInfo->env = env; + deviceInfoAsyncCallbackInfo->devList = devList; + deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; + LOGE("GetLocalDeviceInfo for argc %d", argc); + if(argc == 0) { + // DmFilterOptions filterOptions; + // memset_s(filterOptions.targetPkgName, sizeof(filterOptions.targetPkgName), 0, + // sizeof(filterOptions.targetPkgName)); + // int32_t sortType = -1; + // filterOptions.sortType = (DmDeviceSortType)sortType; + // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); + // deviceInfoAsyncCallbackInfo->filter = filterOptions; + 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); + NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); + + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[1], &eventHandleType); + NAPI_ASSERT(env, eventHandleType == napi_function, "Wrong argument type. Object expected."); + + LOGE("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); + // JsToDmFilterOptions(env, argv[0], filterOptions); + // deviceInfoAsyncCallbackInfo->filter = filterOptions; + 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(deviceInfo); if (ret != 0) { - LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); - return array; + 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; +} - if (devList.size() > 0) { - bool isArray = false; - napi_create_array(env, &array); - napi_is_array(env, array, &isArray); - if (isArray == false) { - LOGE("napi_create_array fail"); - } +napi_value DeviceManagerNapi::UnAuthenticateDevice(napi_env env, napi_callback_info info) +{ + LOGI("UnAuthenticateDevice"); + napi_value result = nullptr; + napi_valuetype deviceInfoType; - for (size_t i = 0; i != devList.size(); ++i) { - DeviceInfoToJsArray(env, devList, i, array); - } - } else { - LOGE("devList is null"); + GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); + napi_typeof(env, argv[0], &deviceInfoType); + NAPI_ASSERT(env, deviceInfoType == napi_object, "Wrong argument type. Object expected."); + + DmDeviceInfo deviceInfo; + JsToDmDeviceInfo(env, argv[0], deviceInfo); + + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + int32_t ret = DeviceManager::GetInstance().UnAuthenticateDevice(deviceManagerWrapper->bundleName_, + deviceInfo); + 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) @@ -831,14 +1074,15 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac int32_t res = JsToDmSubscribeInfo(env, argv[0], subInfo); NAPI_ASSERT(env, res == 0, "Wrong subscribeId "); + std::string extra = ""; //TODO: -// int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, -// subInfo, DiscoveryCallback); -// if (ret != 0) { -// LOGE("StartDeviceDiscovery for bunderName %s failed, ret %d", -// deviceManagerWrapper->bundleName_.c_str(), ret); -// return result; -// } + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, + subInfo, extra, DiscoveryCallback); + if (ret != 0) { + LOGE("StartDeviceDiscovery for bunderName %s failed, ret %d", + deviceManagerWrapper->bundleName_.c_str(), ret); + return result; + } napi_get_undefined(env, &result); return result; @@ -909,7 +1153,7 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf // DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); std::string extra; -// JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], extra, authAsyncCallbackInfo_.authType); +// JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], appImageInfo, extra, authAsyncCallbackInfo_.authType); //TODO:get real authType int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, @@ -963,20 +1207,8 @@ napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info in 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[]) { - 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"); - - 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); @@ -984,6 +1216,10 @@ 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; @@ -991,7 +1227,8 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) LOGI("JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); - deviceManagerWrapper->On(eventType, argv[1]); + deviceManagerWrapper->On(eventType, argv[num+1]); + CreateDmCallback(deviceManagerWrapper->bundleName_, eventType); napi_value result = nullptr; @@ -999,26 +1236,55 @@ 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) { - 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"); + 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[]) +{ + // DmFilterOptions filterOptions; size_t typeLen = 0; napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen); - + // if(num){ + // JsToDmFilterOptions(env, argv[1], filterOptions); + // } NAPI_ASSERT(env, typeLen > 0, "typeLen == 0"); NAPI_ASSERT(env, typeLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN"); char type[DM_NAPI_BUF_LENGTH] = {0}; @@ -1038,6 +1304,50 @@ 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) { LOGI("ReleaseDeviceManager in"); @@ -1183,12 +1493,14 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) napi_value dmClass = nullptr; napi_property_descriptor dmProperties[] = { DECLARE_NAPI_FUNCTION("release", ReleaseDeviceManager), - DECLARE_NAPI_FUNCTION("getTrustedDeviceListSync", GetTrustedDeviceListSync), + DECLARE_NAPI_FUNCTION("getTrustedDeviceListSync", GetTrustedDeviceList), DECLARE_NAPI_FUNCTION("startDeviceDiscovery", StartDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("stopDeviceDiscovery", StopDeviceDiscoverSync), + DECLARE_NAPI_FUNCTION("getLocalDeviceInfoSync", GetLocalDeviceInfoSync), + DECLARE_NAPI_FUNCTION("unAuthenticateDevice", UnAuthenticateDevice), DECLARE_NAPI_FUNCTION("authenticateDevice", AuthenticateDevice), DECLARE_NAPI_FUNCTION("verifyAuthInfo", VerifyAuthInfo), -// DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync), + DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync), // DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync), DECLARE_NAPI_FUNCTION("on", JsOn), DECLARE_NAPI_FUNCTION("off", JsOff) -- Gitee From bc17b4b3b06323cbce70df06a1a010fbc1da3a5b Mon Sep 17 00:00:00 2001 From: puhui Date: Wed, 8 Dec 2021 18:34:42 +0800 Subject: [PATCH 025/110] =?UTF-8?q?=E6=9E=B6=E6=9E=84=E9=80=82=E9=85=8D?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/include/dm_constants.h | 28 +- ext/pin_auth/BUILD.gn | 44 +++ .../pin_auth/include}/pin_auth.h | 7 +- .../pin_auth/include}/pin_auth_ui.h | 6 +- ext/pin_auth/src/pin_auth.cpp | 24 ++ ext/pin_auth/src/pin_auth_ui.cpp | 24 ++ ext/profile/BUILD.gn | 26 +- ext/profile/include/device_profile_adapter.h | 12 +- services/devicemanagerservice/BUILD.gn | 15 +- .../include/adapter/crypto_adapter.h | 2 + .../include/adapter/decision_adapter.h | 2 + .../include/adapter/dm_adapter_manager.h | 2 +- .../authentication/auth_message_processor.h | 52 +++ .../authentication/auth_request_state.h | 92 +++++ .../authentication/auth_response_state.h | 80 +++++ .../include/authentication/dm_auth_manager.h | 144 +++++++- .../include/{ => dependency}/eventbus/event.h | 2 +- .../{ => dependency}/eventbus/event_bus.h | 101 +++++- .../eventbus/event_registration.h | 8 +- .../{ => dependency}/eventbus/event_sender.h | 1 - .../eventbus/eventbus_handler.h | 2 +- .../dependency/hichain/hichain_connector.h | 16 +- .../dependency/softbus/softbus_connector.h | 36 +- .../softbus/softbus_discovery_callback.h | 6 +- .../dependency/softbus/softbus_session.h | 16 +- .../softbus/softbus_session_callback.h | 6 +- .../softbus/softbus_state_callback.h | 8 +- .../include/device_manager_service.h | 18 +- .../include/device_manager_service_listener.h | 2 +- .../deviceinfo/dm_device_info_manager.h | 4 +- .../devicestate/dm_device_state_manager.h | 14 +- .../include/discovery/dm_discovery_manager.h | 27 +- .../authentication/auth_message_processor.cpp | 194 +++++++++++ .../src/authentication/auth_request_state.cpp | 139 ++++++++ .../authentication/auth_response_state.cpp | 126 +++++++ .../src/authentication/dm_auth_manager.cpp | 202 ++++++++++- .../src/dependency/eventbus/event_bus.cpp | 24 ++ .../dependency/hichain/hichain_connector.cpp | 166 +++------ .../dependency/softbus/softbus_connector.cpp | 316 +++++++++--------- .../dependency/softbus/softbus_session.cpp | 138 ++++---- .../src/device_manager_service.cpp | 62 ++-- .../src/device_manager_service_listener.cpp | 2 +- .../src/deviceinfo/dm_device_info_manager.cpp | 14 +- .../devicestate/dm_device_state_manager.cpp | 21 +- .../src/discovery/dm_discovery_manager.cpp | 54 ++- utils/BUILD.gn | 16 +- utils/src/dm_random.cpp | 77 +++++ 47 files changed, 1814 insertions(+), 564 deletions(-) create mode 100644 ext/pin_auth/BUILD.gn rename {services/devicemanagerservice/include/authentication/pin_auth => ext/pin_auth/include}/pin_auth.h (86%) rename {services/devicemanagerservice/include/authentication/pin_auth => ext/pin_auth/include}/pin_auth_ui.h (94%) create mode 100644 ext/pin_auth/src/pin_auth.cpp create mode 100644 ext/pin_auth/src/pin_auth_ui.cpp 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 rename services/devicemanagerservice/include/{ => dependency}/eventbus/event.h (99%) rename services/devicemanagerservice/include/{ => dependency}/eventbus/event_bus.h (36%) rename services/devicemanagerservice/include/{ => dependency}/eventbus/event_registration.h (87%) rename services/devicemanagerservice/include/{ => dependency}/eventbus/event_sender.h (98%) rename services/devicemanagerservice/include/{ => dependency}/eventbus/eventbus_handler.h (99%) 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/dependency/eventbus/event_bus.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 4ef70b600..5cc8726fa 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -24,12 +24,19 @@ namespace DistributedHardware { const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; - 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 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 SUBSCRIBE_ID_MASK = 0x0000FFFF; + const int32_t DISCOVER_DEVICE_INFO_MAX_SIZE = 20; + const int32_t ENCRYPT_TAG_LEN = 32; + const int32_t MESSAGE_MAX_SIZE = 45 * 1024; + const int32_t AUTH_REPLY_ACCEPT = 0; + const int32_t AUTH_REPLY_CANCEL = 1; + const int32_t AUTH_REPLY_TIMEOUT = 2; enum { DM_OK = 0, @@ -55,6 +62,9 @@ namespace DistributedHardware { 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_SOFTBUS_FAILED = 3000, DM_SOFTBUS_CREATE_SESSION_SERVER_FAILED, DM_HICHAIN_FAILED = 4000, @@ -68,7 +78,9 @@ namespace DistributedHardware { 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_DEVICEINFO_MAX_SIZE = 20; + 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; //HiChain const int32_t DEVICE_UUID_LENGTH = 65; @@ -78,6 +90,8 @@ namespace DistributedHardware { 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; } } #endif diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn new file mode 100644 index 000000000..b84625d6f --- /dev/null +++ b/ext/pin_auth/BUILD.gn @@ -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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} + +import("//foundation/distributedhardware/devicemanager/devicemanager.gni") + +shared_library("devicemanagerext_pin_auth") { + include_dirs = [ + "${common_path}/include", + "${services_path}/include/adapter/", + ] + + include_dirs += [ + ] + + sources = [ + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerext\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + + ] +} + diff --git a/services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h b/ext/pin_auth/include/pin_auth.h similarity index 86% rename from services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h rename to ext/pin_auth/include/pin_auth.h index 13d672f6a..14c9f2bbf 100644 --- a/services/devicemanagerservice/include/authentication/pin_auth/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.h @@ -16,18 +16,21 @@ #ifndef OHOS_DM_PIN_AUTH_H #define OHOS_DM_PIN_AUTH_H +#include +#include #include "authentication.h" namespace OHOS { namespace DistributedHardware { -class PinAuth : IAuthentication { +class PinAuth : public IAuthentication { public: PinAuth(); + ~PinAuth(); int32_t ShowAuthInfo(); int32_t StartAuth(); private: - std::shared_ptr pinAuthUiPtr_; + std::shared_ptr pinAuthUi_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h b/ext/pin_auth/include/pin_auth_ui.h similarity index 94% rename from services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h rename to ext/pin_auth/include/pin_auth_ui.h index 4219abf08..ee339b143 100644 --- a/services/devicemanagerservice/include/authentication/pin_auth/pin_auth_ui.h +++ b/ext/pin_auth/include/pin_auth_ui.h @@ -17,11 +17,13 @@ #define OHOS_DM_PIN_AUTH_UI_H +#include + namespace OHOS { namespace DistributedHardware { -class PinAuthUI { +class PinAuthUi { public: - PinAuthUI(); + PinAuthUi(); int32_t ShowPinDialog(); int32_t InputPinDialog(); diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp new file mode 100644 index 000000000..2882905a0 --- /dev/null +++ b/ext/pin_auth/src/pin_auth.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} 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..a8e440ca9 --- /dev/null +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_constants.h" + +namespace OHOS { +namespace DistributedHardware { + + +} +} diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn index 37658245e..5db7565da 100644 --- a/ext/profile/BUILD.gn +++ b/ext/profile/BUILD.gn @@ -19,7 +19,7 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -shared_library("devicemanagerext") { +shared_library("devicemanagerext_profile") { include_dirs = [ "${common_path}/include", "${services_path}/include/adapter/", @@ -28,25 +28,9 @@ shared_library("devicemanagerext") { ] 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/anonymous_string.cpp", - # "src/ipc/lite/ipc_cmd_register.cpp", ] defines = [ @@ -56,13 +40,7 @@ shared_library("devicemanagerext") { ] 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", - "//utils/native/lite:utils", + ] } diff --git a/ext/profile/include/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h index 3213e5689..1e58ce5a2 100644 --- a/ext/profile/include/device_profile_adapter.h +++ b/ext/profile/include/device_profile_adapter.h @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef OHOS_DM_ADAPTER_MANAGER_H -#define OHOS_DM_ADAPTER_MANAGER_H +#ifndef OHOS_DM_ADAPTER_DEVICE_PROFILE_H +#define OHOS_DM_ADAPTER_DEVICE_PROFILE_H #include "profile_adapter.h" namespace OHOS { namespace DistributedHardware { -class DeviceProfileAdapter : IProfileAdapter { +class DeviceProfileAdapter : public IProfileAdapter { public: DeviceProfileAdapter(); private: }; -} -} -#endif +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_ADAPTER_DEVICE_PROFILE_H diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 8df17c274..e8efcb6ab 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -25,12 +25,12 @@ if (defined(ohos_lite)) { "include", "include/adapter", "include/authentication", - "include/authentication/pin_auth", "include/deviceinfo", "include/devicestate", "include/discovery", "include/dependency/hichain", "include/dependency/softbus", +# "include/dependency/eventbus", "include/ipc", "include/ipc/lite", "${common_path}/include", @@ -65,9 +65,13 @@ if (defined(ohos_lite)) { "src/device_manager_service_listener.cpp", "src/adapter/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", + "src/authentication/auth_message_processor.cpp", + "src/authentication/auth_request_state.cpp", + "src/authentication/auth_response_state.cpp", "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", +# "src/dependency/eventbus/event_bus.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", @@ -94,8 +98,6 @@ if (defined(ohos_lite)) { "//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", ] } @@ -105,14 +107,15 @@ if (defined(ohos_lite)) { "include", "include/adapter", "include/authentication", - "include/authentication/pin_auth", "include/deviceinfo", "include/devicestate", "include/discovery", "include/dependency/hichain", "include/dependency/softbus", + "include/dependency/eventbus", "include/ipc", "include/ipc/standard", + "include/eventbus", "${common_path}/include", "${common_path}/include/ipc", "${common_path}/include/ipc/model", @@ -133,9 +136,13 @@ if (defined(ohos_lite)) { "src/device_manager_service_listener.cpp", "src/adapter/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", + "src/authentication/auth_message_processor.cpp", + "src/authentication/auth_request_state.cpp", + "src/authentication/auth_response_state.cpp", "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", + "src/dependency/eventbus/event_bus.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h index ea1fc3146..83fc84f33 100644 --- a/services/devicemanagerservice/include/adapter/crypto_adapter.h +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.h @@ -23,6 +23,8 @@ 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, diff --git a/services/devicemanagerservice/include/adapter/decision_adapter.h b/services/devicemanagerservice/include/adapter/decision_adapter.h index a9c0f5daa..3457bae9e 100644 --- a/services/devicemanagerservice/include/adapter/decision_adapter.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.h @@ -26,6 +26,8 @@ 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; }; diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index 1297b694e..325e1ce0b 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -39,4 +39,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_DEVICE_STATE_MAGANGER_H +#endif // OHOS_DM_ADAPTER_MANAGER_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..1a71a0d9d --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.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_AUTH_MESSAGE_PROCESSOR_H +#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_H + +#include +#include +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManager; +struct DmAuthRequestContext; +struct DmAuthResponseContext; +class ICryptoAdapter; +class AuthMessageProcessor { +public: + AuthMessageProcessor(std::shared_ptr authMgr); + virtual ~AuthMessageProcessor() = default; + std::vector CreateAuthRequestMessage(); + std::string CreateSimpleMessage(int32_t msgType); + int32_t ParseMessage(const std::string &message); +private: + std::string CreateRequestAuthMessage(nlohmann::json &json); + void CreateNegotiateMessage(nlohmann::json &json); + void CreateSyncGroupMessage(nlohmann::json &json); + void CreateResponseAuthMessage(nlohmann::json &json); + void ParseAuthRequestMessage(); + void ParseNegotiateMessage(const nlohmann::json &json); +private: + std::shared_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..b8d0569e2 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_request_state.h @@ -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. + */ + +#ifndef OHOS_DM_AUTH_REQUEST_STATE_H +#define OHOS_DM_AUTH_REQUEST_STATE_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManager; +struct DmAuthRequestContext; +class AuthRequestState : public std::enable_shared_from_this{ +public: + virtual ~AuthRequestState() = default; + virtual int32_t GetStateType() = 0; + virtual void Enter() = 0; + void Leave(); + void TransitionTo(std::shared_ptr state); + void SetLastState(std::shared_ptr state); + void SetAuthManager(std::shared_ptr authManager); + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); +protected: + std::shared_ptr authManager_; + std::shared_ptr lastState_; + 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..d9550fe95 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_response_state.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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() = default; + virtual int32_t GetStateType() = 0; + virtual void Enter() = 0; + void Leave(); + void TransitionTo(std::shared_ptr state); + void SetLastState(std::shared_ptr state); + void SetAuthManager(std::shared_ptr authManager); + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); +protected: + std::shared_ptr authManager_; + std::shared_ptr lastState_; + 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/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 514dd85f3..a49c0971d 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -23,25 +23,161 @@ #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" namespace OHOS { namespace DistributedHardware { -class DmAuthManager { + +const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; +const std::string HOST_PKG_NAME_KEY = "hostPackageName"; +const std::string APP_NAME = "appName"; +const std::string APP_DESC = "appDescription"; +const std::string APP_ICON = "appIcon"; +const std::string APP_THUMBNAIL = "appThumbnail"; +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_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 AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; +const int32_t AUTHENTICATE_TIMEOUT = 120; + +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 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; + std::vector syncGroupList; +} DmAuthRequestContext; + +typedef struct DmAuthResponseContext { + std::string deviceId; + int32_t msgType; + bool cryptoSupport; + std::string cryptoName; + std::string cryptoVer; + int32_t reply; + std::string networkId; + std::string groupId; + std::string groupName; + 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 softbusConnectorPtr, std::shared_ptr listenerPtr); + 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 &pkgName, 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 SendAuthRequest(const int32_t &sessionId); + void StartAuthProcess(const int32_t &authType); + void JoinGroup(const std::string &deviceId); + void JoinNetwork(); + void AuthenticateFinish(); +private: + void HandleAuthenticateTimeout(); private: std::shared_ptr softbusConnector_; + std::shared_ptr sessionSession_; std::shared_ptr hiChainConnector_; - std::shared_ptr listenerPtr_; + std::shared_ptr listener_; std::shared_ptr adapterMgr_; -// std::map authenticationMap_; + 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_; + }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/eventbus/event.h b/services/devicemanagerservice/include/dependency/eventbus/event.h similarity index 99% rename from services/devicemanagerservice/include/eventbus/event.h rename to services/devicemanagerservice/include/dependency/eventbus/event.h index 8d9019cdc..8db338218 100644 --- a/services/devicemanagerservice/include/eventbus/event.h +++ b/services/devicemanagerservice/include/dependency/eventbus/event.h @@ -42,7 +42,7 @@ public: } private: EventSender &sender_; -} +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_EVENTBUS_EVENT_H diff --git a/services/devicemanagerservice/include/eventbus/event_bus.h b/services/devicemanagerservice/include/dependency/eventbus/event_bus.h similarity index 36% rename from services/devicemanagerservice/include/eventbus/event_bus.h rename to services/devicemanagerservice/include/dependency/eventbus/event_bus.h index 110e6c994..683bd96bb 100644 --- a/services/devicemanagerservice/include/eventbus/event_bus.h +++ b/services/devicemanagerservice/include/dependency/eventbus/event_bus.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H -#define OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H +#ifndef OHOS_DM_EVENTBUS_H +#define OHOS_DM_EVENTBUS_H #include #include @@ -23,7 +23,9 @@ #include "event_handler.h" #include "event.h" #include "eventbus_handler.h" -#include "event_registeration.h" +#include "event_registration.h" +#include "dm_log.h" +#include "dm_anonymous.h" namespace OHOS { namespace DistributedHardware { @@ -44,17 +46,93 @@ public: return instance_; } + template + static std::shared_ptr AddHandler(const std::string &typeId, EventBusHandler &handler, EventSender &sender) + { + EventBus *instance = GetInstance(); + Registrations *registrations = instance->handlers_[typeId]; + if (registrations == nullptr) { + registrations = new EventRegistration::Registrations(); + instance->handlers_[typeId] = registrations; + } + for (auto ® : *registrations) { + if (reg->GetHandler() == static_cast(&handler) && reg->GetSender() == &sender) { + return reg; + } + } + std::shared_ptr registration = std::make_shared(static_cast(&handler), + &sender); + registrations->insert(registration); + return registration; + } + + template + static std::shared_ptr AddHandler(const std::string &typeId, DistributedHardware::EventBusHandler &handler) + { + return AddHandler(typeId, handler, nullptr); + } + + template + static bool RemoveHandler(const std::string &typeId, std::shared_ptr &eventReg) + { + EventBus *instance = GetInstance(); + Registrations *registrations = instance->handlers_[typeId]; + if (registrations == nullptr) { + return false; + } + auto regIter = registrations->find(eventReg); + if (regIter != registrations->end()) { + registrations->erase(regIter); + return true; + } + return false; + } + + template + static void PostEvent(T &e, int64_t delayTime) + { + auto eventFunc = [e]() mutable { + PostEventInner(e); + }; + if (!eventBusHandler_ && eventBusHandler_->PostTask(eventFunc, e->GetType(), delayTime)) { + LOGE("Eventbus:PostEvent PostTask failed"); + } + } + + template + static void RemoveEvent(T &e) + { + if (!eventBusHandler_ && eventBusHandler_->RemoveTask(e->GetType())) { + LOGE("Eventbus:PostEvent RemoveTask failed"); + } + } + + static void PostTask(const AppExecFwk::InnerEvent::Callback &callback, const std::string &name, int64_t delayTimeInMs) + { + LOGI("Eventbus:PostTask Async, taskName:%s.", GetAnonyString(name).c_str()); + if (eventBusHandler_ != nullptr) { + eventBusHandler_->PostTask(callback, name, delayTimeInMs); + } + } + + static void RemoveTask(const std::string &name) + { + LOGI("Eventbus:RemoveTask Async, taskName:%s.", GetAnonyString(name).c_str()); + if (eventBusHandler_ != nullptr) { + eventBusHandler_->RemoveTask(name); + } + } + private: template static void PostEventInner(T &e) { - Eventbus *instance = GetInstace(); - Registrations *registerations = instance->handlers[e.GetType()]; - if (registerations == nullptr) { + EventBus *instance = GetInstance(); + Registrations *registrations = instance->handlers_[e.GetType()]; + if (registrations == nullptr) { return; } - - for (auto ® : *Registrations) { + for (auto ® : *registrations) { if ((reg->GetSender() == nullptr) || (reg->GetSender() == &e.GetSender())) { static_cast *>(const_cast(reg->GetHandler()))->Dispatch(e); } @@ -63,12 +141,11 @@ private: private: static EventBus *instance_; - static std::share_ptr eventBusHandler_; + static std::shared_ptr eventBusHandler_; using Registrations = std::set>; - using TypeMap = std::unordered_map> *>; + using TypeMap = std::unordered_map> *>; TypeMap handlers_; - }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H +#endif // OHOS_DM_EVENTBUS_H diff --git a/services/devicemanagerservice/include/eventbus/event_registration.h b/services/devicemanagerservice/include/dependency/eventbus/event_registration.h similarity index 87% rename from services/devicemanagerservice/include/eventbus/event_registration.h rename to services/devicemanagerservice/include/dependency/eventbus/event_registration.h index 321d90024..882607866 100644 --- a/services/devicemanagerservice/include/eventbus/event_registration.h +++ b/services/devicemanagerservice/include/dependency/eventbus/event_registration.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H -#define OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H +#ifndef OHOS_DM_EVENTBUS_EVENT_REGISTRATION_H +#define OHOS_DM_EVENTBUS_EVENT_REGISTRATION_H #include #include @@ -31,7 +31,7 @@ public: const void *GetHandler() { - return handler_ + return handler_; } const EventSender *GetSender() @@ -46,4 +46,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_EVENTBUS_EVENT_REGISTERATION_H +#endif // OHOS_DM_EVENTBUS_EVENT_REGISTRATION_H diff --git a/services/devicemanagerservice/include/eventbus/event_sender.h b/services/devicemanagerservice/include/dependency/eventbus/event_sender.h similarity index 98% rename from services/devicemanagerservice/include/eventbus/event_sender.h rename to services/devicemanagerservice/include/dependency/eventbus/event_sender.h index a4c97c3fd..840607e24 100644 --- a/services/devicemanagerservice/include/eventbus/event_sender.h +++ b/services/devicemanagerservice/include/dependency/eventbus/event_sender.h @@ -18,7 +18,6 @@ namespace OHOS { namespace DistributedHardware { -template class EventSender { public: virtual ~EventSender() = default; diff --git a/services/devicemanagerservice/include/eventbus/eventbus_handler.h b/services/devicemanagerservice/include/dependency/eventbus/eventbus_handler.h similarity index 99% rename from services/devicemanagerservice/include/eventbus/eventbus_handler.h rename to services/devicemanagerservice/include/dependency/eventbus/eventbus_handler.h index f443339e0..902f112b5 100644 --- a/services/devicemanagerservice/include/eventbus/eventbus_handler.h +++ b/services/devicemanagerservice/include/dependency/eventbus/eventbus_handler.h @@ -31,7 +31,7 @@ public: { OnEvent(e); } -} +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_EVENTBUS_EVENT_HANDLE_H diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index b376f7c71..ce68ec7c0 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -29,6 +29,13 @@ namespace OHOS { namespace DistributedHardware { +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"; struct GroupInfo { std::string groupName; @@ -51,16 +58,17 @@ public: public: HiChainConnector(); ~HiChainConnector(); - void RegisterHiChainCallback(const std::string &pkgName, const IHiChainConnectorCallback &callback); + 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 AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth); + int32_t AddMember(std::string deviceId, std::string connectInfo); int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); private: int64_t GenRequestId(); void GetRelatedGroups(std::string DeviceId, std::vector &groupList); void SyncGroups(std::string deviceId, std::vector &remoteGroupIdList); - void GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList); + void GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList); int32_t GetGroupInfo(std::string queryParams, std::vector &groupList); // std::string GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth); bool IsGroupCreated(std::string groupName, GroupInfo &groupInfo); @@ -68,7 +76,7 @@ private: private: const DeviceGroupManager *deviceGroupManager_ = nullptr; DeviceAuthCallback deviceAuthCallback_ ; -// std::map hichainConnectorCallback_; + static std::map> hiChainConnectorCallbackMap_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index 9b74e5a25..6884ad5e6 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -27,6 +27,7 @@ #include "dm_subscribe_info.h" #include "softbus_state_callback.h" #include "softbus_discovery_callback.h" +#include "softbus_session.h" namespace OHOS { namespace DistributedHardware { @@ -40,43 +41,34 @@ public: static void OnSoftbusDeviceFound(const DeviceInfo *device); static void OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason); static void OnSoftbusDiscoverySuccess(int32_t subscribeId); + static int32_t GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress); + static ConnectionAddr *GetConnectAddr(const std::string &deviceId); + static bool IsDeviceOnLine(const std::string &deviceId); public: SoftbusConnector(); ~SoftbusConnector(); - int32_t RegisterSoftbusStateCallback(const std::string &pkgName, const ISoftbusStateCallback &callback); + 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 ISoftbusDiscoveryCallback &callback); + 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); - bool IsDeviceOnLine(const std::string &deviceId); -// int32_t GetConnectionIpAddr(const std::string &deviceId, std::string &ipAddr); + std::shared_ptr GetSoftbusSession(); private: int32_t Init(); -// ConnectionAddr *GetConnectAddr(const std::string &deviceId); - // bool GetSubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId); - // bool GetPkgNameBySubscribeId(int32_t adapterId, std::string &pkgName); - // void SaveDiscoveryDeviceInfo(const DeviceInfo *deviceInfo); - // void RemoveDiscoveryDeviceInfo(const std::string deviceId); - void NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo); - void DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo); -// ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); + static void CovertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo); + static void CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo); + static ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); private: - // struct SubscribeInfoAdapter { - // SubscribeInfo info; - // uint16_t subscribeIdOrigin; - // uint16_t subscribeIdPrefix; - // }; - // std::map>> subscribeInfos_; - // std::map> discoveryDeviceInfoMap_; - // std::vector> discoveryDeviceInfoVector_; - // uint16_t subscribeIdPrefix_; - // std::mutex lock_; INodeStateCb softbusNodeStateCb_; IDiscoveryCallback softbusDiscoveryCallback_; IPublishCallback softbusPublishCallback_; + std::shared_ptr softbusSession_; + static std::map> discoveryDeviceInfoMap_; + static std::map> stateCallbackMap_; + static std::map> discoveryCallbackMap_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h index 512cef99d..a862b49ee 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h @@ -21,9 +21,9 @@ namespace OHOS { namespace DistributedHardware { class ISoftbusDiscoveryCallback { public: - virtual int32_t OnDeviceFound(uint16_t sbuscribeId, const DmDeviceInfo &info); - virtual int32_t OnDiscoverySuccess(int32_t subscribeId); - virtual int32_t OnDiscoveryFailed(uint16_t subscribeId, const std::string &failedReason); + 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 diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 0ecba444f..2da087841 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -19,10 +19,10 @@ #include #include #include - +#include +#include #include "session.h" #include "inner_session.h" - #include "softbus_session_callback.h" namespace OHOS { @@ -35,18 +35,14 @@ public: public: SoftbusSession(); ~SoftbusSession(); - int32_t RegisterSessionCallback(const std::string &pkgName, ISoftbusSessionCallback callback); - int32_t UnRegisterSessionCallback(const std::string& pkgName); - int32_t OpenAuthSession(const char *deviceId); + 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 SendMessages(const char *deviceId, std::vector &messages); int32_t SendData(int32_t sessionId, std::string &message); void GetPeerDeviceId(int32_t sessionId, std::string &peerDevId); private: - int32_t SendDataInternal(int32_t sessionId, const void *data, int32_t len); -private: - std::set sessionIdSet_; - std::vector messages_ {}; + static std::map> sessionCallbackMap_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h index 7c8ecf49d..41adf3282 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h @@ -21,9 +21,9 @@ namespace OHOS { namespace DistributedHardware { class ISoftbusSessionCallback { public: - virtual int32_t OnSessionOpened(int32_t sessionId, int32_t result); - virtual int32_t OnSessionClosed(int32_t sessionId); - virtual int32_t OnDataReceived(); + 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; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h index a393742ec..9335ac060 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h @@ -21,10 +21,10 @@ namespace OHOS { namespace DistributedHardware { class ISoftbusStateCallback { public: - virtual int32_t OnDeviceOnline(const DmDeviceInfo &info); - virtual int32_t OnDeviceOfflie(const DmDeviceInfo &info); - virtual int32_t OnDeviceChanged(const DmDeviceInfo &info); - virtual int32_t OnDeviceReady(const DmDeviceInfo &info); + 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 diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index a6c59e887..7b29bb4fa 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -40,21 +40,15 @@ public: 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 &pkgName, const std::string &authParam); -//private: -// DeviceManagerService(const DeviceManagerService&) = delete; -// DeviceManagerService& operator= (const DeviceManagerService&) = delete; -// DeviceManagerService(DeviceManagerService&&) = delete; -// DeviceManagerService& operator= (DeviceManagerService&&) = delete; private: bool intFlag_ = false; - std::shared_ptr authMgrPtr_; - std::shared_ptr deviceInfoMgrPtr_; - std::shared_ptr deviceStateMgrPtr_; - std::shared_ptr discoveryMgrPtr_; - std::shared_ptr softbusConnectorPtr_; - std::shared_ptr listenerPtr_; + std::shared_ptr authMgr_; + std::shared_ptr deviceInfoMgr_; + std::shared_ptr deviceStateMgr_; + std::shared_ptr discoveryMgr_; + std::shared_ptr softbusConnector_; + std::shared_ptr listener_; }; } // 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 index e4b6f73aa..3192895c5 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -25,7 +25,7 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerServiceListener { public: - void OnDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info); + 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, const std::string &failedReason); void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId); diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h index 77fe61dc5..4a111f350 100644 --- a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h @@ -31,8 +31,8 @@ public: int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); int32_t GetLocalDeviceInfo(DmDeviceInfo &info); private: - std::shared_ptr softbusConnectorPtr_; - std::shared_ptr adapterMgrPtr_; + std::shared_ptr softbusConnector_; + std::shared_ptr adapterMgr_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index e7a69515c..7b6ab6f8c 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -23,15 +23,19 @@ namespace OHOS { namespace DistributedHardware { -class DmDeviceStateManager { +class DmDeviceStateManager final : public ISoftbusStateCallback, public std::enable_shared_from_this { public: - DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, std::shared_ptr listenerPtr); + 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); private: - std::shared_ptr softbusConnectorPtr_; - std::shared_ptr adapterMgrPtr_; - std::shared_ptr listenerPtr_; + std::shared_ptr softbusConnector_; + std::shared_ptr adapterMgr_; + std::shared_ptr listener_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h index 823c39b20..cbac75997 100644 --- a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h @@ -23,19 +23,32 @@ namespace OHOS { namespace DistributedHardware { -class DmDiscoveryManager { + +const std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout"; +const int32_t DISCOVERY_TIMEOUT = 120; + +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 softbusConnectorPtr, std::shared_ptr listenerPtr); + 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); +private: + void HandleDiscoveryTimeout(); private: - std::shared_ptr softbusConnectorPtr_; - std::shared_ptr listenerPtr_; - //TODO:discovery queue used to prevent re entry and stop discovery automatically when timeout - //also used to record the pkg which was being discovered + std::shared_ptr softbusConnector_; + std::shared_ptr listener_; std::queue discoveryQueue_; + std::map discoveryContextMap_; }; } // 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..018419456 --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_log.h" +#include "dm_constants.h" +#include "dm_auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +AuthMessageProcessor::AuthMessageProcessor(std::shared_ptr authMgr) : authMgr_(authMgr) +{ + LOGI("AuthMessageProcessor constructor"); +} + +std::vector AuthMessageProcessor::CreateAuthRequestMessage() +{ + LOGI("AuthMessageProcessor::CreateAuthRequestMessage start."); + std::vector jsonStrVec; + int32_t thumbnailSize = authRequestContext_->appThumbnail.size(); + int32_t thumbnailSlice = + ((thumbnailSize / MESSAGE_MAX_SIZE) + (thumbnailSize % MESSAGE_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 * MESSAGE_MAX_SIZE; + int32_t sliceLen = (leftLen > MESSAGE_MAX_SIZE) ? MESSAGE_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 * MESSAGE_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; + 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(); + } +} + +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_GROUPIDS] = authResponseContext_->deviceId; + if (authResponseContext_->reply == 0) { + json[TAG_NET_ID] = authResponseContext_->networkId; + json[TAG_REQUEST_ID] = authResponseContext_->requestId; + json[TAG_GROUP_ID] = authResponseContext_->groupId; + json[TAG_GROUP_NAME] = authResponseContext_->groupName; + } +} + +int32_t AuthMessageProcessor::ParseMessage(const std::string &message) +{ + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + //TODO::try to crypto first then parse json + if (!jsonObject.contains(TAG_INDEX) || !jsonObject.contains(TAG_DEVICE_ID) || !jsonObject.contains(TAG_SLICE_NUM)) { + LOGE("err json string, first time"); + return DM_FAILED; + } + int32_t msgType = jsonObject[TAG_TYPE]; + int32_t sliceNum = jsonObject[TAG_SLICE_NUM]; + authResponseContext_->msgType = msgType; + switch (msgType) { + case MSG_TYPE_NEGOTIATE: + ParseNegotiateMessage(jsonObject); + break; + case MSG_TYPE_REQ_AUTH: + if ((int32_t)authSplitJsonList_.size() < sliceNum) { + authSplitJsonList_.push_back(message); + } else { + ParseAuthRequestMessage(); + } + break; + default: + break; + } + return DM_OK; +} + +void AuthMessageProcessor::ParseAuthRequestMessage() +{ + nlohmann::json jsonObject = authSplitJsonList_.front(); + authResponseContext_->deviceId = jsonObject[TAG_DEVICE_ID]; + authResponseContext_->reply = jsonObject[TAG_REPLY]; +// authResponseContext_->syncGroupList = jsonObject[TAG_GROUPIDS]; + + 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]; + } +} +} +} \ 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..b5ceeedd0 --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_log.h" +#include "dm_constants.h" +#include "dm_auth_manager.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_ = std::move(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) { + state->SetAuthManager(authManager_); + state->SetLastState((std::shared_ptr)this); + state->SetAuthContext(context_); + this->Leave(); + state->Enter(); +} + +int32_t AuthRequestInitState::GetStateType() { + return AuthState::AUTH_REQUEST_INIT; +} + +void AuthRequestInitState::Enter() { + authManager_->EstablishAuthChannel(context_->deviceId); +} + +int32_t AuthRequestNegotiateState::GetStateType() { + return AuthState::AUTH_REQUEST_NEGOTIATE; +} + +void AuthRequestNegotiateState::Enter() { +// //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 +// std::string message = authMessageProcessor_->CreateMessage(MSG_TYPE_NEGOTIATE); +// softbusSession_->SendData(context_.sessionId, message); + authManager_->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); + authManager_->SendAuthRequest(context_->sessionId); +} + +int32_t AuthRequestReplyState::GetStateType() { + return AuthState::AUTH_REQUEST_REPLY; +} + +void AuthRequestReplyState::Enter() { + //1. 收到请求响应,判断用户响应结果 + + //2. 用户授权同意 + + //3. 回调给认证实现模块,启动认证 + authManager_->StartAuthProcess(context_->authType); +} + +int32_t AuthRequestInputState::GetStateType() { + return AuthState::AUTH_REQUEST_INPUT; +} + +void AuthRequestInputState::Enter() { +// //1. 获取用户输入 +// +// //2. 验证认证信息 +// authManager_->VerifyAuthentication(); +} + +int32_t AuthRequestJoinState::GetStateType() { + return AuthState::AUTH_REQUEST_JOIN; +} + +void AuthRequestJoinState::Enter() { + //1. 加入群组 + authManager_->JoinGroup(context_->deviceId); +} + +int32_t AuthRequestNetworkState::GetStateType() { + return AuthState::AUTH_REQUEST_NETWORK; +} + +void AuthRequestNetworkState::Enter() { + //1. 进行组网 +} + +int32_t AuthRequestFinishState::GetStateType() { + return AuthState::AUTH_REQUEST_FINISH; +} + +void AuthRequestFinishState::Enter() { + //1. 清理资源 + //2. 通知对端认证结束,并关闭认证通道 + authManager_->AuthenticateFinish(); +} +} +} 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..371376fde --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_log.h" +#include "dm_constants.h" +#include "dm_auth_manager.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_ = authManager; +} + +void AuthResponseState::SetLastState(std::shared_ptr state) +{ + lastState_ = state; +} + +void AuthResponseState::TransitionTo(std::shared_ptr state) +{ + state->SetAuthManager(authManager_); + state->SetLastState((std::shared_ptr)this); + state->SetAuthContext(context_); + this->Leave(); + state->Enter(); +} + +int32_t AuthResponseInitState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_INIT; +} + +void AuthResponseInitState::Enter() +{ + //1.认证通道建立后,进入该状态 +} + +int32_t AuthResponseNegotiateState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_NEGOTIATE; +} + +void AuthResponseNegotiateState::Enter() +{ + //1.收到协商消息后进入 + + //2. 获取本地加解密模块信息,并回复消息 +} + +int32_t AuthResponseConfirmState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_CONFIRM; +} + +void AuthResponseConfirmState::Enter() +{ + //委托授权UI模块进行用户交互 + //如果交互成功 + +// TransitionTo(new AuthResponseGroupState()); +} + +int32_t AuthResponseGroupState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_GROUP; +} + +void AuthResponseGroupState::Enter() +{ +// //1.创建群组, +// authManagerPtr_->GetHiChainConnector()->CreateGroup(); +} + +int32_t AuthResponseShowState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_SHOW; +} + +void AuthResponseShowState::Enter() +{ + //1.委托认证实现模块进行用户交互 + +} + +int32_t AuthResponseFinishState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_FINISH; +} + +void AuthResponseFinishState::Enter() +{ + //1.结束UI显示 + + //2.清理资源,结束状态机 +} +} +} diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index be569134c..2f56114dd 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -14,16 +14,22 @@ */ #include "dm_auth_manager.h" + +#include "nlohmann/json.hpp" + #include "dm_log.h" #include "dm_constants.h" +#include "auth_message_processor.h" namespace OHOS { namespace DistributedHardware { -DmAuthManager::DmAuthManager(std::shared_ptr softbusConnectorPtr, - std::shared_ptr listenerPtr) : softbusConnector_(softbusConnectorPtr), listenerPtr_(listenerPtr) +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(); } DmAuthManager::~DmAuthManager() @@ -33,6 +39,54 @@ DmAuthManager::~DmAuthManager() 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; + } + if (authRequestState_ != nullptr) { + LOGE("DmAuthManager::AuthenticateDevice %s is request authentication.", authRequestState_->GetAuthContext()->hostPkgName.c_str()); + return DM_AUTH_BUSINESS_BUSY; + } + if (authResponseState_ != nullptr) { + LOGE("DmAuthManager::AuthenticateDevice is response authentication."); + return DM_AUTH_BUSINESS_BUSY; + } + sessionSession_->RegisterSessionCallback(pkgName, std::shared_ptr(this)); + hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + + std::shared_ptr requestContext = std::make_shared(); + requestContext->authType = authType; + requestContext->deviceId = deviceId; + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (!jsonObject.is_discarded()) { + if (jsonObject.contains(TARGET_PKG_NAME_KEY)) { + requestContext->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY]; + } + if (jsonObject.contains(APP_NAME)) { + requestContext->appName = jsonObject[APP_NAME]; + } + if (jsonObject.contains(APP_DESC)) { + requestContext->appDesc = jsonObject[APP_DESC]; + } + if (jsonObject.contains(APP_THUMBNAIL)) { + requestContext->appThumbnail = jsonObject[APP_THUMBNAIL]; + } + if (jsonObject.contains(APP_ICON)) { + requestContext->appIcon = jsonObject[APP_ICON]; + } + } + authMessageProcessor_ = std::make_shared(std::shared_ptr(this)); + authRequestState_ = std::shared_ptr(new AuthRequestInitState()); + authRequestState_->SetAuthManager(std::shared_ptr(this)); + authRequestState_->SetAuthContext(requestContext); + authRequestState_->Enter(); + +// auto authenticateStartTimer = [this]() { +// HandleAuthenticateTimeout(); +// }; +// EventBus::PostTask(authenticateStartTimer, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT); return DM_OK; } @@ -43,8 +97,152 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) { + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT) { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); + } 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) { + authResponseState_ = std::shared_ptr(new AuthResponseInitState()); + authResponseState_->Enter(); + } else { + //TODO:RESP_AUTH 认证失败,流程终止 + } + } else { + if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); + } else { + LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType()); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } + } +} + +void DmAuthManager::OnSessionClosed(const std::string &pkgName, int32_t sessionId) +{ + +} + +void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message) +{ + int32_t ret = authMessageProcessor_->ParseMessage(message); + if (ret != DM_OK) { + LOGE("OnDataReceived, parse message error"); + return; + } + switch (authResponseContext_->msgType) { + case MSG_TYPE_NEGOTIATE: + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); + } else { + //状态错误,流程终止 + } + break; + case MSG_TYPE_REQ_AUTH: + //检查状态机状态 + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT || authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseConfirmState())); + } else { + //状态错误,流程终止 + } + break; + case MSG_TYPE_RESP_AUTH: + //根据响应结果 + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT || + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestReplyState())); + } else { + //状态错误,流程终止 + } + break; + case MSG_TYPE_RESP_NEGOTIATE: + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) { + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateDoneState())); + } else { + //状态错误,流程终止 + } + break; + default: + break; + } +} + +void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId) +{ + //创建群组成功 + //发送认证响应消息给请求端 + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); + softbusConnector_->GetSoftbusSession()->SendData(authRequestContext_->sessionId, message); +} + +void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) +{ +// if (authRequestState_->GetStateType() == AuthRequestJoinState) { +// authRequestState_->TransitionTo(new AuthRequestNetworkState()); +// } +} + +void DmAuthManager::HandleAuthenticateTimeout() { + //1. 状态机走到结束状态,并清理资源 +} + +void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) +{ + //TODO:检查crypto模块是否适配 + //TODO:兼容性处理,兼容与手机的认证 + int32_t ret = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + if (ret != DM_OK) { + LOGE("OpenAuthSession failed, stop the authentication"); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } +} + +void DmAuthManager::StartNegotiate(const int32_t &sessionId) +{ + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); + //TODO::设置消息等待超时时间 + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); +} + +void DmAuthManager::SendAuthRequest(const int32_t &sessionId) +{ + std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); + //TODO::设置消息等待超时时间 + for (auto msg : messageList) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + } +} + +void DmAuthManager::StartAuthProcess(const int32_t &authType) +{ + //1. 收到请求响应,判断用户响应结果 + //2. 用户授权同意 + //3. 回调给认证实现模块,启动认证 + std::shared_ptr authentication = authenticationMap_[authType]; + authentication->StartAuth(); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestInputState())); +} + +void DmAuthManager::JoinGroup(const std::string &deviceId) +{ +// hiChainConnector_->AddMember(deviceId); +} + +void DmAuthManager::JoinNetwork() +{ + //TODO: +} + +void DmAuthManager::AuthenticateFinish() +{ + //清理资源,关闭通道 + softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); } } +} \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/eventbus/event_bus.cpp b/services/devicemanagerservice/src/dependency/eventbus/event_bus.cpp new file mode 100644 index 000000000..1512d73ef --- /dev/null +++ b/services/devicemanagerservice/src/dependency/eventbus/event_bus.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_bus.h" + + +namespace OHOS { +namespace DistributedHardware { +EventBus *EventBus::instance_ = nullptr; +std::shared_ptr EventBus::eventBusHandler_ = nullptr; +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index d4900e5a9..2fe785688 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -32,22 +32,6 @@ 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 DM_PKG_NAME = "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; -// } - void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) { if (jsonObject.find(FIELD_GROUP_NAME) != jsonObject.end()) { @@ -71,6 +55,8 @@ void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) } } +std::map> HiChainConnector::hiChainConnectorCallbackMap_ = {}; + HiChainConnector::HiChainConnector() { LOGI("HiChainConnector::constructor"); @@ -96,11 +82,15 @@ HiChainConnector::~HiChainConnector() //TODO:delete resource } -void HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, const IHiChainConnectorCallback &callback) +int32_t HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, std::shared_ptr callback) { -// if (hichainConnectorCallback_.count(pkgName) == 0) { -// hichainConnectorCallback[pkgName] = 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) @@ -109,17 +99,14 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou 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; @@ -129,7 +116,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou 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("Faild to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); + LOGE("Failed to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); return DM_HICHAIN_GROUP_CREATE_FAILED; } return DM_OK; @@ -140,7 +127,6 @@ bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInf 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]; @@ -156,20 +142,17 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vectorgetGroupInfo(DM_PKG_NAME.c_str(), queryParams.c_str(), &groupVec, &num); if (ret != 0) { - LOGE("HiChainConnector::GetGroupInfo faild , ret: %d.", ret); + LOGE("HiChainConnector::GetGroupInfo failed , ret: %d.", ret); return false; } - if (groupVec == nullptr) { - LOGE("HiChainConnector::GetGroupInfo faild , returnGroups is 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); @@ -178,43 +161,41 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, 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::AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth) -//{ -// LOGI("HiChainConnector::AddMemeber"); -// if (deviceGroupManager_ == nullptr) { -// LOGI("HiChainConnector::AddMemeber group manager is null."); -// return -1; -// } -// -// char localDeviceId[DEVICE_UUID_LENGTH] = {0}; -// GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); +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; + } + + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); // std::string connectInfo = GetConnectPara(deviceId, msgResponseAuth); -// -// nlohmann::json jsonObj; + + nlohmann::json jsonObj; // jsonObj[FIELD_GROUP_ID] = msgResponseAuth->GetGroupId(); -// jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + 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_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(); -// -// LOGI("HiChainConnector::AddMemeber completed"); -// return deviceGroupManager_->addMemberToGroup(msgResponseAuth->GetRequestId(), DM_PKG_NAME.c_str(), -// tmpStr.c_str()); -//} + jsonObj[FIELD_CONNECT_PARAMS] = connectInfo.c_str(); + std::string tmpStr = jsonObj.dump(); + + LOGI("HiChainConnector::AddMember completed"); + return deviceGroupManager_->addMemberToGroup(0/*msgResponseAuth->GetRequestId()*/, DM_PKG_NAME.c_str(), + tmpStr.c_str()); +} void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) { @@ -225,11 +206,15 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const LOGI("HiChainConnector::onFinish reqId:%lld, operation:%d", requestId, operationCode); if (operationCode == GroupOperationCode::MEMBER_JOIN) { LOGI("Add Member To Group success"); - // HichainConnector::GetInstance().OnMemberJoin(requestId, SUCCESS); + for(auto & iter : hiChainConnectorCallbackMap_) { + iter.second->OnMemberJoin(requestId, DM_OK); + } } if (operationCode == GroupOperationCode::GROUP_CREATE) { LOGI("Create group success"); - // HichainConnector::GetInstance().OnGroupCreated(requestId, data); + for(auto & iter : hiChainConnectorCallbackMap_) { + iter.second->OnGroupCreated(requestId, data); + } } if (operationCode == GroupOperationCode::MEMBER_DELETE) { LOGI("Delete Member from group success"); @@ -245,14 +230,17 @@ void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t (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"); - // HichainConnector::GetInstance().OnMemberJoin(requestId, FAIL); + for(auto & iter : hiChainConnectorCallbackMap_) { + iter.second->OnMemberJoin(requestId, DM_FAILED); + } } if (operationCode == GroupOperationCode::GROUP_CREATE) { LOGE("Create group failed"); - // HichainConnector::GetInstance().OnGroupCreated(requestId, "{}"); + for(auto & iter : hiChainConnectorCallbackMap_) { + iter.second->OnGroupCreated(requestId, "{}"); + } } if (operationCode == GroupOperationCode::MEMBER_DELETE) { LOGE("Delete Member from group failed"); @@ -286,53 +274,6 @@ char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, cons return nullptr; } -// void HiChainConnector::RegisterConnectorCallback(std::shared_ptr callback) -// { -// HiChainConnectorCallback_ = callback; -// } - -// void HiChainConnector::OnGroupCreated(int64_t requestId, const std::string &returnData) -// { -// if (HiChainConnectorCallback_ == nullptr) { -// LOGE("HiChainConnector::OnGroupCreated HiChainConnectorCallback_ not registe."); -// return; -// } - -// nlohmann::json jsonObject = nlohmann::json::parse(returnData); -// if (jsonObject.is_discarded()) { -// LOGE("HiChainConnector::OnGroupCreated returnData not json."); -// HiChainConnectorCallback_->OnGroupCreated(requestId, ""); -// return; -// } - -// if (jsonObject.find(FIELD_GROUP_ID) == jsonObject.end()) { -// LOGE("HiChainConnector::OnGroupCreated failed to get groupId."); -// HiChainConnectorCallback_->OnGroupCreated(requestId, ""); -// return; -// } - -// std::string groupId = jsonObject.at(FIELD_GROUP_ID).get(); -// LOGI("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(); -// LOGI("HiChainConnector::OnMemberJoin:: role = %d", (int32_t)role); - -// if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { -// AuthManager::GetInstance().NotifyHostOnCheckAuthResult(requestId, status); -// return; -// } - -// if (HiChainConnectorCallback_ == nullptr) { -// LOGE("HiChainConnector::OnMemberJoin HiChainConnectorCallback_ not registe."); -// return; -// } -// HiChainConnectorCallback_->OnMemberJoin(requestId, status); -// } - int64_t HiChainConnector::GenRequestId() { return GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); @@ -382,24 +323,20 @@ void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vector groupInfos = jsonObject.get>(); if (groupInfos.size() == 0) { LOGE("HiChainConnector::GetRelatedGroups group failed, groupInfos is empty."); @@ -414,7 +351,6 @@ void HiChainConnector::GetSyncGroupList(std::vector &groupList, std:: LOGE("groupList is empty."); return; } - for (auto group : groupList) { if (IsGroupInfoInvalid(group)) { continue; @@ -440,7 +376,6 @@ void HiChainConnector::SyncGroups(std::string deviceId, std::vector if (IsGroupInfoInvalid(groupInfo)) { continue; } - auto iter = std::find(remoteGroupIdList.begin(), remoteGroupIdList.end(), groupInfo.groupId); if (iter == remoteGroupIdList.end()) { (void)DelMemberFromGroup(groupInfo.groupId, deviceId); @@ -457,14 +392,13 @@ int32_t HiChainConnector::DelMemberFromGroup(std::string groupId, std::string de 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 faild , ret: %d.", ret); + LOGE("HiChainConnector::DelMemberFromGroup failed , ret: %d.", ret); return ret; } - return 0; + return DM_OK; } void HiChainConnector::DeleteGroup(std::string &groupId) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 85ec37dc6..ea359cd57 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -29,6 +29,11 @@ namespace OHOS { namespace DistributedHardware { + +std::map> SoftbusConnector::discoveryDeviceInfoMap_ = {}; +std::map> SoftbusConnector::stateCallbackMap_ = {}; +std::map> SoftbusConnector::discoveryCallbackMap_ = {}; + SoftbusConnector::SoftbusConnector() { LOGI("SoftbusConnector constructor"); @@ -47,6 +52,7 @@ SoftbusConnector::SoftbusConnector() .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged }; + softbusSession_ = std::make_shared(); Init(); } @@ -82,23 +88,27 @@ int32_t SoftbusConnector::Init() return ret; } -int32_t SoftbusConnector::RegisterSoftbusDiscoveryCallback(const std::string &pkgName, const ISoftbusDiscoveryCallback &callback) +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 ISoftbusStateCallback &callback) +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; } @@ -150,11 +160,11 @@ int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) DmDeviceInfo *pInfo = &deviceInfo; if (memcpy_s(pInfo->deviceId, sizeof(pInfo->deviceId), nodeBasicInfo->networkId, std::min(sizeof(pInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { - LOGE("memcpy failed"); + LOGE("copy info failed"); } if (memcpy_s(pInfo->deviceName, sizeof(pInfo->deviceName), nodeBasicInfo->deviceName, std::min(sizeof(pInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { - LOGE("memcpy failed"); + LOGE("copy info failed"); } pInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; LOGD("SoftbusConnector::GetLocalDeviceInfo success"); @@ -216,33 +226,12 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &subscribeInfo) int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) { - // int32_t subscribeIdAdapter = -1; - // if (!GetsubscribeIdAdapter(pkgName, subscribeId, subscribeIdAdapter)) { - // LOGE("StopDiscovery failed, subscribeId not match"); - // return DEVICEMANAGER_FAILED; - // } - 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; } - - // 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); - // } LOGI("SoftbusConnector::StopDiscovery completed"); return DM_OK; } @@ -252,7 +241,7 @@ 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("DM_IsDeviceOnLine DM_GetSoftbusTrustDevices failed"); + LOGE("GetAllNodeDeviceInfo failed"); return false; } bool bDeviceOnline = false; @@ -285,110 +274,110 @@ bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) return bDeviceOnline; } -//int32_t SoftbusConnector::GetConnectionIpAddr(std::string deviceId, std::string &ipAddr) -//{ -// auto iter = discoverDeviceInfoMap_.find(deviceId); -// if (iter == discoverDeviceInfoMap_.end()) { -// LOGE("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) { -// LOGE("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; -// LOGI("DM_GetConnectionIpAddr get ip ok."); -// return DM_OK; -// } -// LOGE("failed to get ipAddr 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(std::string deviceId) -//{ -// auto iter = discoverDeviceInfoMap_.find(deviceId); -// if (iter == discoverDeviceInfoMap_.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; -// } -// -// ConnectionAddr *addr = nullptr; -// addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH); -// if (addr != nullptr) { -// LOGI("get ETH ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); -// return addr; -// } -// addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); -// if (addr != nullptr) { -// LOGI("get WLAN ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); -// return addr; -// } -// addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); -// if (addr != nullptr) { -// LOGI("get BLE ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); -// return addr; -// } -// addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); -// if (addr != nullptr) { -// LOGI("get BR ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); -// return addr; -// } -// LOGE("failed to get ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); -// return nullptr; -//} +std::shared_ptr SoftbusConnector::GetSoftbusSession() { + return softbusSession_; +} + +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) +{ + 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; + } + ConnectionAddr *addr = nullptr; + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH); + if (addr != nullptr) { + LOGI("get ETH ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + return addr; + } + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); + if (addr != nullptr) { + LOGI("get WLAN ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + return addr; + } + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); + if (addr != nullptr) { + LOGI("get BLE ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + return addr; + } + addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); + if (addr != nullptr) { + LOGI("get BR ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + return addr; + } + LOGE("failed to get ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + return nullptr; +} -void SoftbusConnector::NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo) +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("memcpy failed"); + 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("memcpy failed"); + LOGE("copy data failed"); } dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId; } -void SoftbusConnector::DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo) +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("memcpy failed"); + 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("memcpy failed"); + LOGE("copy data failed"); } dmDeviceInfo.deviceTypeId = deviceInfo.devType; } @@ -406,34 +395,38 @@ void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) { if (info == nullptr) { - LOGE("SoftbusConnector::OnSoftBusDeviceOnline NodeBasicInfo is nullptr"); + LOGE("SoftbusConnector::OnSoftbusDeviceOffline 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 != DM_OK) { - // LOGE("GetNodeKeyInfo failed"); - // return; - // } - // std::string deviceId = (char *)udid; - // LOGI("device online, deviceId: %s", GetAnonyString(deviceId).c_str()); - // RemoveDiscoveryDeviceInfo(deviceId); + 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("SoftbusConnector::OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); + LOGE("OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); return; } -// DmDeviceInfo dmDeviceInfo; -// NodeBasicInfoCopyToDmDevice(dmDeviceInfo, *info); - // IpcServerListenerAdapter::GetInstance().OnDeviceStateChange(DmDeviceState::DEVICE_STATE_OFFLINE, dmDeviceInfo); + DmDeviceInfo dmDeviceInfo; + CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); + for (auto & iter : stateCallbackMap_) { + iter.second->OnDeviceOffline(iter.first, dmDeviceInfo); + } } void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) @@ -450,51 +443,44 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) } std::string deviceId = device->devId; LOGI("SoftbusConnector::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(); -// LOGI("subscribe info capability:%s.", info->info.capability); -// if (strcmp(DM_CAPABILITY_OSD, info->info.capability) != 0) { -// LOGE("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); -// } -// } + 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() == 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); -// std::string pkgName; -// if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { -// LOGE("SoftbusConnector::OnSoftbusDiscoverFailed: pkgName not found"); -// return; -// } -// -// uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); - // IpcServerListenerAdapter::GetInstance().OnDiscoveryFailed(pkgName, originId, failReason); + uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & 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); -// std::string pkgName; -// if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { -// LOGE("OnSoftbusDiscoverySuccess: pkgName not found"); -// return; -// } -// uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); - // IpcServerListenerAdapter::GetInstance().OnDiscoverySuccess(pkgName, originId); + uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); + for (auto & iter : discoveryCallbackMap_) { + iter.second->OnDiscoverySuccess(iter.first, originId); + } } - } // 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 index 22dfafa1d..82454c306 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -14,6 +14,7 @@ */ #include "softbus_session.h" +#include "softbus_connector.h" #include "dm_constants.h" #include "dm_log.h" #include "dm_anonymous.h" @@ -22,7 +23,9 @@ namespace OHOS { namespace DistributedHardware { -SoftbusSession::SoftbusSession() : sessionIdSet_(), messages_() +std::map> SoftbusSession::sessionCallbackMap_ = {}; + +SoftbusSession::SoftbusSession() { ISessionListener sessionListener = { .OnSessionOpened = SoftbusSession::OnSessionOpened, @@ -42,31 +45,41 @@ SoftbusSession::~SoftbusSession() RemoveSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str()); } -int32_t SoftbusSession::OpenAuthSession(const char *deviceId) +int32_t SoftbusSession::RegisterSessionCallback(const std::string &pkgName, + std::shared_ptr callback) { - LOGE("open channel and start SendMsg"); - int32_t sessionId = -1; -// messages_ = message; -// ConnectionAddr *addrInfo = SoftbusAdapter::GetConnectAddr(deviceId); -// if (addrInfo == nullptr) { -// LOGE("GetConnectAddr error"); -// return sessionId; -// } + sessionCallbackMap_[pkgName] = callback; + return DM_OK; +} + +int32_t SoftbusSession::UnRegisterSessionCallback(const std::string &pkgName) +{ + sessionCallbackMap_.erase(pkgName); + return DM_OK; +} - sessionId = ::OpenAuthSession(DM_SESSION_NAME.c_str(), nullptr, 1, nullptr); +int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) +{ + LOGE("SoftbusSession::OpenAuthSession"); + int32_t sessionId = -1; + ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId); + 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; } - sessionIdSet_.insert(sessionId); - LOGI("opened auth session is:%d", sessionId); + LOGI("SoftbusSession::OpenAuthSession success. sessionId is:%d", sessionId); return sessionId; } void SoftbusSession::CloseAuthSession(int32_t sessionId) { - LOGI("CloseSession in"); - CloseSession(sessionId); + LOGI("SoftbusSession::CloseAuthSession"); + ::CloseSession(sessionId); } void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) @@ -79,19 +92,18 @@ void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) GetAnonyString(peerDevId).c_str()); return; } - LOGE("GetPeerDeviceId failed for session:%d", sessionId); peerDevId = ""; } int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) { - LOGE("start SendMsg"); -// uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MSG_MAX_SIZE + ENCRYPT_TAG_LEN)); -// if (buf == nullptr) { -// LOGE("SendMsg: malloc memory failed"); -// return DM_MALLOC_ERROR; -// } + LOGE("SendData Start"); + uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MESSAGE_MAX_SIZE + ENCRYPT_TAG_LEN)); + if (buf == nullptr) { + LOGE("SendData: malloc memory failed"); + return DM_MALLOC_ERROR; + } // int32_t outLen = 0; // int32_t ret = EncryptUtils::MbedtlsEncrypt((const uint8_t *)message.c_str(), message.size(), buf, MSG_MAX_SIZE, // &outLen); @@ -100,75 +112,40 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) // free(buf); // return ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; // } -// ret = SendData(sessionId, buf, outLen); -// free(buf); +// int32_t ret = SendBytes(sessionId, buf, strlen(buf)); + free(buf); return DM_OK; } -// int32_t SoftbusSession::SendData(int32_t sessionId, const void *data, int32_t len) -// { -// LOGI("in, datalen:%d", len); -// int32_t ret = DEVICEMANAGER_FAILED; -// if (sessionIdSet_.count(sessionId) > 0) { -// ret = SendBytes(sessionId, data, len); -// if (ret != DM_OK) { -// return DEVICEMANAGER_FAILED; -// } -// } else { -// LOGI("in, datalen:%d", len); -// } -// return ret; -// } - int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) { -// if (result != DM_OK) { -// LOGI("session open failed, sessionId %d", sessionId); -// if (sessionIdSet_.count(sessionId) > 0) { -// sessionIdSet_.erase(sessionId); -// messages_.clear(); -// } -// return DM_OK; -// } -// -// int32_t sessionSide = GetSessionSide(sessionId); -// LOGI("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 != DM_OK) { -// LOGI("send message failed"); -// return ret; -// } -// } -// } else { -// sessionIdSet_.insert(sessionId); -// } + int32_t sessionSide = GetSessionSide(sessionId); + for (auto & iter : sessionCallbackMap_) { + iter.second->OnSessionOpened(iter.first, sessionId, sessionSide, result); + } return DM_OK; } void SoftbusSession::OnSessionClosed(int32_t sessionId) { LOGI("OnSessionClosed, sessionId:%d", sessionId); -// if (sessionIdSet_.count(sessionId) > 0) { -// sessionIdSet_.erase(sessionId); -// } + for (auto & iter : sessionCallbackMap_) { + iter.second->OnSessionClosed(iter.first, 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; -// } -// -// uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); -// if (buf == nullptr) { -// LOGE("SendMsg: malloc memory failed"); -// return; -// } -// + if (sessionId < 0 || data == nullptr || dataLen <= 0) { + LOGI("OnBytesReceived param check failed"); + return; + } + uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); + if (buf == nullptr) { + LOGE("SendMsg: malloc memory failed"); + return; + } // int32_t outLen = 0; // int32_t ret = EncryptUtils::MbedtlsDecrypt((const uint8_t*)data, dataLen, buf, dataLen, &outLen); // if (ret != DM_OK || outLen > (int32_t)dataLen) { @@ -176,11 +153,12 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 // free(buf); // return; // } -// -// std::string message = (char *)buf; -// AuthManager::GetInstance().OnReceiveMsg(sessionId, message); -// free(buf); -// LOGI("OnBytesReceived completed"); + std::string message = (char *)buf; + for (auto & iter : sessionCallbackMap_) { + iter.second->OnDataReceived(iter.first, sessionId, message); + } + free(buf); + LOGI("OnBytesReceived completed"); } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index a4025b7ac..710d8ec5a 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -31,50 +31,50 @@ int32_t DeviceManagerService::Init() return DM_INT_MULTIPLE; } - if (softbusConnectorPtr_ == nullptr) { - softbusConnectorPtr_ = std::make_shared(); - if (softbusConnectorPtr_ == nullptr) { - LOGE("Init failed, softbusConnectorPtr_ apply for failure"); + if (softbusConnector_ == nullptr) { + softbusConnector_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, softbusConnector_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } - if (listenerPtr_ == nullptr) { - listenerPtr_ = std::make_shared(); - if (softbusConnectorPtr_ == nullptr) { - LOGE("Init failed, listenerPtr_ apply for failure"); + if (listener_ == nullptr) { + listener_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, listener_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } - if (deviceInfoMgrPtr_ == nullptr) { - deviceInfoMgrPtr_ = std::make_shared(softbusConnectorPtr_); - if (deviceInfoMgrPtr_ == nullptr) { - LOGE("Init failed, deviceInfoMgrPtr_ apply for failure"); + if (deviceInfoMgr_ == nullptr) { + deviceInfoMgr_ = std::make_shared(softbusConnector_); + if (deviceInfoMgr_ == nullptr) { + LOGE("Init failed, deviceInfoMgr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } - if (deviceStateMgrPtr_ == nullptr) { - deviceStateMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); - if (deviceStateMgrPtr_ == nullptr) { - LOGE("Init failed, deviceStateMgrPtr_ apply for failure"); + if (deviceStateMgr_ == nullptr) { + deviceStateMgr_ = std::make_shared(softbusConnector_, listener_); + if (deviceStateMgr_ == nullptr) { + LOGE("Init failed, deviceStateMgr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } - if (discoveryMgrPtr_ == nullptr) { - discoveryMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); - if (discoveryMgrPtr_ == nullptr) { - LOGE("Init failed, discoveryMgrPtr_ apply for failure"); + 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(authMgrPtr_ == nullptr) { - authMgrPtr_ = std::make_shared(softbusConnectorPtr_, listenerPtr_); - if (authMgrPtr_ == nullptr) { - LOGE("Init failed, authMgrPtr_ apply for failure"); + if(authMgr_ == nullptr) { + authMgr_ = std::make_shared(softbusConnector_, listener_); + if (authMgr_ == nullptr) { + LOGE("Init failed, authMgr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } @@ -95,7 +95,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c LOGE("GetTrustedDeviceList failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - return deviceInfoMgrPtr_->GetTrustedDeviceList(pkgName, extra, deviceList); + return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); } int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) @@ -105,7 +105,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) return DM_NOT_INIT; } - return deviceInfoMgrPtr_->GetLocalDeviceInfo(info); + return deviceInfoMgr_->GetLocalDeviceInfo(info); } int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) @@ -119,7 +119,7 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - return discoveryMgrPtr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); } int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) @@ -133,7 +133,7 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui LOGE("StopDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - return discoveryMgrPtr_->StopDeviceDiscovery(pkgName, subscribeId); + return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); } int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) @@ -152,7 +152,7 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int LOGE("AuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - return authMgrPtr_->AuthenticateDevice(pkgName, authType, deviceId, extra); + return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) @@ -170,7 +170,7 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c LOGE("UnAuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - return authMgrPtr_->UnAuthenticateDevice(pkgName, deviceId); + return authMgr_->UnAuthenticateDevice(pkgName, deviceId); } int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) @@ -185,7 +185,7 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c return DM_INPUT_PARA_EMPTY; } - return authMgrPtr_->VerifyAuthentication(pkgName, authParam); + return authMgr_->VerifyAuthentication(pkgName, authParam); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index d1b3938e2..a05c91b6c 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -30,7 +30,7 @@ namespace OHOS { namespace DistributedHardware { -void DeviceManagerServiceListener::OnDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info) +void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) { LOGI("OnDeviceStateChange"); std::shared_ptr pReq = std::make_shared(); diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index c4801010f..88777f8c2 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -20,27 +20,27 @@ namespace OHOS { namespace DistributedHardware { -DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr& softbusConnectorPtr) : softbusConnectorPtr_(softbusConnectorPtr) +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 = softbusConnectorPtr_->GetTrustedDeviceList(deviceList); + int32_t ret = softbusConnector_->GetTrustedDeviceList(deviceList); if (ret != DM_OK) { LOGE("GetTrustedDeviceList failed"); return ret; } if (!extra.empty() && !deviceList.empty()) { - adapterMgrPtr_ = std::make_shared(); - if (adapterMgrPtr_ == nullptr) { - LOGE("GetTrustedDeviceList adapterMgrPtr_ is nullptr"); + adapterMgr_ = std::make_shared(); + if (adapterMgr_ == nullptr) { + LOGE("GetTrustedDeviceList adapterMgr_ is nullptr"); return DM_POINT_NULL; } -// IDecisionAdapter decisionAdapter = adapterMgrPtr_->GetDecisionAdapter(); +// IDecisionAdapter decisionAdapter = adapterMgr_->GetDecisionAdapter(); // if (decisionAdapter != nullptr) { // decisionAdapter->FilterDeviceList(deviceList, extra); // } else { @@ -54,7 +54,7 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info) { - int32_t ret = softbusConnectorPtr_->GetLocalDeviceInfo(info); + int32_t ret = softbusConnector_->GetLocalDeviceInfo(info); if (ret != DM_OK) { LOGE("GetLocalDeviceInfo failed"); return ret; diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 80a6b11d7..f1adebc42 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -20,16 +20,33 @@ namespace OHOS { namespace DistributedHardware { -DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnectorPtr, - std::shared_ptr listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) +DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnector, + std::shared_ptr listener) : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmDeviceStateManager constructor"); + softbusConnector_->RegisterSoftbusStateCallback("", std::shared_ptr(this)); } DmDeviceStateManager::~DmDeviceStateManager() { LOGI("DmDeviceStateManager destructor"); + softbusConnector_->UnRegisterSoftbusStateCallback(""); } +void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) { + +} + +void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) { + +} + +void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) { + +} + +void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info) { + +} } } diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 946bb4d49..de0b33572 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -16,12 +16,13 @@ #include "dm_discovery_manager.h" #include "dm_log.h" #include "dm_constants.h" +#include "dm_anonymous.h" namespace OHOS { namespace DistributedHardware { -DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnectorPtr, - std::shared_ptr listenerPtr) : softbusConnectorPtr_(softbusConnectorPtr), listenerPtr_(listenerPtr) +DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnector, + std::shared_ptr listener) : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmDiscoveryManager constructor"); } @@ -33,17 +34,54 @@ DmDiscoveryManager::~DmDiscoveryManager() int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { - //TODO:prevent reentration - //TODO:save extra for later filter the found device - return softbusConnectorPtr_->StartDiscovery(subscribeInfo); + 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); + softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); + } + } + DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId}; + discoveryContextMap_.emplace(pkgName, context); + softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(this)); +// auto discoveryTimer = [this]() { +// HandleDiscoveryTimeout(); +// }; +// EventBus::PostTask(discoveryTimer, DISCOVERY_TIMEOUT_TASK, DISCOVERY_TIMEOUT); + return softbusConnector_->StartDiscovery(subscribeInfo); } int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - //TODO:stop discovery and remove queue - softbusConnectorPtr_->UnRegisterSoftbusDiscoveryCallback(pkgName); - return softbusConnectorPtr_->StopDiscovery(subscribeId); + discoveryContextMap_.erase(pkgName); + softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); + return softbusConnector_->StopDiscovery(subscribeId); } +void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) { + LOGI("DmDiscoveryManager::OnDeviceFound deviceId=%s", GetAnonyString(info.deviceId).c_str()); +// std::string pkgName = discoveryQueue_.front(); + //TODO:获取Extra信息判断是否进行筛选,完成后上报设备信息 +// listener_->OnDeviceFound(pkgName, subscribeId, info); +} + +void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) { + LOGI("DmDiscoveryManager::OnDiscoveryFailed subscribeId=%d reason=%d", subscribeId, failedReason); +// std::string pkgName = discoveryQueue_.front(); + StopDeviceDiscovery(pkgName, subscribeId); +} + +void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) { + LOGI("DmDiscoveryManager::OnDiscoverySuccess subscribeId=%d", subscribeId); +// std::string pkgName = discoveryQueue_.front(); + discoveryContextMap_[pkgName].subscribeId = subscribeId; +} + +void DmDiscoveryManager::HandleDiscoveryTimeout() { + LOGI("DmDiscoveryManager::HandleDiscoveryTimeout"); +} } } diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 86987ca90..87648c2d6 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -65,7 +65,7 @@ if (defined(ohos_lite)) { # "//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/bounds_checking_function:libsec_shared", "//third_party/mbedtls:mbedtls_shared", "//utils/native/lite:utils", ] @@ -92,7 +92,10 @@ if (defined(ohos_lite)) { "src/ipc/standard/ipc_cmd_register.cpp", ] - deps = [ "//utils/native/base:utils" ] + deps = [ + "//utils/native/base:utils", + "//third_party/mbedtls:mbedtls_shared", + ] defines = [ "HI_LOG_ENABLE", @@ -101,15 +104,8 @@ 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", + "ipc:ipc_core" ] subsystem_name = "distributedhardware" diff --git a/utils/src/dm_random.cpp b/utils/src/dm_random.cpp index 5c05af675..52f264d30 100644 --- a/utils/src/dm_random.cpp +++ b/utils/src/dm_random.cpp @@ -17,6 +17,15 @@ #include +#include "mbedtls/base64.h" +#include "mbedtls/gcm.h" +#include "mbedtls/md.h" + +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" + +#include "dm_constants.h" + namespace OHOS { namespace DistributedHardware { int32_t GenRandInt(int32_t randMin, int32_t randMax) @@ -34,5 +43,73 @@ int64_t GenRandLongLong(int64_t randMin, int64_t randMax) 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 5c3d37d51ac9c38d33fd5999ed858ddf6ce33df9 Mon Sep 17 00:00:00 2001 From: puhui Date: Wed, 8 Dec 2021 20:57:41 +0800 Subject: [PATCH 026/110] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E9=80=82=E9=85=8D?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/include/dm_constants.h | 13 ++++--- services/devicemanagerservice/BUILD.gn | 2 +- .../include/adapter/dm_adapter_manager.h | 2 +- .../include/authentication/dm_auth_manager.h | 36 ------------------- .../{ipc => lite}/dm_adapter_manager.cpp | 6 ++++ .../adapter/standard/dm_adapter_manager.cpp | 5 +++ .../authentication/auth_message_processor.cpp | 8 ++--- .../src/authentication/dm_auth_manager.cpp | 12 +++---- .../dependency/softbus/softbus_connector.cpp | 6 ++-- .../dependency/softbus/softbus_session.cpp | 2 +- 10 files changed, 36 insertions(+), 56 deletions(-) rename services/devicemanagerservice/src/adapter/{ipc => lite}/dm_adapter_manager.cpp (91%) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 2800361b8..5d0573c4a 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -21,8 +21,6 @@ namespace OHOS { namespace DistributedHardware { - const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; - const std::string HOST_PKG_NAME_KEY = "hostPackageName"; const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; @@ -75,6 +73,8 @@ namespace DistributedHardware { 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"; @@ -96,10 +96,13 @@ namespace DistributedHardware { 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"; + 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"; @@ -108,6 +111,8 @@ namespace DistributedHardware { const std::string APP_THUMBNAIL_LEN = "appThumbnailLen"; const std::string APP_THUMBNAIL = "appThumbnail"; const int32_t MSG_MAX_SIZE = 45 * 1024; + const int32_t AUTH_REPLY_ACCEPT = 0; + const int32_t ENCRYPT_TAG_LEN = 32; //json const std::string AUTH_TYPE = "authType"; const std::string TOKEN = "token"; diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 693041bde..443706e46 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -63,7 +63,7 @@ if (defined(ohos_lite)) { sources = [ "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", - "src/adapter/dm_adapter_manager.cpp", + "src/adapter/lite/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", "src/authentication/auth_message_processor.cpp", "src/authentication/auth_request_state.cpp", diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index c53a39169..8c0813ddc 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -32,7 +32,7 @@ public: std::shared_ptr GetProfileAdapter(); std::shared_ptr GetCryptoAdapter(); private: - DmAdapterManager() = default; + DmAdapterManager(); ~DmAdapterManager(); DmAdapterManager(const DmAdapterManager&) = delete; DmAdapterManager& operator= (const DmAdapterManager&) = delete; diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index a49c0971d..3785ab305 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -33,42 +33,6 @@ namespace OHOS { namespace DistributedHardware { -const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; -const std::string HOST_PKG_NAME_KEY = "hostPackageName"; -const std::string APP_NAME = "appName"; -const std::string APP_DESC = "appDescription"; -const std::string APP_ICON = "appIcon"; -const std::string APP_THUMBNAIL = "appThumbnail"; -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_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 AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; const int32_t AUTHENTICATE_TIMEOUT = 120; diff --git a/services/devicemanagerservice/src/adapter/ipc/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp similarity index 91% rename from services/devicemanagerservice/src/adapter/ipc/dm_adapter_manager.cpp rename to services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp index 881a3d181..592176348 100644 --- a/services/devicemanagerservice/src/adapter/ipc/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace DistributedHardware { +DmAdapterManager& DmAdapterManager::GetInstance() +{ + static DmAdapterManager instance; + return instance; +} + DmAdapterManager::DmAdapterManager() { LOGI("DmAdapterManager constructor"); diff --git a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp index cdbb332be..fede2d727 100644 --- a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp @@ -27,6 +27,11 @@ DmAdapterManager& DmAdapterManager::GetInstance() return instance; } +DmAdapterManager::DmAdapterManager() +{ + LOGI("DmAdapterManager constructor"); +} + DmAdapterManager::~DmAdapterManager() { void *so_handle = nullptr; diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index 018419456..b39b809c1 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -33,7 +33,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() std::vector jsonStrVec; int32_t thumbnailSize = authRequestContext_->appThumbnail.size(); int32_t thumbnailSlice = - ((thumbnailSize / MESSAGE_MAX_SIZE) + (thumbnailSize % MESSAGE_MAX_SIZE) == 0 ? 0 : 1); + ((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; @@ -64,11 +64,11 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() jsonThumbnailObj[TAG_DEVICE_ID] = authRequestContext_->deviceId; jsonThumbnailObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; - int32_t leftLen = thumbnailSize - idx * MESSAGE_MAX_SIZE; - int32_t sliceLen = (leftLen > MESSAGE_MAX_SIZE) ? MESSAGE_MAX_SIZE : leftLen; + 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 * MESSAGE_MAX_SIZE, sliceLen); + jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); jsonStrVec.push_back(jsonThumbnailObj.dump()); } return jsonStrVec; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 2f56114dd..58cec854d 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -64,17 +64,17 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au if (jsonObject.contains(TARGET_PKG_NAME_KEY)) { requestContext->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY]; } - if (jsonObject.contains(APP_NAME)) { - requestContext->appName = jsonObject[APP_NAME]; + if (jsonObject.contains(APP_NAME_KEY)) { + requestContext->appName = jsonObject[APP_NAME_KEY]; } - if (jsonObject.contains(APP_DESC)) { - requestContext->appDesc = jsonObject[APP_DESC]; + if (jsonObject.contains(APP_DESCRIPTION_KEY)) { + requestContext->appDesc = jsonObject[APP_DESCRIPTION_KEY]; } if (jsonObject.contains(APP_THUMBNAIL)) { requestContext->appThumbnail = jsonObject[APP_THUMBNAIL]; } - if (jsonObject.contains(APP_ICON)) { - requestContext->appIcon = jsonObject[APP_ICON]; + if (jsonObject.contains(APP_ICON_KEY)) { + requestContext->appIcon = jsonObject[APP_ICON_KEY]; } } authMessageProcessor_ = std::make_shared(std::shared_ptr(this)); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index ea359cd57..b83ce9042 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -454,7 +454,7 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) } discoveryDeviceInfoMap_[deviceId] = infoPtr; // Remove the earliest element when reached the max size - if (discoveryDeviceInfoMap_.size() == DISCOVER_DEVICE_INFO_MAX_SIZE) { + if (discoveryDeviceInfoMap_.size() == SOFTBUS_DISCOVER_DEVICE_INFO_MAX_SIZE) { auto iter = discoveryDeviceInfoMap_.begin(); discoveryDeviceInfoMap_.erase(iter->second->devId); } @@ -468,7 +468,7 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) 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) & SUBSCRIBE_ID_MASK); + 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); } @@ -477,7 +477,7 @@ void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFa void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) { LOGI("In, subscribeId %d", subscribeId); - uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); + uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); for (auto & iter : discoveryCallbackMap_) { iter.second->OnDiscoverySuccess(iter.first, originId); } diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 82454c306..45ca18143 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -99,7 +99,7 @@ void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) { LOGE("SendData Start"); - uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MESSAGE_MAX_SIZE + ENCRYPT_TAG_LEN)); + uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MSG_MAX_SIZE + ENCRYPT_TAG_LEN)); if (buf == nullptr) { LOGE("SendData: malloc memory failed"); return DM_MALLOC_ERROR; -- Gitee From 862ebefc646682a57d46f0fdbd1f8db5009fbbff Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Thu, 9 Dec 2021 15:37:31 +0800 Subject: [PATCH 027/110] discovery and two other part --- .../include/device_manager_service_listener.h | 2 +- .../dependency/softbus/softbus_connector.cpp | 96 ++++++++----------- .../src/device_manager_service_listener.cpp | 4 +- .../devicestate/dm_device_state_manager.cpp | 22 ++++- .../src/discovery/dm_discovery_manager.cpp | 20 +++- 5 files changed, 79 insertions(+), 65 deletions(-) diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index 3192895c5..8851ed98b 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -27,7 +27,7 @@ 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, const std::string &failedReason); + 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); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index b83ce9042..57db8f480 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -115,36 +115,28 @@ int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgN int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceInfoList) { LOGD("SoftbusConnector::GetTrustDevices start"); -// NodeBasicInfo **nodeInfo = nullptr; -// int32_t *infoNum = 0; -// 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; -// if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, -// std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { -// LOGE("memcpy failed"); -// } -// if (memcpy_s(deviceInfo->deviceName, sizeof(deviceInfo->deviceName), nodeBasicInfo->deviceName, -// std::min(sizeof(deviceInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { -// LOGE("memcpy failed"); -// } -// deviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; -// deviceInfoList.push_back(*deviceInfo); -// } -// FreeNodeInfo(nodeInfo); -// free(info); -// LOGD("SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); + NodeBasicInfo *nodeInfo = nullptr; + int32_t *infoNum = 0; + 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; } @@ -157,32 +149,24 @@ int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) LOGE("GetLocalNodeDeviceInfo failed with ret %d", ret); return DM_FAILED; } - DmDeviceInfo *pInfo = &deviceInfo; - if (memcpy_s(pInfo->deviceId, sizeof(pInfo->deviceId), nodeBasicInfo->networkId, - std::min(sizeof(pInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { - LOGE("copy info failed"); - } - if (memcpy_s(pInfo->deviceName, sizeof(pInfo->deviceName), nodeBasicInfo->deviceName, - std::min(sizeof(pInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { - LOGE("copy info failed"); - } - pInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; + // DmDeviceInfo *pInfo = &deviceInfo; + CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, deviceInfo); LOGD("SoftbusConnector::GetLocalDeviceInfo success"); return DM_OK; } -int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &subscribeInfo) +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; + 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; //TODO:check these later // std::shared_ptr subinfo = nullptr; @@ -216,11 +200,11 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &subscribeInfo) // LOGD("StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", // pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); // LOGD("Capability: %s", subinfo->info.capability); -// 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; -// } + 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; } diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index a05c91b6c..26ce7cb6f 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -54,7 +54,7 @@ void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uin ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } -void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, const std::string &failedReason) +void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) { LOGI("OnDiscoveryFailed"); std::shared_ptr pReq = std::make_shared(); @@ -62,7 +62,7 @@ void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, pReq->SetPkgName(pkgName); pReq->SetSubscribeId(subscribeId); -// pReq->SetResult(failReason); + pReq->SetResult(failedReason); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index f1adebc42..eeaf56d63 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -16,7 +16,7 @@ #include "dm_device_state_manager.h" #include "dm_log.h" #include "dm_constants.h" - +#include "dm_adapter_manager.h" namespace OHOS { namespace DistributedHardware { @@ -34,11 +34,27 @@ DmDeviceStateManager::~DmDeviceStateManager() } void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) { - + DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); + if (profileAdapter == nullptr){ + LOGE("OnDeviceOnline profile adapter is null"); + return; + } + DmDeviceState state = DEVICE_STATE_ONLINE; + // profileAdapter->RegisterProfileListener(); + listener_->OnDeviceStateChange(pkgName, state, info); } void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) { - + DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); + if (profileAdapter == nullptr){ + LOGE("OnDeviceOnline profile adapter is null"); + return; + } + DmDeviceState state = DEVICE_STATE_OFFLINE; + // profileAdapter->UnRegisterProfileListener(); + listener_->OnDeviceStateChange(pkgName, state, info); } void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) { diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index de0b33572..e25d41567 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -44,6 +44,7 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); } } + discoveryQueue_.push(pkgName); DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId}; discoveryContextMap_.emplace(pkgName, context); softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(this)); @@ -56,6 +57,7 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { + discoveryQueue_.pop(); discoveryContextMap_.erase(pkgName); softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); return softbusConnector_->StopDiscovery(subscribeId); @@ -63,25 +65,37 @@ int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) { LOGI("DmDiscoveryManager::OnDeviceFound deviceId=%s", GetAnonyString(info.deviceId).c_str()); -// std::string pkgName = discoveryQueue_.front(); + // std::string pkgName = discoveryQueue_.front(); + auto iter = discoveryContextMap_.find(pkgName); + if (iter == discoveryContextMap_.end()) { + LOGE("subscribeId not found by pkgName %s", GetAnonyString(pkgName).c_str()); + return; + } //TODO:获取Extra信息判断是否进行筛选,完成后上报设备信息 -// listener_->OnDeviceFound(pkgName, subscribeId, info); + 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); -// std::string pkgName = discoveryQueue_.front(); + // std::string pkgName = discoveryQueue_.front(); + discoveryQueue_.pop(); + discoveryContextMap_.erase(pkgName); + softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); StopDeviceDiscovery(pkgName, subscribeId); + listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); } void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) { LOGI("DmDiscoveryManager::OnDiscoverySuccess subscribeId=%d", subscribeId); // std::string pkgName = discoveryQueue_.front(); discoveryContextMap_[pkgName].subscribeId = subscribeId; + listener_->OnDiscoverySuccess(pkgName, subscribeId); } void DmDiscoveryManager::HandleDiscoveryTimeout() { LOGI("DmDiscoveryManager::HandleDiscoveryTimeout"); + StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); + softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); } } } -- Gitee From 5d9ffe609503dc21cd636e3e4d3d58bcd63448af Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Fri, 10 Dec 2021 10:03:41 +0800 Subject: [PATCH 028/110] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E9=80=9A?= =?UTF-8?q?=E8=BF=87=E7=B3=BB=E7=BB=9F=E5=8F=82=E6=95=B0=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E5=BC=80=E5=90=AF=E6=88=96=E5=85=B3=E9=97=AD=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E5=8F=91=E7=8E=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 4 ++ services/devicemanagerservice/BUILD.gn | 2 + .../dependency/softbus/softbus_connector.cpp | 59 +++++++++++++++---- 3 files changed, 55 insertions(+), 10 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 5d0573c4a..aad58d03f 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -23,6 +23,9 @@ namespace OHOS { namespace DistributedHardware { const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; const std::string DM_SESSION_NAME = "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 DS_SO_NAME = "libdevicemanagerservice_ds_adapter.z.so"; const std::string DP_SO_NAME = "libdevicemanagerservice_dp_adapter.z.so"; @@ -36,6 +39,7 @@ namespace DistributedHardware { 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 TOKEN_LEN = 9; enum { diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 443706e46..4d61022aa 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -127,6 +127,7 @@ if (defined(ohos_lite)) { "//utils/native/base/include", "//utils/system/safwk/native/include", "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/interfaces/kits", "//base/startup/syspara_lite/adapter/native/syspara/include", "//third_party/json/include", ] @@ -178,6 +179,7 @@ if (defined(ohos_lite)) { "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "startup_l2:syspara", + "startup_l2:syspara_watchagent", ] subsystem_name = "distributedhardware" diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 57db8f480..89049a580 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -20,6 +20,7 @@ #include #include +#include "parameter.h" #include "system_ability_definition.h" #include "dm_log.h" @@ -30,6 +31,31 @@ namespace OHOS { namespace DistributedHardware { +IPublishCallback PublishCallback = { + .OnPublishSuccess = SoftbusConnector::OnPublishSuccess, + .OnPublishFail = SoftbusConnector::OnPublishFail +}; + +void ParameterChgCallback(const char *key, const char *value, void *context) +{ + int32_t ret; + if (strcmp(value, DISCOVER_STATUS_ON.c_str()) == 0) { + 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 = nullptr; + dmPublishInfo.capabilityData = nullptr; + dmPublishInfo.dataLen = 0; + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &PublishCallback); + LOGI("service publish result is : %d", ret); + } else if (strcmp(value, DISCOVER_STATUS_OFF.c_str()) == 0) { + ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + LOGI("service unpublish result is : %d", ret); + } +} + std::map> SoftbusConnector::discoveryDeviceInfoMap_ = {}; std::map> SoftbusConnector::stateCallbackMap_ = {}; std::map> SoftbusConnector::discoveryCallbackMap_ = {}; @@ -74,17 +100,30 @@ int32_t SoftbusConnector::Init() } } while (ret != DM_OK); LOGI("RegNodeDeviceStateCb success."); + //TODO:check system properties first - PublishInfo publishInfo; - publishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; - publishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; - publishInfo.medium = ExchanageMedium::AUTO; - publishInfo.freq = ExchangeFreq::HIGH; - publishInfo.capability = nullptr; - publishInfo.capabilityData = nullptr; - publishInfo.dataLen = 0; - ret = PublishService(DM_PKG_NAME.c_str(), &publishInfo, &softbusPublishCallback_); - LOGI("service publish result is : %d", ret); + 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_OFF.c_str()); + } else if (ret >= 0 && strcmp(discoverStatus, DISCOVER_STATUS_ON.c_str()) == 0) { + 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 = CAPABILITY_OSD.c_str(); + dmPublishInfo.capabilityData = nullptr; + dmPublishInfo.dataLen = 0; + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); + 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); + LOGI("service unpublish result is : %d", ret); + } + + ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), ParameterChgCallback, nullptr); + LOGI("register Watch Parameter result is : %d"); return ret; } -- Gitee From a55360a893fd942578f2949bb95a7cbe9a1bb9c1 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Mon, 13 Dec 2021 19:08:34 +0800 Subject: [PATCH 029/110] discovery and get local device info --- common/include/dm_constants.h | 4 +++- .../native_cpp/include/device_manager.h | 2 +- .../native_cpp/include/device_manager_impl.h | 2 +- .../native_cpp/src/device_manager_impl.cpp | 7 +++--- .../src/ipc/standard/ipc_cmd_parser.cpp | 24 ++++++++++++++++++- .../kits/js/src/native_devicemanager_js.cpp | 20 ++++++++-------- .../dependency/softbus/softbus_connector.cpp | 10 ++++---- .../src/discovery/dm_discovery_manager.cpp | 8 +++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 17 +++++++++++++ 9 files changed, 67 insertions(+), 27 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index aad58d03f..e8eed261c 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -34,6 +34,8 @@ namespace DistributedHardware { const std::string CREATE_IPROFILE = "CreateIProfileAdapter"; const std::string CREATE_ICRYPTO = "CreateICryptoAdapterFuncPtr"; + 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; @@ -126,13 +128,13 @@ namespace DistributedHardware { const int32_t DEFAULT_PIN_CODE = 0; const int32_t DEFAULT_PIN_TOKEN = 0; //Softbus - const std::string CAPABILITY_OSD = "osdCapability"; 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; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 6f5cf498e..cebaffb65 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -33,7 +33,7 @@ public: 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(DmDeviceInfo &deviceInfo) = 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; 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 a718f44f2..f7d488d26 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -31,7 +31,7 @@ public: 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(DmDeviceInfo &deviceInfo) 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; 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 92d77eea1..6cc2428cf 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -106,11 +106,12 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons return DM_OK; } -int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &info) +int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) { - LOGI("DeviceManager::GetLocalDeviceInfo start"); + LOGI("DeviceManager::GetLocalDeviceInfo start, pkgName: %s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); int32_t ret = ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp); if (ret != DM_OK) { LOGE("GetLocalDeviceInfo error: Send Request failed ret: %d", ret); @@ -124,7 +125,7 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(DmDeviceInfo &info) } info = rsp->GetLocalDeviceInfo(); - LOGI("GetLocalDeviceInfo completed"); + LOGI("GetLocalDeviceInfo completed,pkgname%s",req->GetPkgName().c_str()); return DM_OK; } 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 befc00671..09cd78b2c 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 @@ -29,7 +29,7 @@ #include "ipc_get_trustdevice_rsp.h" #include "ipc_authenticate_device_req.h" #include "ipc_verify_authenticate_req.h" - +#include "ipc_get_local_device_info_rsp.h" namespace OHOS { namespace DistributedHardware { ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, MessageParcel &data) @@ -109,6 +109,28 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, MessageParcel &reply, std::shared_pt 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(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 833f4acbe..5df4ee9b2 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -506,9 +506,9 @@ int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_v int32_t capability = -1; JsObjectToInt(env, object, "capability", capability); -// if (capability == DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_NAPI_SUBSCRIBE_CAPABILITY_OSD) { -// (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); -// } + if (capability == DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_NAPI_SUBSCRIBE_CAPABILITY_OSD) { + (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); + } return 0; } @@ -1003,17 +1003,17 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback { LOGI("GetLocalDeviceInfoSync in"); napi_value result = nullptr; - // napi_value thisVar = 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; + 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(deviceInfo); + 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; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 89049a580..d041d4924 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -45,7 +45,7 @@ void ParameterChgCallback(const char *key, const char *value, void *context) dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; dmPublishInfo.medium = ExchanageMedium::AUTO; dmPublishInfo.freq = ExchangeFreq::HIGH; - dmPublishInfo.capability = nullptr; + dmPublishInfo.capability = DM_CAPABILITY_OSD; dmPublishInfo.capabilityData = nullptr; dmPublishInfo.dataLen = 0; ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &PublishCallback); @@ -112,7 +112,7 @@ int32_t SoftbusConnector::Init() dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; dmPublishInfo.medium = ExchanageMedium::AUTO; dmPublishInfo.freq = ExchangeFreq::HIGH; - dmPublishInfo.capability = CAPABILITY_OSD.c_str(); + dmPublishInfo.capability = DM_CAPABILITY_OSD; dmPublishInfo.capabilityData = nullptr; dmPublishInfo.dataLen = 0; ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); @@ -182,14 +182,14 @@ int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceI int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) { LOGD("SoftbusConnector::GetLocalDeviceInfo start"); - NodeBasicInfo *nodeBasicInfo = nullptr; - int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), nodeBasicInfo); + 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; } // DmDeviceInfo *pInfo = &deviceInfo; - CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, deviceInfo); + CovertNodeBasicInfoToDmDevice(nodeBasicInfo, deviceInfo); LOGD("SoftbusConnector::GetLocalDeviceInfo success"); return DM_OK; } diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index e25d41567..fced39c0f 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -41,7 +41,7 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con } else { LOGD("DmDiscoveryManager::StartDeviceDiscovery stop preview discovery first, the preview pkgName is %s", discoveryQueue_.front().c_str()); StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); - softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); + // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); } } discoveryQueue_.push(pkgName); @@ -78,9 +78,7 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDevic void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) { LOGI("DmDiscoveryManager::OnDiscoveryFailed subscribeId=%d reason=%d", subscribeId, failedReason); // std::string pkgName = discoveryQueue_.front(); - discoveryQueue_.pop(); - discoveryContextMap_.erase(pkgName); - softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); + // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); StopDeviceDiscovery(pkgName, subscribeId); listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); } @@ -95,7 +93,7 @@ void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t void DmDiscoveryManager::HandleDiscoveryTimeout() { LOGI("DmDiscoveryManager::HandleDiscoveryTimeout"); StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); - softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); + // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); } } } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 4a4c602c1..313fe7ffd 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -287,6 +287,23 @@ ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) 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(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) //{ // std::string packName = data.ReadString(); -- Gitee From b4d7170036a57f1bc84b722627f60bb1df55e239 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Tue, 14 Dec 2021 16:09:58 +0800 Subject: [PATCH 030/110] finsh get trusted device --- .../kits/js/include/native_devicemanager_js.h | 1 + .../kits/js/src/native_devicemanager_js.cpp | 50 ++++++++++++------- .../dependency/softbus/softbus_connector.h | 2 +- .../dependency/softbus/softbus_connector.cpp | 14 +++--- .../src/ipc/standard/ipc_cmd_parser.cpp | 38 ++++++++------ 5 files changed, 64 insertions(+), 41 deletions(-) diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 4a9e32484..29a525d4b 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -48,6 +48,7 @@ struct DeviceInfoAsyncCallbackInfo { 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; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 5df4ee9b2..dc749a9d9 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -862,14 +862,14 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI [](napi_env env, void *data) { (void)env; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - // int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - // deviceInfoAsyncCallbackInfo->filter, deviceInfoAsyncCallbackInfo->devList); - // if (ret != 0) { - // LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", - // deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); - // deviceInfoAsyncCallbackInfo->status = -1; - // return; - // } + int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->extra, deviceInfoAsyncCallbackInfo->devList); + 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); }, @@ -891,14 +891,14 @@ void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo env, nullptr, resourceName, [](napi_env env, void *data) { DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - // int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - // deviceInfoAsyncCallbackInfo->filter, deviceInfoAsyncCallbackInfo->devList); - // if (ret != 0) { - // LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", - // deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); - // deviceInfoAsyncCallbackInfo->status = -1; - // return; - // } + int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->extra, deviceInfoAsyncCallbackInfo->devList); + 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); }, @@ -922,6 +922,8 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in // filterOptions.sortType = (DmDeviceSortType)sortType; // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + 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); @@ -940,6 +942,9 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in deviceInfoAsyncCallbackInfo->deferred = deferred; // JsToDmFilterOptions(env, argv[0], filterOptions); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + char extraString[20]; + JsObjectToString(env, argv[0], "extra", extraString, sizeof(extraString)); + deviceInfoAsyncCallbackInfo->extra = extraString; CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); return promise; } @@ -969,6 +974,8 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i // filterOptions.sortType = (DmDeviceSortType)sortType; // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + std::string extra = ""; + deviceInfoAsyncCallbackInfo->extra = extra; napi_deferred deferred; napi_value promise = 0; napi_create_promise(env, &deferred, &promise); @@ -991,6 +998,9 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i LOGE("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); // JsToDmFilterOptions(env, argv[0], filterOptions); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + 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); @@ -1152,12 +1162,14 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf JsToDmDeviceInfo(env, argv[0], deviceInfo); // DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); - std::string extra; + char extra[20]; + JsObjectToString(env, argv[PARAM_INDEX_ONE], "extra", extra, sizeof(extra)); + std::string extraString = extra; // JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], appImageInfo, extra, authAsyncCallbackInfo_.authType); //TODO:get real authType int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, - extra, authCallback); + extraString, authCallback); if (ret != 0) { LOGE("AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); @@ -1493,7 +1505,7 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) napi_value dmClass = nullptr; napi_property_descriptor dmProperties[] = { DECLARE_NAPI_FUNCTION("release", ReleaseDeviceManager), - DECLARE_NAPI_FUNCTION("getTrustedDeviceListSync", GetTrustedDeviceList), + DECLARE_NAPI_FUNCTION("getTrustedDeviceList", GetTrustedDeviceList), DECLARE_NAPI_FUNCTION("startDeviceDiscovery", StartDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("stopDeviceDiscovery", StopDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("getLocalDeviceInfoSync", GetLocalDeviceInfoSync), diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index 6884ad5e6..eca99fb91 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -51,7 +51,7 @@ public: 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 GetTrustedDeviceList(std::vector &deviceInfoList); int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo); int32_t StartDiscovery(const DmSubscribeInfo &subscribeInfo); int32_t StopDiscovery(uint16_t subscribeId); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index d041d4924..7a72df241 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -101,7 +101,7 @@ int32_t SoftbusConnector::Init() } while (ret != DM_OK); LOGI("RegNodeDeviceStateCb success."); - //TODO:check system properties first + // TODO:check system properties first 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) { @@ -151,23 +151,23 @@ int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgN return DM_OK; } -int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceInfoList) +int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &deviceInfoList) { LOGD("SoftbusConnector::GetTrustDevices start"); + int32_t infoNum = 0; NodeBasicInfo *nodeInfo = nullptr; - int32_t *infoNum = 0; - int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeInfo, infoNum); + 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)); + 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) { + for (int32_t i = 0; i < infoNum; ++i) { NodeBasicInfo *nodeBasicInfo = nodeInfo + i; DmDeviceInfo *deviceInfo = *pInfoList + i; CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, *deviceInfo); @@ -175,7 +175,7 @@ int32_t SoftbusConnector::GetTrustedDeviceList(std::vector deviceI } FreeNodeInfo(nodeInfo); free(info); - LOGD("SoftbusConnector::GetTrustDevices success, deviceCount %d", *infoNum); + LOGD("SoftbusConnector::GetTrustDevices success, deviceCount %d", infoNum); return DM_OK; } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 313fe7ffd..d6e4384ce 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -187,20 +187,30 @@ ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) std::string extra = data.ReadString(); LOGI("pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str()); //TODO: -// DmDeviceInfo *info = nullptr; -// int32_t infoNum = 0; -// int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); -// reply.WriteInt32(infoNum); -// if (infoNum > 0 && info != nullptr) { -// if (!reply.WriteRawData(info, sizeof(DmDeviceInfo) * infoNum)) { -// LOGE("write subscribeInfo failed"); -// } -// free(info); -// } -// if (!reply.WriteInt32(result)) { -// LOGE("write result failed"); -// return DM_WRITE_FAILED; -// } + std::vector deviceList; + int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + int32_t infoNum = deviceList.size(); + if (!reply.WriteInt32(infoNum)) { + LOGE("write infoNum failed"); + return DM_WRITE_FAILED; + } + if (!deviceList.empty()){ + DmDeviceInfo *deviceInfo = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo)*infoNum); + for (; !deviceList.empty();){ + *(deviceInfo + infoNum) = deviceList.back(); + deviceList.pop_back(); + } + if (!reply.WriteRawData(deviceInfo, sizeof(DmDeviceInfo) * infoNum)) { + LOGE("write subscribeInfo failed"); + return DM_WRITE_FAILED; + } + free(deviceInfo); + } + 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; } -- Gitee From c94fe9741c032bf799eaea147bcc92e10b694c0e Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Wed, 15 Dec 2021 15:32:42 +0800 Subject: [PATCH 031/110] =?UTF-8?q?=E7=94=A8=E6=88=B7=E5=88=87=E6=8D=A2?= =?UTF-8?q?=E4=BA=8B=E4=BB=B6=E7=9B=91=E5=90=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 3 +- services/devicemanagerservice/BUILD.gn | 6 + .../commonevent/event_manager_adapt.h | 76 +++++++++ .../commonevent/event_manager_adapt.cpp | 151 ++++++++++++++++++ 4 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h create mode 100644 services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index e8eed261c..4c68324db 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -26,7 +26,7 @@ namespace DistributedHardware { 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 DS_SO_NAME = "libdevicemanagerservice_ds_adapter.z.so"; const std::string DP_SO_NAME = "libdevicemanagerservice_dp_adapter.z.so"; const std::string CRYPTO_SO_NAME = "ibdevicemanagerservice_crypto_adapter.z.so"; @@ -42,6 +42,7 @@ namespace DistributedHardware { 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 { diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 4d61022aa..804f60a3a 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -110,6 +110,7 @@ if (defined(ohos_lite)) { "include/deviceinfo", "include/devicestate", "include/discovery", + "include/dependency/commonevent", "include/dependency/hichain", "include/dependency/softbus", "include/dependency/eventbus", @@ -126,6 +127,8 @@ if (defined(ohos_lite)) { "${innerkits_path}/native_cpp/include/ipc/standard", "//utils/native/base/include", "//utils/system/safwk/native/include", + "//base/notification/ces_standard/frameworks/core/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/security/deviceauth/interfaces/innerkits", "//base/startup/syspara_lite/interfaces/kits", "//base/startup/syspara_lite/adapter/native/syspara/include", @@ -144,6 +147,7 @@ if (defined(ohos_lite)) { "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", "src/dependency/eventbus/event_bus.cpp", + "src/dependency/commonevent/event_manager_adapt.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", @@ -170,6 +174,8 @@ if (defined(ohos_lite)) { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "appexecfwk_standard:appexecfwk_base", "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", 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..f472380be --- /dev/null +++ b/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_log.h" +#include "common_event.h" +#include "matching_skills.h" +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.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/src/dependency/commonevent/event_manager_adapt.cpp b/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp new file mode 100644 index 000000000..06386d2b9 --- /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 -- Gitee From 2afd80ce2c737c4f4f7e6f72f84d9b113eb12151 Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Thu, 16 Dec 2021 19:10:36 +0800 Subject: [PATCH 032/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/devicemanagerservice/src/device_manager_service.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 710d8ec5a..691e2e95d 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -185,7 +185,6 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c return DM_INPUT_PARA_EMPTY; } - return authMgr_->VerifyAuthentication(pkgName, authParam); } } // namespace DistributedHardware } // namespace OHOS -- Gitee From 2477e2e2c5d9135d3f7f1c3a7845dab323772268 Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Thu, 16 Dec 2021 19:13:50 +0800 Subject: [PATCH 033/110] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/devicemanagerservice/src/device_manager_service.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 691e2e95d..710d8ec5a 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -185,6 +185,7 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c return DM_INPUT_PARA_EMPTY; } + return authMgr_->VerifyAuthentication(pkgName, authParam); } } // namespace DistributedHardware } // namespace OHOS -- Gitee From b172721774c354ae5950b0a7f8be263ddb23d8ae Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Thu, 16 Dec 2021 21:06:33 +0800 Subject: [PATCH 034/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9hap=E5=8C=85=E6=8B=89?= =?UTF-8?q?=E8=B5=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/c_cpp_properties.json | 19 ++ common/include/device_manager_errno.h | 62 ++++++ common/include/dm_constants.h | 6 +- common/include/ipc/ipc_def.h | 2 + .../include/ipc/model/ipc_get_dmfaparam_rsp.h | 41 ++++ .../ipc/model/ipc_set_useroperation_req.h | 41 ++++ ext/pin_auth/src/pin_auth.cpp | 1 + ext/pin_auth/src/pin_auth_ui.cpp | 24 +++ .../native_cpp/include/device_manager.h | 3 + .../native_cpp/include/device_manager_impl.h | 3 + .../native_cpp/include/dm_device_info.h | 27 ++- .../native_cpp/src/device_manager_impl.cpp | 45 +++++ .../src/ipc/lite/ipc_cmd_parser.cpp | 36 ++-- .../src/ipc/standard/ipc_cmd_parser.cpp | 95 ++++++++- .../kits/js/include/native_devicemanager_js.h | 3 +- .../kits/js/src/native_devicemanager_js.cpp | 184 ++++++++---------- services/devicemanagerservice/BUILD.gn | 10 +- .../include/ability/dm_ability_manager.h | 69 +++++++ .../include/authentication/auth_ui.h | 31 +++ .../include/authentication/dm_auth_manager.h | 10 + .../include/device_manager_service.h | 3 + .../src/ability/lite/dm_ability_manager.cpp | 53 +++++ .../ability/standard/dm_ability_manager.cpp | 108 ++++++++++ .../src/authentication/auth_ui.cpp | 42 ++++ .../src/authentication/dm_auth_manager.cpp | 49 +++++ .../src/device_manager_service.cpp | 32 +++ .../src/ipc/lite/ipc_cmd_parser.cpp | 10 + .../src/ipc/standard/ipc_cmd_parser.cpp | 122 ++++++++---- 28 files changed, 964 insertions(+), 167 deletions(-) create mode 100644 .vscode/c_cpp_properties.json create mode 100644 common/include/device_manager_errno.h create mode 100644 common/include/ipc/model/ipc_get_dmfaparam_rsp.h create mode 100644 common/include/ipc/model/ipc_set_useroperation_req.h create mode 100644 services/devicemanagerservice/include/ability/dm_ability_manager.h create mode 100644 services/devicemanagerservice/include/authentication/auth_ui.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/authentication/auth_ui.cpp diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 000000000..46cf7f48c --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,19 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "cStandard": "c17", + "cppStandard": "c++17", + "intelliSenseMode": "windows-msvc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/common/include/device_manager_errno.h b/common/include/device_manager_errno.h new file mode 100644 index 000000000..7189a7520 --- /dev/null +++ b/common/include/device_manager_errno.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_ERRNO_H +#define OHOS_DEVICE_MANAGER_ERRNO_H + +namespace OHOS { +namespace DistributedHardware { +enum { + DEVICEMANAGER_FAILED = (-10000), + DEVICEMANAGER_SEND_WIFI_INFO_FAILED, + 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/dm_constants.h b/common/include/dm_constants.h index 4c68324db..c6928dbd3 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -26,7 +26,7 @@ namespace DistributedHardware { 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 DS_SO_NAME = "libdevicemanagerservice_ds_adapter.z.so"; const std::string DP_SO_NAME = "libdevicemanagerservice_dp_adapter.z.so"; const std::string CRYPTO_SO_NAME = "ibdevicemanagerservice_crypto_adapter.z.so"; @@ -43,6 +43,8 @@ namespace DistributedHardware { 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 FAIL = -1; + const int32_t SUCCESS = 0; // const int32_t TOKEN_LEN = 9; enum { @@ -120,6 +122,8 @@ namespace DistributedHardware { const int32_t MSG_MAX_SIZE = 45 * 1024; const int32_t AUTH_REPLY_ACCEPT = 0; const int32_t ENCRYPT_TAG_LEN = 32; + const int32_t DISPLAY_OWNER_SYSTEM = 0; + const int32_t DISPLAY_OWNER_OTHER = 1; //json const std::string AUTH_TYPE = "authType"; const std::string TOKEN = "token"; diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 477bc20f1..1091f52f8 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -49,6 +49,8 @@ enum IpcCmdID { SERVER_DISCOVER_FINISH, SERVER_AUTH_RESULT, SERVER_VERIFY_AUTH_RESULT, + SERVER_GET_DMFA_INFO, + SERVER_USER_AUTHORIZATION_OPERATION, }; } // namespace DistributedHardware } // namespace OHOS 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..ccc8ed836 --- /dev/null +++ b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_GET_DM_FA_PARAM_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_GET_DM_FA_PARAM_RSP_H + +#include "ipc_rsp.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetDmFaParamRsp : public IpcRsp { +DECLARE_IPC_MODEL(IpcGetDmFaParamRsp); +public: + const DmFaParam& GetDmFaParam() const + { + return dmFaParam_; + } + + void SetDmFaParam(DmFaParam &dmFaParam) + { + dmFaParam_ = dmFaParam; + } +private: + DmFaParam 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_set_useroperation_req.h b/common/include/ipc/model/ipc_set_useroperation_req.h new file mode 100644 index 000000000..e2f51db3f --- /dev/null +++ b/common/include/ipc/model/ipc_set_useroperation_req.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_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" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetOperationReq : public IpcReq { +DECLARE_IPC_MODEL(IpcGetOperationReq); +public: + int32_t GetOperation() const + { + return action_; + } + + void SetOperation(int32_t action) + { + action_ = action; + } + +private: + int32_t action_ {0}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_GET_USER_OPERATION_REQ_H diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 2882905a0..4fa0b6b76 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -15,6 +15,7 @@ #include "pin_auth.h" #include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index a8e440ca9..6a285beda 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -14,11 +14,35 @@ */ #include "pin_auth_ui.h" +#include "dm_ability_manager.h" +#include "dm_log.h" #include "dm_constants.h" namespace OHOS { namespace DistributedHardware { +PinAuthUi::PinAuthUi() +{ + LOGI("AuthUi constructor"); +} + +int32_t PinAuthUi::ShowPinDialog() +{ + LOGI("RequestSession::StartFaService in"); + return SUCCESS; +} + +int32_t PinAuthUi::InputPinDialog() +{ + LOGI("RequestSession::StartFaService in"); + AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); + if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { + LOGE("RequestSession::StartFaService timeout"); + return FAIL; + } + return SUCCESS; +} + } } diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index cebaffb65..c80a4ab15 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -22,6 +22,7 @@ #include "device_manager_callback.h" #include "dm_subscribe_info.h" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -45,6 +46,8 @@ public: virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) = 0; virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback) = 0; + virtual int32_t GetFaParam(std::string &pkgName, DmAuthParam &faParam) = 0; + virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) = 0; }; } // namespace DistributedHardware } // namespace OHOS 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 f7d488d26..629544ef2 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -19,6 +19,7 @@ #include "device_manager.h" #include "ipc_client_proxy.h" #include "ipc_client_manager.h" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -43,6 +44,8 @@ public: virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) override; virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback) override; + virtual int32_t GetFaParam(std::string &pkgName, DmAuthParam &faParam) override; + virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) override; private: DeviceManagerImpl() = default; ~DeviceManagerImpl() = default; 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 b27d11c01..a0efaf188 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -43,17 +43,42 @@ typedef enum DmDeviceState { DEVICE_INFO_READY = 4, } DmDeviceState; +typedef struct DmConWifiParam { + std::string packageName; + std::string wifiSsid; + int32_t configureResult; +}DmConWifiParam; + typedef struct DmDeviceInfo { char deviceId[DM_MAX_DEVICE_ID_LEN]; char deviceName[DM_MAX_DEVICE_NAME_LEN]; uint16_t deviceTypeId; } DmDeviceInfo; +typedef enum DmFaType { + FA_TYPE_UNKNOWN = 0X00, + FA_TYPE_AUTH = 0x01, + FA_TYPE_CONWIFI = 0x02, +} DmFaType; + typedef struct DmAuthParam { - int32_t authType; std::string authToken; + std::string packageName; + std::string appName; + std::string appDescription; + int32_t authType; + int32_t business; + int32_t pincode; int32_t direction; + int32_t pinToken; + DmAppImageInfo imageinfo; } DmAuthParam; + +typedef struct DmFaParam { + DmFaType type; + DmAuthParam authParam; + DmConWifiParam conWifiParam; +}DmFaParam; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_DEVICE_INFO_H 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 6cc2428cf..37fa4d167 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,6 +15,7 @@ #include "device_manager_impl.h" +#include "device_manager_errno.h" #include "dm_log.h" #include "dm_constants.h" #include "device_manager_notify.h" @@ -26,6 +27,7 @@ #include "ipc_get_trustdevice_rsp.h" #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.h" +#include "ipc_get_dmfaparam_rsp.h" #include "ipc_authenticate_device_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" @@ -312,5 +314,48 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons LOGI("DeviceManager::VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); return DM_OK; } + +int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &faParam) +{ + LOGI("DeviceManager::GetAuthenticationParam start"); + if (pkgName.empty()) { + LOGE("Invalid para"); + return DEVICEMANAGER_INVALID_VALUE; + } + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + if (ipcClientProxy_->SendRequest(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + faParam = rsp->GetDmFaParam(); + return DM_OK; +} + + +int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action) +{ + LOGI("DeviceManager::SetUserOperation start"); + if (pkgName.empty()) { + LOGE("Invalid para"); + return DEVICEMANAGER_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) != DM_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("CheckAuthentication Failed with ret %d", ret); + return ret; + } + 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 95d5b9ba5..c23140576 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 @@ -346,24 +346,24 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply) // return DM_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 DM_OK; -//} -// -//ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) -//{ -// pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); -// return DM_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 DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; +} // //ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) //{ 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 09cd78b2c..7ab87f65a 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 @@ -22,6 +22,8 @@ #include "device_manager_notify.h" #include "ipc_def.h" +#include "ipc_rsp.h" +#include "ipc_req.h" #include "ipc_register_listener_req.h" #include "ipc_start_discovery_req.h" #include "ipc_stop_discovery_req.h" @@ -322,6 +324,89 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) 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 DEVICEMANAGER_FLATTEN_OBJECT; + } + 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); + DmFaParam dmFaParam; + DmAuthParam authParam; + DmConWifiParam conWifiParam; + size_t dmFaTypeSize = sizeof(DmFaType); + DmFaType *type = (DmFaType*)reply.ReadRawData(dmFaTypeSize); + LOGI("dmfa %d", *type); + if(*type == FA_TYPE_AUTH){ + LOGI("dmfa2 %d", *type); + authParam.direction = reply.ReadInt32(); + authParam.authType = reply.ReadInt32(); + if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { + authParam.pinToken = reply.ReadInt32(); + dmFaParam.authParam = authParam; + dmFaParam.type = *type; + pRsp->SetDmFaParam(dmFaParam); + return DM_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); + dmFaParam.authParam = authParam; + dmFaParam.type = *type; + pRsp->SetDmFaParam(dmFaParam); + LOGI("dmfa3 %d", *type); + }else{ + conWifiParam.packageName = reply.ReadString(); + conWifiParam.wifiSsid = reply.ReadString(); + conWifiParam.configureResult = reply.ReadInt32(); + dmFaParam.type = *type; + dmFaParam.conWifiParam = conWifiParam; + pRsp->SetDmFaParam(dmFaParam); + } + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_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 DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(action)) { + LOGE("write extra failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + + return DM_OK; +} + + //ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &reply, std::shared_ptr pBaseRsp) //{ // std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); @@ -355,10 +440,10 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) // return DM_OK; //} -//ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) -//{ -// pBaseRsp->SetErrCode(reply.ReadInt32()); -// return DM_OK; -//} +ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 29a525d4b..3b29cfdd4 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -48,7 +48,6 @@ struct DeviceInfoAsyncCallbackInfo { 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; @@ -149,7 +148,7 @@ public: 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 GetAuthenticationParamSync(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); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index dc749a9d9..b556a7254 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -352,46 +352,46 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, napi_value extraInfo = nullptr; napi_create_object(env, &extraInfo); SetValueInt32(env, "direction", authParam.direction, extraInfo); -// SetValueInt32(env, "authToken", authParam.authToken, extraInfo); + SetValueInt32(env, "authToken", authParam.authToken, extraInfo); if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; } -// SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); -// SetValueUtf8String(env, "appName", authParam.appName, extraInfo); -// SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); -// SetValueInt32(env, "business", authParam.business, extraInfo); -// SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); -// napi_set_named_property(env, paramResult, "extraInfo", extraInfo); - -// size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); -// if (appIconLen > 0) { -// void *appIcon = nullptr; -// 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) { -// napi_value appIconArray = nullptr; -// napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); -// napi_set_named_property(env, paramResult, "appIcon", appIconArray); -// } -// } - -// size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); -// if (appThumbnailLen > 0) { -// void *appThumbnail = nullptr; -// napi_value appThumbnailBuffer = nullptr; -// napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); -// if (appThumbnail != nullptr && -// memcpy_s(appThumbnail, appThumbnailLen, -// 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); -// } -// } + SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); + SetValueUtf8String(env, "appName", authParam.appName, extraInfo); + SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); + SetValueInt32(env, "business", authParam.business, extraInfo); + SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); + napi_set_named_property(env, paramResult, "extraInfo", extraInfo); + + size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); + if (appIconLen > 0) { + void *appIcon = nullptr; + 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) { + napi_value appIconArray = nullptr; + napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); + napi_set_named_property(env, paramResult, "appIcon", appIconArray); + } + } + + size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); + if (appThumbnailLen > 0) { + void *appThumbnail = nullptr; + napi_value appThumbnailBuffer = nullptr; + napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); + if (appThumbnail != nullptr && + memcpy_s(appThumbnail, appThumbnailLen, + 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); + } + } } void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, @@ -728,32 +728,32 @@ 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().GetAuthenticationParam(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::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) { @@ -767,11 +767,11 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i napi_get_value_int32(env, argv[0], &action); DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - // int32_t ret = DeviceManager::GetInstance().SetUserOperation(deviceManagerWrapper->bundleName_, action); - // if (ret != 0) { - // LOGE("SetUserOperation for bunderName %s failed, ret %d", - // deviceManagerWrapper->bundleName_.c_str(), ret); - // } + int32_t ret = DeviceManager::GetInstance().SetUserOperation(deviceManagerWrapper->bundleName_, action); + if (ret != 0) { + LOGE("SetUserOperation for bunderName %s failed, ret %d", + deviceManagerWrapper->bundleName_.c_str(), ret); + } napi_value result = nullptr; napi_get_undefined(env, &result); return result; @@ -862,14 +862,14 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI [](napi_env env, void *data) { (void)env; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->extra, deviceInfoAsyncCallbackInfo->devList); - if (ret != 0) { - LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", - deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); - deviceInfoAsyncCallbackInfo->status = -1; - return; - } + // int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + // deviceInfoAsyncCallbackInfo->filter, deviceInfoAsyncCallbackInfo->devList); + // 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); }, @@ -891,14 +891,14 @@ void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo env, nullptr, resourceName, [](napi_env env, void *data) { DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->extra, deviceInfoAsyncCallbackInfo->devList); - if (ret != 0) { - LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", - deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); - deviceInfoAsyncCallbackInfo->status = -1; - return; - } + // int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, + // deviceInfoAsyncCallbackInfo->filter, deviceInfoAsyncCallbackInfo->devList); + // 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); }, @@ -922,8 +922,6 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in // filterOptions.sortType = (DmDeviceSortType)sortType; // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); // deviceInfoAsyncCallbackInfo->filter = filterOptions; - 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); @@ -942,9 +940,6 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in deviceInfoAsyncCallbackInfo->deferred = deferred; // JsToDmFilterOptions(env, argv[0], filterOptions); // deviceInfoAsyncCallbackInfo->filter = filterOptions; - char extraString[20]; - JsObjectToString(env, argv[0], "extra", extraString, sizeof(extraString)); - deviceInfoAsyncCallbackInfo->extra = extraString; CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); return promise; } @@ -974,8 +969,6 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i // filterOptions.sortType = (DmDeviceSortType)sortType; // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); // deviceInfoAsyncCallbackInfo->filter = filterOptions; - std::string extra = ""; - deviceInfoAsyncCallbackInfo->extra = extra; napi_deferred deferred; napi_value promise = 0; napi_create_promise(env, &deferred, &promise); @@ -998,9 +991,6 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i LOGE("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); // JsToDmFilterOptions(env, argv[0], filterOptions); // deviceInfoAsyncCallbackInfo->filter = filterOptions; - 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); @@ -1162,14 +1152,12 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf JsToDmDeviceInfo(env, argv[0], deviceInfo); // DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); - char extra[20]; - JsObjectToString(env, argv[PARAM_INDEX_ONE], "extra", extra, sizeof(extra)); - std::string extraString = extra; + std::string extra; // JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], appImageInfo, extra, authAsyncCallbackInfo_.authType); //TODO:get real authType int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, - extraString, authCallback); + extra, authCallback); if (ret != 0) { LOGE("AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); @@ -1505,7 +1493,7 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) napi_value dmClass = nullptr; napi_property_descriptor dmProperties[] = { DECLARE_NAPI_FUNCTION("release", ReleaseDeviceManager), - DECLARE_NAPI_FUNCTION("getTrustedDeviceList", GetTrustedDeviceList), + DECLARE_NAPI_FUNCTION("getTrustedDeviceListSync", GetTrustedDeviceList), DECLARE_NAPI_FUNCTION("startDeviceDiscovery", StartDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("stopDeviceDiscovery", StopDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("getLocalDeviceInfoSync", GetLocalDeviceInfoSync), @@ -1513,7 +1501,7 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("authenticateDevice", AuthenticateDevice), DECLARE_NAPI_FUNCTION("verifyAuthInfo", VerifyAuthInfo), DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync), -// DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync), + DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync), DECLARE_NAPI_FUNCTION("on", JsOn), DECLARE_NAPI_FUNCTION("off", JsOff) }; diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 804f60a3a..1bd3ba0ed 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -23,6 +23,7 @@ if (defined(ohos_lite)) { executable("devicemanagerservice") { include_dirs = [ "include", + "include/ability", "include/adapter", "include/authentication", "include/deviceinfo", @@ -61,6 +62,7 @@ if (defined(ohos_lite)) { ] sources = [ + "src/ability/lite/dm_ability_manager.cpp", "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", "src/adapter/lite/dm_adapter_manager.cpp", @@ -105,12 +107,12 @@ if (defined(ohos_lite)) { ohos_shared_library("devicemanagerservice") { include_dirs = [ "include", + "include/ability", "include/adapter", "include/authentication", "include/deviceinfo", "include/devicestate", "include/discovery", - "include/dependency/commonevent", "include/dependency/hichain", "include/dependency/softbus", "include/dependency/eventbus", @@ -127,8 +129,6 @@ if (defined(ohos_lite)) { "${innerkits_path}/native_cpp/include/ipc/standard", "//utils/native/base/include", "//utils/system/safwk/native/include", - "//base/notification/ces_standard/frameworks/core/include", - "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/security/deviceauth/interfaces/innerkits", "//base/startup/syspara_lite/interfaces/kits", "//base/startup/syspara_lite/adapter/native/syspara/include", @@ -136,6 +136,7 @@ if (defined(ohos_lite)) { ] sources = [ + "src/ability/standard/dm_ability_manager.cpp", "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", "src/adapter/standard/dm_adapter_manager.cpp", @@ -147,7 +148,6 @@ if (defined(ohos_lite)) { "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", "src/dependency/eventbus/event_bus.cpp", - "src/dependency/commonevent/event_manager_adapt.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", @@ -174,8 +174,6 @@ if (defined(ohos_lite)) { ] external_deps = [ - "ces_standard:cesfwk_core", - "ces_standard:cesfwk_innerkits", "appexecfwk_standard:appexecfwk_base", "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h new file mode 100644 index 000000000..0db1b7cdb --- /dev/null +++ b/services/devicemanagerservice/include/ability/dm_ability_manager.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "nlohmann/json.hpp" + +#include "single_instance.h" +#include "dm_device_info.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(); + const DmFaType &GetDmFaType() const; + void SetDmFaType(const DmFaType &type); +private: + void waitForTimeout(uint32_t timeout_s); + +private: + sem_t mSem_; + AbilityStatus mStatus_; + AbilityRole mAbilityStatus_; + DmFaType mDmFaType_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h new file mode 100644 index 000000000..647ddc218 --- /dev/null +++ b/services/devicemanagerservice/include/authentication/auth_ui.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_AUTH_UI_H +#define OHOS_DM_AUTH_UI_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class AuthUi { +public: + AuthUi(); + int32_t ShowConfirmDialog(); +private: +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_UI_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 3785ab305..5f3628a19 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -20,6 +20,7 @@ #include #include "authentication.h" +#include "dm_device_info.h" #include "softbus_session.h" #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" @@ -118,6 +119,7 @@ public: 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); + int32_t GetDisplayOwner(); //auth state machine void EstablishAuthChannel(const std::string &deviceId); @@ -127,6 +129,9 @@ public: void JoinGroup(const std::string &deviceId); void JoinNetwork(); void AuthenticateFinish(); + int32_t GetAuthenticationParam(DmAuthParam &authParam); + void OnUserOperate(int32_t action); + private: void HandleAuthenticateTimeout(); private: @@ -136,12 +141,17 @@ private: std::shared_ptr listener_; std::shared_ptr adapterMgr_; std::map> authenticationMap_; + int32_t displayOwner_ = 0; std::shared_ptr authRequestState_ = nullptr; std::shared_ptr authResponseState_ = nullptr; std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; + std::shared_ptr mPendingReqSessionPtr_ {nullptr}; + std::shared_ptr mPendingRespSessionPtr {}; + + }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index 7b29bb4fa..c284c2f8d 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -23,6 +23,7 @@ #include "dm_device_info_manager.h" #include "dm_device_state_manager.h" #include "dm_discovery_manager.h" +#include "device_manager_errno.h" #include "dm_device_info.h" #include "softbus_connector.h" #include "single_instance.h" @@ -40,6 +41,8 @@ public: 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 &pkgName, const std::string &authParam); + int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam,DmConWifiParam &conWifiParam, DmFaType &type); + int32_t SetUserOperation(std::string &pkgName, int32_t action); private: bool intFlag_ = false; std::shared_ptr authMgr_; 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..d8c9a369f --- /dev/null +++ b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_ability_manager.h" + +#include "semaphore.h" + +#include "dm_constants.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 new file mode 100644 index 000000000..a77000cf4 --- /dev/null +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_auth_manager.h" +#include "ability_manager_client.h" +#include "ability_record.h" +#include "ability_manager_service.h" +#include "parameter.h" +#include "semaphore.h" + +#include "dm_constants.h" +#include "single_instance.h" +#include "dm_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 { + LOGE("StartAbility, failed, role unknown"); + return AbilityStatus::ABILITY_STATUS_FAILED; + } + + LOGE("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) ? + DmAuthManager::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) { + LOGI("Start Ability succeed"); + } else { + 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); +} + +const DmFaType &DmAbilityManager::GetDmFaType() const +{ + return mDmFaType_; +} + +void DmAbilityManager::SetDmFaType(const DmFaType &type) +{ + mDmFaType_ = type; +} + +void DmAbilityManager::StartAbilityDone() +{ + mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + sem_post(&mSem_); +} +} +} diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp new file mode 100644 index 000000000..a2c68b155 --- /dev/null +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -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. + */ + +#include "auth_ui.h" +#include "dm_ability_manager.h" +#include "dm_log.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +AuthUi::AuthUi() +{ + LOGI("AuthUi constructor"); +} + +int32_t AuthUi::ShowConfirmDialog() +{ + LOGI("RequestSession::StartFaService in"); + AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); + if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { + LOGE("RequestSession::StartFaService timeout"); + return FAIL; + } + return SUCCESS; +} + + +} +} diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 58cec854d..f14494b4c 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -244,5 +244,54 @@ void DmAuthManager::AuthenticateFinish() //清理资源,关闭通道 softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); } + +int32_t DmAuthManager::GetDisplayOwner() +{ + return displayOwner_; +} + +int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) +{ + AbilityRole role = DmAbilityManager::GetInstance().GetAbilityRole(); + LOGI("GetAuthenticationParam:: role = %d", (int32_t)role); + if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { + if (mPendingReqSessionPtr_ == nullptr) { + LOGE("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(); + LOGI("GetAuthenticationParam, role is ABILITY_ROLE_INITIATIVE"); + return SUCCESS; + } + + if (mPendingRespSessionPtr == nullptr) { + LOGE("AuthManager:: Get Auth params FAIL : mPendingRespSessionPtr(nullptr)"); + return FAIL; + } + + mPendingRespSessionPtr->BuildAuthenticationInfo(authParam); + return SUCCESS; +} + +void DmAuthManager::OnUserOperate(int32_t action) +{ + if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { + if (mPendingReqSessionPtr_ == nullptr) { + LOGE("mPendingReqSessionPtr_ not exist"); + return; + } + mPendingReqSessionPtr_->OnUserOperate(action); + return; + } + + if (mPendingRespSessionPtr == nullptr) { + LOGE("mPendingRespSessionPtr not exist"); + return; + } + + mPendingRespSessionPtr->OnUserOperate(action); +} } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 710d8ec5a..0cf6449bd 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -187,5 +187,37 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c return authMgr_->VerifyAuthentication(pkgName, authParam); } + +int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam, + DmConWifiParam &conWifiParam, DmFaType &type) +{ + if (pkgName.empty()) { + LOGE("invalid para"); + return DEVICEMANAGER_INVALID_VALUE; + } + + type = DmAbilityManager::GetInstance().GetDmFaType(); + + ConfignetWifiParam wifiParam; + ConfignetManager::GetInstance().GetConfigureWifiParam(conWifiParam.packageName, wifiParam); + conWifiParam.wifiSsid = wifiParam.ssid; + conWifiParam.configureResult = wifiParam.result; + LOGI("::.GetConfigureWifiParam %d, %s,%d",type,conWifiParam.wifiSsid.c_str(), + conWifiParam.configureResult); + DmAbilityManager::GetInstance().StartAbilityDone(); + DmAuthManager::GetInstance().GetAuthenticationParam(authParam); + return DM_OK; +} + +int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action) +{ + if (pkgName.empty()) { + LOGE("invalid para"); + return DEVICEMANAGER_INVALID_VALUE; + } + + DmAuthManager::GetInstance().OnUserOperate(action); + return DM_OK; +} } // 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 index cbf4ebf0d..267dd9a3b 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -228,6 +228,16 @@ ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATION, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, ret); } +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); + DeviceManagerService::GetInstance().SetUserOperation(packName, action); + + IpcIoPushInt32(&reply, action); +} + //ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) //{ // size_t len = 0; diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index d6e4384ce..d73b57100 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -187,30 +187,20 @@ ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) std::string extra = data.ReadString(); LOGI("pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str()); //TODO: - std::vector deviceList; - int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); - int32_t infoNum = deviceList.size(); - if (!reply.WriteInt32(infoNum)) { - LOGE("write infoNum failed"); - return DM_WRITE_FAILED; - } - if (!deviceList.empty()){ - DmDeviceInfo *deviceInfo = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo)*infoNum); - for (; !deviceList.empty();){ - *(deviceInfo + infoNum) = deviceList.back(); - deviceList.pop_back(); - } - if (!reply.WriteRawData(deviceInfo, sizeof(DmDeviceInfo) * infoNum)) { - LOGE("write subscribeInfo failed"); - return DM_WRITE_FAILED; - } - free(deviceInfo); - } - 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()); +// DmDeviceInfo *info = nullptr; +// int32_t infoNum = 0; +// int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); +// reply.WriteInt32(infoNum); +// if (infoNum > 0 && info != nullptr) { +// if (!reply.WriteRawData(info, sizeof(DmDeviceInfo) * infoNum)) { +// LOGE("write subscribeInfo failed"); +// } +// free(info); +// } +// if (!reply.WriteInt32(result)) { +// LOGE("write result failed"); +// return DM_WRITE_FAILED; +// } return DM_OK; } @@ -314,6 +304,66 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) { return DM_OK; } +ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { + std::string packName = data.ReadString(); + DmAuthParam authParam; + DmConWifiParam conWifiParam; + DmFaType type; + int32_t ret = DM_OK; + LOGE("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); + DeviceManagerService::GetInstance().GetFaParam(packName, authParam, conWifiParam, type); + + if (!reply.WriteRawData(&type, sizeof(DmFaType))) { + LOGE("write appThumbnail failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + LOGI("dmfa1 %d", type); + if(type == FA_TYPE_AUTH){ + if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { + if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + !reply.WriteInt32(authParam.pinToken)) { + LOGE("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)) { + LOGE("write reply failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + + if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { + if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { + LOGE("write appIcon failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + } + + if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { + if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { + LOGE("write appThumbnail failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + } + }else { + if(!reply.WriteString(conWifiParam.packageName) || !reply.WriteString(conWifiParam.wifiSsid) || + !reply.WriteInt32(conWifiParam.configureResult)){ + LOGE("write reply failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + } + return DM_OK; +} + //ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) //{ // std::string packName = data.ReadString(); @@ -358,18 +408,18 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) { // return DM_OK; //} // -//ON_IPC_CMD(SERVER_USER_AUTHORIZATION_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; -//} +ON_IPC_CMD(SERVER_USER_AUTHORIZATION_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; +} //ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) //{ -- Gitee From c0e9d5d2e2e6e6416fbaa454f1e841446bc5b82b Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Sat, 18 Dec 2021 10:26:06 +0800 Subject: [PATCH 035/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E5=85=B3=E9=94=AE=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/device_manager_errno.h | 62 ------------------- common/include/dm_constants.h | 3 + .../native_cpp/include/dm_device_info.h | 1 - .../native_cpp/src/device_manager_impl.cpp | 13 ++-- .../src/ipc/standard/ipc_cmd_parser.cpp | 6 +- .../include/authentication/dm_auth_manager.h | 7 +-- .../include/device_manager_service.h | 1 - .../src/authentication/dm_auth_manager.cpp | 44 +++++++++---- .../src/device_manager_service.cpp | 14 ++--- .../src/ipc/standard/ipc_cmd_parser.cpp | 12 ++-- 10 files changed, 57 insertions(+), 106 deletions(-) delete mode 100644 common/include/device_manager_errno.h diff --git a/common/include/device_manager_errno.h b/common/include/device_manager_errno.h deleted file mode 100644 index 7189a7520..000000000 --- a/common/include/device_manager_errno.h +++ /dev/null @@ -1,62 +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_SEND_WIFI_INFO_FAILED, - 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/dm_constants.h b/common/include/dm_constants.h index c6928dbd3..f1a869d2c 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -124,6 +124,9 @@ namespace DistributedHardware { const int32_t ENCRYPT_TAG_LEN = 32; 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"; 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 a0efaf188..8d598851b 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -71,7 +71,6 @@ typedef struct DmAuthParam { int32_t pincode; int32_t direction; int32_t pinToken; - DmAppImageInfo imageinfo; } DmAuthParam; typedef struct DmFaParam { 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 37fa4d167..48055a281 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,7 +15,6 @@ #include "device_manager_impl.h" -#include "device_manager_errno.h" #include "dm_log.h" #include "dm_constants.h" #include "device_manager_notify.h" @@ -319,14 +318,14 @@ int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &faParam { LOGI("DeviceManager::GetAuthenticationParam start"); if (pkgName.empty()) { - LOGE("Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + 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); if (ipcClientProxy_->SendRequest(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } faParam = rsp->GetDmFaParam(); return DM_OK; @@ -337,8 +336,8 @@ int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action { LOGI("DeviceManager::SetUserOperation start"); if (pkgName.empty()) { - LOGE("Invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("VerifyAuthentication failed, pkgName is empty"); + return DM_INVALID_VALUE; } std::shared_ptr req = std::make_shared(); @@ -348,7 +347,7 @@ int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action req->SetOperation(action); if (ipcClientProxy_->SendRequest(SERVER_USER_AUTHORIZATION_OPERATION, req, rsp) != DM_OK) { - return DEVICEMANAGER_IPC_FAILED; + return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); if (ret != DM_OK) { 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 7ab87f65a..f8d459911 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 @@ -330,7 +330,7 @@ ON_IPC_SET_REQUEST(SERVER_GET_DMFA_INFO, std::shared_ptr pBaseReq, Messa std::string packagename = pReq->GetPkgName(); if (!data.WriteString(packagename)) { LOGE("write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_FLATTEN_OBJECT; } return DM_OK; } @@ -396,11 +396,11 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr if (!data.WriteString(pkgName)) { LOGE("write pkgName failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteInt32(action)) { LOGE("write extra failed"); - return DEVICEMANAGER_FLATTEN_OBJECT; + return DM_WRITE_FAILED; } return DM_OK; diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 5f3628a19..cc415ca30 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -87,7 +87,7 @@ typedef struct DmAuthRequestContext { std::string appThumbnail; std::string token; std::vector syncGroupList; -} DmAuthRequestContext; +} ; typedef struct DmAuthResponseContext { std::string deviceId; @@ -131,6 +131,8 @@ public: void AuthenticateFinish(); int32_t GetAuthenticationParam(DmAuthParam &authParam); void OnUserOperate(int32_t action); + void BuildAuthenticationInfo(DmAuthParam &authParam); + void OnUserOperate(int32_t action); private: void HandleAuthenticateTimeout(); @@ -148,9 +150,6 @@ private: std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; - std::shared_ptr mPendingReqSessionPtr_ {nullptr}; - std::shared_ptr mPendingRespSessionPtr {}; - }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index c284c2f8d..5c3d0db85 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -23,7 +23,6 @@ #include "dm_device_info_manager.h" #include "dm_device_state_manager.h" #include "dm_discovery_manager.h" -#include "device_manager_errno.h" #include "dm_device_info.h" #include "softbus_connector.h" #include "single_instance.h" diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index f14494b4c..8f157e6ad 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -255,43 +255,63 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) AbilityRole role = DmAbilityManager::GetInstance().GetAbilityRole(); LOGI("GetAuthenticationParam:: role = %d", (int32_t)role); if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { - if (mPendingReqSessionPtr_ == nullptr) { - LOGE("AuthManager:: Get Auth params FAIL : mPendingReqSessionPtr_(nullptr)"); + if (authRequestState_ == nullptr) { + LOGE("Get Auth params FAIL : authRequestState_(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(); + authParam.pinToken = DmAuthRequestContext::token; LOGI("GetAuthenticationParam, role is ABILITY_ROLE_INITIATIVE"); return SUCCESS; } - if (mPendingRespSessionPtr == nullptr) { - LOGE("AuthManager:: Get Auth params FAIL : mPendingRespSessionPtr(nullptr)"); + if (authResponseState_ == nullptr) { + LOGE("Get Auth params FAIL : authResponseState_(nullptr)"); return FAIL; } - mPendingRespSessionPtr->BuildAuthenticationInfo(authParam); + BuildAuthenticationInfo(authParam); return SUCCESS; } void DmAuthManager::OnUserOperate(int32_t action) { if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { - if (mPendingReqSessionPtr_ == nullptr) { - LOGE("mPendingReqSessionPtr_ not exist"); + if (authRequestState_ == nullptr) { + LOGE("authRequestState_ not exist"); + return; + } + if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { + SoftbusSession::GetInstance().CloseAuthSession(DmAuthRequestContext::sessionId); return; } - mPendingReqSessionPtr_->OnUserOperate(action); return; } - if (mPendingRespSessionPtr == nullptr) { - LOGE("mPendingRespSessionPtr not exist"); + if (authResponseState_ == nullptr) { + LOGE("authResponseState_ not exist"); return; } - mPendingRespSessionPtr->OnUserOperate(action); } + +void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) +{ + LOGI("BuildAuthenticationInfo in"); + authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole(); + if (authRequestState_ == nullptr) { + LOGE("BuildAuthenticationInfo authRequestState_ is nullptr"); + return; + } + + authParam.packageName = DmAuthRequestContext::targetPkgName; + authParam.appName = DmAuthRequestContext::appName; + authParam.appDescription = DmAuthRequestContext::appName; + authParam.authType = DmAuthRequestContext::authType; + authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION + authParam.pincode = DmAuthRequestContext::authType;//获取生成的pincode +} + } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 0cf6449bd..11610a570 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -192,18 +192,12 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth DmConWifiParam &conWifiParam, DmFaType &type) { if (pkgName.empty()) { - LOGE("invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("VerifyAuthentication failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; } type = DmAbilityManager::GetInstance().GetDmFaType(); - ConfignetWifiParam wifiParam; - ConfignetManager::GetInstance().GetConfigureWifiParam(conWifiParam.packageName, wifiParam); - conWifiParam.wifiSsid = wifiParam.ssid; - conWifiParam.configureResult = wifiParam.result; - LOGI("::.GetConfigureWifiParam %d, %s,%d",type,conWifiParam.wifiSsid.c_str(), - conWifiParam.configureResult); DmAbilityManager::GetInstance().StartAbilityDone(); DmAuthManager::GetInstance().GetAuthenticationParam(authParam); return DM_OK; @@ -212,8 +206,8 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action) { if (pkgName.empty()) { - LOGE("invalid para"); - return DEVICEMANAGER_INVALID_VALUE; + LOGE("VerifyAuthentication failed, pkgName is empty"); + return DM_INPUT_PARA_EMPTY; } DmAuthManager::GetInstance().OnUserOperate(action); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index d73b57100..e4921b7f2 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -315,7 +315,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { if (!reply.WriteRawData(&type, sizeof(DmFaType))) { LOGE("write appThumbnail failed"); - return DEVICEMANAGER_WRITE_FAILED; + return DM_IPC_FLATTEN_OBJECT; } LOGI("dmfa1 %d", type); if(type == FA_TYPE_AUTH){ @@ -323,7 +323,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || !reply.WriteInt32(authParam.pinToken)) { LOGE("DeviceManagerStub::wirte client fail"); - ret = DEVICEMANAGER_WRITE_FAILED; + ret = DM_IPC_FLATTEN_OBJECT; } return ret; @@ -338,27 +338,27 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { !reply.WriteInt32(authParam.pincode) || !reply.WriteInt32(appIconLen) || !reply.WriteInt32(appThumbnailLen)) { LOGE("write reply failed"); - return DEVICEMANAGER_WRITE_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 DEVICEMANAGER_WRITE_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 DEVICEMANAGER_WRITE_FAILED; + return DM_IPC_FLATTEN_OBJECT; } } }else { if(!reply.WriteString(conWifiParam.packageName) || !reply.WriteString(conWifiParam.wifiSsid) || !reply.WriteInt32(conWifiParam.configureResult)){ LOGE("write reply failed"); - return DEVICEMANAGER_WRITE_FAILED; + return DM_IPC_FLATTEN_OBJECT; } } return DM_OK; -- Gitee From 6eaf47a0aa31ff133bf7a43901744766feeeedfa Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Sat, 18 Dec 2021 11:40:45 +0800 Subject: [PATCH 036/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../inner_kits/native_cpp/include/dm_device_info.h | 7 ------- .../native_cpp/src/ipc/standard/ipc_cmd_parser.cpp | 8 -------- .../include/device_manager_service.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 3 +-- .../devicemanagerservice/src/device_manager_service.cpp | 3 +-- .../src/ipc/standard/ipc_cmd_parser.cpp | 9 +-------- 6 files changed, 4 insertions(+), 28 deletions(-) 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 8d598851b..a391bf896 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -43,12 +43,6 @@ typedef enum DmDeviceState { DEVICE_INFO_READY = 4, } DmDeviceState; -typedef struct DmConWifiParam { - std::string packageName; - std::string wifiSsid; - int32_t configureResult; -}DmConWifiParam; - typedef struct DmDeviceInfo { char deviceId[DM_MAX_DEVICE_ID_LEN]; char deviceName[DM_MAX_DEVICE_NAME_LEN]; @@ -76,7 +70,6 @@ typedef struct DmAuthParam { typedef struct DmFaParam { DmFaType type; DmAuthParam authParam; - DmConWifiParam conWifiParam; }DmFaParam; } // 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 f8d459911..e29a80fef 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 @@ -340,7 +340,6 @@ ON_IPC_READ_RESPONSE(SERVER_GET_DMFA_INFO, MessageParcel &reply, std::shared_ptr std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); DmFaParam dmFaParam; DmAuthParam authParam; - DmConWifiParam conWifiParam; size_t dmFaTypeSize = sizeof(DmFaType); DmFaType *type = (DmFaType*)reply.ReadRawData(dmFaTypeSize); LOGI("dmfa %d", *type); @@ -377,13 +376,6 @@ ON_IPC_READ_RESPONSE(SERVER_GET_DMFA_INFO, MessageParcel &reply, std::shared_ptr dmFaParam.type = *type; pRsp->SetDmFaParam(dmFaParam); LOGI("dmfa3 %d", *type); - }else{ - conWifiParam.packageName = reply.ReadString(); - conWifiParam.wifiSsid = reply.ReadString(); - conWifiParam.configureResult = reply.ReadInt32(); - dmFaParam.type = *type; - dmFaParam.conWifiParam = conWifiParam; - pRsp->SetDmFaParam(dmFaParam); } return DM_OK; } diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index 5c3d0db85..618dbebf7 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -40,7 +40,7 @@ public: 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 &pkgName, const std::string &authParam); - int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam,DmConWifiParam &conWifiParam, DmFaType &type); + int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam, DmFaType &type); int32_t SetUserOperation(std::string &pkgName, int32_t action); private: bool intFlag_ = false; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 8f157e6ad..ce669ebb8 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -307,11 +307,10 @@ void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) authParam.packageName = DmAuthRequestContext::targetPkgName; authParam.appName = DmAuthRequestContext::appName; - authParam.appDescription = DmAuthRequestContext::appName; + authParam.appDescription = DmAuthRequestContext::appDesc; authParam.authType = DmAuthRequestContext::authType; authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION authParam.pincode = DmAuthRequestContext::authType;//获取生成的pincode } - } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 11610a570..6154c4875 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -188,8 +188,7 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c return authMgr_->VerifyAuthentication(pkgName, authParam); } -int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam, - DmConWifiParam &conWifiParam, DmFaType &type) +int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam, DmFaType &type) { if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index e4921b7f2..d01ba5f6c 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -307,11 +307,10 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) { ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { std::string packName = data.ReadString(); DmAuthParam authParam; - DmConWifiParam conWifiParam; DmFaType type; int32_t ret = DM_OK; LOGE("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); - DeviceManagerService::GetInstance().GetFaParam(packName, authParam, conWifiParam, type); + DeviceManagerService::GetInstance().GetFaParam(packName, authParam, type); if (!reply.WriteRawData(&type, sizeof(DmFaType))) { LOGE("write appThumbnail failed"); @@ -354,12 +353,6 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { return DM_IPC_FLATTEN_OBJECT; } } - }else { - if(!reply.WriteString(conWifiParam.packageName) || !reply.WriteString(conWifiParam.wifiSsid) || - !reply.WriteInt32(conWifiParam.configureResult)){ - LOGE("write reply failed"); - return DM_IPC_FLATTEN_OBJECT; - } } return DM_OK; } -- Gitee From b86165952bd5a9d24d7c241671bd115f7fe15f6b Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Sat, 18 Dec 2021 17:20:18 +0800 Subject: [PATCH 037/110] =?UTF-8?q?dmFaCallback=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/ipc/ipc_def.h | 1 + .../src/ipc/lite/ipc_cmd_parser.cpp | 16 ++++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 16 ++++++++ .../include/authentication/dm_auth_manager.h | 1 + .../src/authentication/dm_auth_manager.cpp | 13 ++++++- .../src/ipc/lite/ipc_cmd_parser.cpp | 18 +++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 39 ++++++++----------- 7 files changed, 73 insertions(+), 31 deletions(-) diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 1091f52f8..9f077c32c 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -51,6 +51,7 @@ enum IpcCmdID { SERVER_VERIFY_AUTH_RESULT, SERVER_GET_DMFA_INFO, SERVER_USER_AUTHORIZATION_OPERATION, + SERVER_DEVICEMANAGER_FA_NOTIFY, }; } // 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 c23140576..6d2ad25e2 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 @@ -364,14 +364,14 @@ ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::sha pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); return DM_OK; } -// -//ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) -//{ -// size_t len = 0; -// std::string packagename = (const char *)IpcIoPopString(&reply, &len); -// size_t jsonLen = 0; -// std::string paramJson = (const char *)IpcIoPopString(&reply, &jsonLen); + +ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) +{ + size_t len = 0; + std::string packagename = (const char *)IpcIoPopString(&reply, &len); + size_t jsonLen = 0; + std::string paramJson = (const char *)IpcIoPopString(&reply, &jsonLen); // DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); -//} +} } // 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 e29a80fef..cd5229070 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 @@ -437,5 +437,21 @@ ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; } + +ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) +{ + LOGI("OnFaCallBack"); + std::string packagename = data.ReadString(); + std::string paramJson = data.ReadString(); + LOGI("OnFaCallBack Packagename is %s", packagename.c_str()); + LOGI("OnFaCallBack Json is %s", paramJson.c_str()); + // DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); + + if (!reply.WriteInt32(DM_OK)) { + LOGE("write return failed"); + return DM_WRITE_FAILED; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index cc415ca30..8a929bda5 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -120,6 +120,7 @@ public: void OnGroupCreated(int64_t requestId, const std::string &groupId); void OnMemberJoin(int64_t requestId, int32_t status); int32_t GetDisplayOwner(); + void CancelDisplay(); //auth state machine void EstablishAuthChannel(const std::string &deviceId); diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index ce669ebb8..4fd5e38fb 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -186,6 +186,7 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) // if (authRequestState_->GetStateType() == AuthRequestJoinState) { // authRequestState_->TransitionTo(new AuthRequestNetworkState()); // } + CancelDisplay(); } void DmAuthManager::HandleAuthenticateTimeout() { @@ -310,7 +311,17 @@ void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) authParam.appDescription = DmAuthRequestContext::appDesc; authParam.authType = DmAuthRequestContext::authType; authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION - authParam.pincode = DmAuthRequestContext::authType;//获取生成的pincode + authParam.pincode = DmAuthResponseContext::code;//获取生成的pincode +} + +void DmAuthManager::CancelDisplay() +{ + LOGI("Cancel PinCode Display in"); + std::string pkgName = "com.ohos.devicemanagerui"; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + ipcServerListener_.SendRequest(SERVER_DEVICEMANAGER_FA_NOTIFY, req, rsp); } } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 267dd9a3b..7e9cd5e58 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -274,5 +274,23 @@ ON_IPC_SERVER_CMD(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo &req, IpcIo &reply) // IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppThumbnail(), appThumbnailLen); // } //} + +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(); + if (!data.WriteString(packagname)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_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/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index d01ba5f6c..502038752 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -414,27 +414,22 @@ ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParc return result; } -//ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) -//{ -// LOGI("OnFaCallBack"); -// 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_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) -//{ -// pBaseRsp->SetErrCode(reply.ReadInt32()); -// return DM_OK; -//} +ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) +{ + LOGI("OnFaCallBack"); + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagname = pReq->GetPkgName(); + if (!data.WriteString(packagname)) { + LOGE("write pkgName failed"); + return DM_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 34fa447e4568098f166f0c1890d7c82c604e6c96 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Sat, 18 Dec 2021 20:12:43 +0800 Subject: [PATCH 038/110] to do debug foundation --- common/include/dm_constants.h | 6 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 10 +- .../kits/js/include/native_devicemanager_js.h | 3 +- .../kits/js/src/native_devicemanager_js.cpp | 45 ++++- .../authentication/auth_message_processor.h | 3 + .../authentication/auth_request_state.h | 23 ++- .../authentication/auth_response_state.h | 4 +- .../include/authentication/dm_auth_manager.h | 11 +- .../softbus/softbus_session_callback.h | 1 + .../authentication/auth_message_processor.cpp | 33 +++- .../src/authentication/auth_request_state.cpp | 36 ++-- .../authentication/auth_response_state.cpp | 20 ++- .../src/authentication/dm_auth_manager.cpp | 162 +++++++++++++++--- .../dependency/softbus/softbus_session.cpp | 99 +++++++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 8 +- utils/include/dm_random.h | 2 + 16 files changed, 371 insertions(+), 95 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 4c68324db..ad8db383b 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -22,11 +22,13 @@ namespace OHOS { namespace DistributedHardware { const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; - const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; + const std::string DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; + // const std::string DM_PKG_NAME = "com.huawei.devicemanager"; + // const std::string DM_SESSION_NAME = "com.huawei.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 DS_SO_NAME = "libdevicemanagerservice_ds_adapter.z.so"; const std::string DP_SO_NAME = "libdevicemanagerservice_dp_adapter.z.so"; const std::string CRYPTO_SO_NAME = "ibdevicemanagerservice_crypto_adapter.z.so"; 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 09cd78b2c..810c6902f 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 @@ -180,7 +180,9 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string extra = pReq->GetExtra(); + int32_t authType = pReq->GetAuthType(); DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + std::string deviceId = deviceInfo.deviceId; // DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); if (!data.WriteString(pkgName)) { @@ -191,8 +193,12 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag LOGE("write extra failed"); return DM_IPC_FLATTEN_OBJECT; } - if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { - LOGE("write deviceInfo failed"); + if (!data.WriteString(deviceId)) { + LOGE("write extra failed"); + return DM_IPC_FLATTEN_OBJECT; + } + if (!data.WriteInt32(authType)) { + LOGE("write pkgName failed"); return DM_IPC_FLATTEN_OBJECT; } // int32_t appIconLen = imageInfo.GetAppIconLen(); diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 29a525d4b..79a105dd1 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -174,8 +174,7 @@ public: 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); + 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); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index dc749a9d9..ee9f1dbd4 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -522,6 +522,41 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & info.deviceTypeId = (DmDeviceType)deviceType; } +void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &object, std::string &extra, int32_t &authType) +{ + LOGI("JsToDmExtra in."); + int32_t authTypeTemp = -1; + JsObjectToInt(env, object, "authType", authTypeTemp); + authType = authTypeTemp; + + uint8_t *appIconBufferPtr = nullptr; + int32_t appIconBufferLen = 0; + JsToDmBuffer(env, object, "appIcon", &appIconBufferPtr, appIconBufferLen); + + uint8_t *appThumbnailBufferPtr = nullptr; + int32_t appThumbnailBufferLen = 0; + JsToDmBuffer(env, object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); + + // appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); + + if (appIconBufferPtr != nullptr) { + free(appIconBufferPtr); + appIconBufferPtr = nullptr; + } + if (appThumbnailBufferPtr != nullptr) { + free(appThumbnailBufferPtr); + appThumbnailBufferPtr = nullptr; + } + + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = authType; + std::string extraInfo = "extraInfo"; + + JsToJsonObject(env, object, "extraInfo", jsonObj); + extra = jsonObj.dump(); + 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) { @@ -1162,17 +1197,17 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf JsToDmDeviceInfo(env, argv[0], deviceInfo); // DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); - char extra[20]; - JsObjectToString(env, argv[PARAM_INDEX_ONE], "extra", extra, sizeof(extra)); - std::string extraString = extra; -// JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], appImageInfo, extra, authAsyncCallbackInfo_.authType); + // char extra[20]; + // JsObjectToString(env, argv[PARAM_INDEX_ONE], "extra", extra, sizeof(extra)); + std::string extraString; + JsToDmExtra(env, argv[PARAM_INDEX_ONE], extraString, authAsyncCallbackInfo_.authType); //TODO:get real authType int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, extraString, authCallback); if (ret != 0) { LOGE("AuthenticateDevice for bundleName %s failed, ret %d", - deviceManagerWrapper->bundleName_.c_str(), ret); + deviceManagerWrapper->bundleName_.c_str(), ret); } napi_get_undefined(env, &result); return result; diff --git a/services/devicemanagerservice/include/authentication/auth_message_processor.h b/services/devicemanagerservice/include/authentication/auth_message_processor.h index 1a71a0d9d..f71610996 100644 --- a/services/devicemanagerservice/include/authentication/auth_message_processor.h +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.h @@ -33,6 +33,9 @@ public: 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(); private: std::string CreateRequestAuthMessage(nlohmann::json &json); void CreateNegotiateMessage(nlohmann::json &json); diff --git a/services/devicemanagerservice/include/authentication/auth_request_state.h b/services/devicemanagerservice/include/authentication/auth_request_state.h index b8d0569e2..f31c5ff09 100644 --- a/services/devicemanagerservice/include/authentication/auth_request_state.h +++ b/services/devicemanagerservice/include/authentication/auth_request_state.h @@ -15,75 +15,86 @@ #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() = default; + virtual ~AuthRequestState(){ + LOGE("AuthRequestState111111111111"); + }; virtual int32_t GetStateType() = 0; virtual void Enter() = 0; void Leave(); void TransitionTo(std::shared_ptr state); - void SetLastState(std::shared_ptr state); + // void SetLastState(std::shared_ptr state); void SetAuthManager(std::shared_ptr authManager); void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); protected: std::shared_ptr authManager_; - std::shared_ptr lastState_; + // std::shared_ptr lastState_; std::shared_ptr context_; }; class AuthRequestInitState : public AuthRequestState { public: + ~AuthRequestInitState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestNegotiateState : public AuthRequestState { public: + ~AuthRequestNegotiateState(){ + LOGE("AuthRequestState22222222222222222"); + }; int32_t GetStateType() override; void Enter() override; }; - class AuthRequestNegotiateDoneState : public AuthRequestState { public: + ~AuthRequestNegotiateDoneState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestReplyState : public AuthRequestState { public: + ~AuthRequestReplyState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestInputState : public AuthRequestState { public: + ~AuthRequestInputState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestJoinState : public AuthRequestState { public: + ~AuthRequestJoinState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestNetworkState : public AuthRequestState { public: + ~AuthRequestNetworkState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestFinishState : public AuthRequestState { public: + ~AuthRequestFinishState(){}; int32_t GetStateType() override; void Enter() override; }; diff --git a/services/devicemanagerservice/include/authentication/auth_response_state.h b/services/devicemanagerservice/include/authentication/auth_response_state.h index d9550fe95..a54ecb3ec 100644 --- a/services/devicemanagerservice/include/authentication/auth_response_state.h +++ b/services/devicemanagerservice/include/authentication/auth_response_state.h @@ -30,13 +30,13 @@ public: virtual void Enter() = 0; void Leave(); void TransitionTo(std::shared_ptr state); - void SetLastState(std::shared_ptr state); + // void SetLastState(std::shared_ptr state); void SetAuthManager(std::shared_ptr authManager); void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); protected: std::shared_ptr authManager_; - std::shared_ptr lastState_; + // std::shared_ptr lastState_; std::shared_ptr context_; }; diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 3785ab305..8a7db1ec9 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -89,8 +89,10 @@ typedef struct DmAuthRequestContext { } DmAuthRequestContext; typedef struct DmAuthResponseContext { + int32_t authType; std::string deviceId; int32_t msgType; + int32_t sessionId; bool cryptoSupport; std::string cryptoName; std::string cryptoVer; @@ -122,11 +124,16 @@ public: //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 JoinGroup(const std::string &deviceId); + void CreateGroup(int64_t requestId, const std::string &groupName); + void AddMember(const std::string &deviceId); void JoinNetwork(); void AuthenticateFinish(); + void GetIsCryptoSupport(bool &isCryptoSupport); + void SetAuthRequestState(std::shared_ptr authRequestState); + void SetAuthResponseState(std::shared_ptr authResponseState); private: void HandleAuthenticateTimeout(); private: @@ -141,7 +148,7 @@ private: std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; - + bool isCryptoSupport_ = false; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h index 41adf3282..0b1a48c41 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h @@ -24,6 +24,7 @@ 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 diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index b39b809c1..44d512f70 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -105,6 +105,7 @@ void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) json[TAG_CRYPTO_SUPPORT] = true; json[TAG_CRYPTO_NAME] = cryptoAdapter_->GetName(); json[TAG_CRYPTO_VERSION] = cryptoAdapter_->GetVersion(); + json[TAG_DEVICE_ID] = authRequestContext_->deviceId; } } @@ -119,6 +120,7 @@ void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) json[TAG_REPLY] = authResponseContext_->reply; json[TAG_DEVICE_ID] = authResponseContext_->deviceId; json[TAG_GROUPIDS] = authResponseContext_->deviceId; + json[PIN_CODE_KEY] = authResponseContext_->code; if (authResponseContext_->reply == 0) { json[TAG_NET_ID] = authResponseContext_->networkId; json[TAG_REQUEST_ID] = authResponseContext_->requestId; @@ -129,24 +131,34 @@ void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) 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; } //TODO::try to crypto first then parse json - if (!jsonObject.contains(TAG_INDEX) || !jsonObject.contains(TAG_DEVICE_ID) || !jsonObject.contains(TAG_SLICE_NUM)) { + LOGE(" AuthMessageProcessor ParseMessage"); + if (!jsonObject.contains(TAG_TYPE)){ LOGE("err json string, first time"); return DM_FAILED; } + int32_t sliceNum = 0; int32_t msgType = jsonObject[TAG_TYPE]; - int32_t sliceNum = jsonObject[TAG_SLICE_NUM]; authResponseContext_->msgType = msgType; + LOGE(" AuthMessageProcessor ParseMessage"); switch (msgType) { case MSG_TYPE_NEGOTIATE: + LOGE(" AuthMessageProcessor ParseMessage"); ParseNegotiateMessage(jsonObject); + LOGE(" AuthMessageProcessor ParseMessage"); 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; + } + sliceNum = jsonObject[TAG_SLICE_NUM]; if ((int32_t)authSplitJsonList_.size() < sliceNum) { authSplitJsonList_.push_back(message); } else { @@ -165,7 +177,7 @@ void AuthMessageProcessor::ParseAuthRequestMessage() authResponseContext_->deviceId = jsonObject[TAG_DEVICE_ID]; authResponseContext_->reply = jsonObject[TAG_REPLY]; // authResponseContext_->syncGroupList = jsonObject[TAG_GROUPIDS]; - + authResponseContext_->authType = jsonObject[TAG_AUTH_TYPE]; if (authResponseContext_->reply == AUTH_REPLY_ACCEPT) { authResponseContext_->networkId = jsonObject[TAG_NET_ID]; authResponseContext_->groupId = jsonObject[TAG_GROUP_ID]; @@ -190,5 +202,20 @@ void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) authResponseContext_->deviceId = json[TAG_DEVICE_ID]; } } + +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_; +} } } \ 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 index b5ceeedd0..c11e5f431 100644 --- a/services/devicemanagerservice/src/authentication/auth_request_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -17,7 +17,7 @@ #include -#include "dm_log.h" + #include "dm_constants.h" #include "dm_auth_manager.h" @@ -29,15 +29,15 @@ void AuthRequestState::Leave() { } void AuthRequestState::SetAuthManager(std::shared_ptr authManager) { - authManager_ = std::move(authManager); + authManager_ = authManager; } -void AuthRequestState::SetLastState(std::shared_ptr state) { - lastState_ = std::move(state); -} +// void AuthRequestState::SetLastState(std::shared_ptr state) { +// lastState_ = state; +// } void AuthRequestState::SetAuthContext(std::shared_ptr context) { - context_ = std::move(context); + context_ = context; } std::shared_ptr AuthRequestState::GetAuthContext() { @@ -45,14 +45,25 @@ std::shared_ptr AuthRequestState::GetAuthContext() { } void AuthRequestState::TransitionTo(std::shared_ptr state) { + LOGI("DmAuthManager::OnSessionOpened sessionId"); state->SetAuthManager(authManager_); - state->SetLastState((std::shared_ptr)this); + LOGE("DmAuthManager::EstablishAuthChannel session id"); + // state->SetLastState((std::shared_ptr)this); + // LOGE("DmAuthManager::EstablishAuthChannel session id"); + // lastState_ = state; + LOGE("DmAuthManager::EstablishAuthChannel session id"); state->SetAuthContext(context_); + LOGE("DmAuthManager::EstablishAuthChannel session id"); this->Leave(); + LOGE("DmAuthManager::EstablishAuthChannel session id"); state->Enter(); + LOGE("DmAuthManager::EstablishAuthChannel session id"); + authManager_->SetAuthRequestState(state); + LOGI("DmAuthManager::OnSessionOpened sessionId"); } int32_t AuthRequestInitState::GetStateType() { + LOGI("AuthRequestState::GetStateType22222222222 sessionId"); return AuthState::AUTH_REQUEST_INIT; } @@ -61,14 +72,17 @@ void AuthRequestInitState::Enter() { } int32_t AuthRequestNegotiateState::GetStateType() { + LOGI("AuthRequestState::GetStateType111111111 sessionId"); return AuthState::AUTH_REQUEST_NEGOTIATE; } void AuthRequestNegotiateState::Enter() { // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 -// std::string message = authMessageProcessor_->CreateMessage(MSG_TYPE_NEGOTIATE); -// softbusSession_->SendData(context_.sessionId, message); + // std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); + // softbusSession_->SendData(context_.sessionId, message); + LOGI("DmAuthManager::OnSessionOpened sessionId"); authManager_->StartNegotiate(context_->sessionId); + LOGI("DmAuthManager::OnSessionOpened sessionId"); } int32_t AuthRequestNegotiateDoneState::GetStateType() { @@ -82,7 +96,9 @@ void AuthRequestNegotiateDoneState::Enter() { // authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH); // std::string message; // softbusSession_->SendData(context_.sessionId, message); +LOGE("DmAuthManager::EstablishAuthChannel session id"); authManager_->SendAuthRequest(context_->sessionId); + LOGE("DmAuthManager::EstablishAuthChannel session id"); } int32_t AuthRequestReplyState::GetStateType() { @@ -115,7 +131,7 @@ int32_t AuthRequestJoinState::GetStateType() { void AuthRequestJoinState::Enter() { //1. 加入群组 - authManager_->JoinGroup(context_->deviceId); + authManager_->AddMember(context_->deviceId); } int32_t AuthRequestNetworkState::GetStateType() { diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp index 371376fde..44b20d9a3 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -40,18 +40,22 @@ void AuthResponseState::SetAuthManager(std::shared_ptr authManage authManager_ = authManager; } -void AuthResponseState::SetLastState(std::shared_ptr state) -{ - lastState_ = state; -} +// void AuthResponseState::SetLastState(std::shared_ptr state) +// { +// lastState_ = state; +// } void AuthResponseState::TransitionTo(std::shared_ptr state) { + LOGI("AuthRequestState:: TransitionTo"); state->SetAuthManager(authManager_); - state->SetLastState((std::shared_ptr)this); + // state->SetLastState((std::shared_ptr)this); + // lastState_ = state; state->SetAuthContext(context_); this->Leave(); state->Enter(); + authManager_->SetAuthResponseState(state); + LOGI("AuthRequestState:: TransitionTo Enter"); } int32_t AuthResponseInitState::GetStateType() @@ -61,6 +65,7 @@ int32_t AuthResponseInitState::GetStateType() void AuthResponseInitState::Enter() { + LOGI("AuthRequestState:: AuthResponseInitState Enter"); //1.认证通道建立后,进入该状态 } @@ -74,6 +79,7 @@ void AuthResponseNegotiateState::Enter() //1.收到协商消息后进入 //2. 获取本地加解密模块信息,并回复消息 + authManager_->RespNegotiate(context_->sessionId); } int32_t AuthResponseConfirmState::GetStateType() @@ -85,8 +91,8 @@ void AuthResponseConfirmState::Enter() { //委托授权UI模块进行用户交互 //如果交互成功 - -// TransitionTo(new AuthResponseGroupState()); + // TransitionTo(new AuthResponseGroupState()); + authManager_->StartAuthProcess(context_->authType); } int32_t AuthResponseGroupState::GetStateType() diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 58cec854d..ce453a903 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -20,7 +20,8 @@ #include "dm_log.h" #include "dm_constants.h" #include "auth_message_processor.h" - +#include +#include namespace OHOS { namespace DistributedHardware { @@ -29,22 +30,26 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, { LOGI("DmAuthManager constructor"); //TODO: load library so for different auth type + std::string pkgName = "com.ohos.devicemangagerdemo"; + sessionSession_->RegisterSessionCallback(pkgName, std::shared_ptr(this)); hiChainConnector_ = std::make_shared(); } DmAuthManager::~DmAuthManager() { LOGI("DmAuthManager destructor"); + LOGI("DmAuthManager destructor11111111111"); } 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; - } + // 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) { LOGE("DmAuthManager::AuthenticateDevice %s is request authentication.", authRequestState_->GetAuthContext()->hostPkgName.c_str()); return DM_AUTH_BUSINESS_BUSY; @@ -53,40 +58,44 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au LOGE("DmAuthManager::AuthenticateDevice is response authentication."); return DM_AUTH_BUSINESS_BUSY; } + sessionSession_->UnRegisterSessionCallback(pkgName); sessionSession_->RegisterSessionCallback(pkgName, std::shared_ptr(this)); hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); - std::shared_ptr requestContext = std::make_shared(); - requestContext->authType = authType; - requestContext->deviceId = deviceId; + authRequestContext_ = std::make_shared(); + 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)) { - requestContext->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY]; + authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY]; } if (jsonObject.contains(APP_NAME_KEY)) { - requestContext->appName = jsonObject[APP_NAME_KEY]; + authRequestContext_->appName = jsonObject[APP_NAME_KEY]; } if (jsonObject.contains(APP_DESCRIPTION_KEY)) { - requestContext->appDesc = jsonObject[APP_DESCRIPTION_KEY]; + authRequestContext_->appDesc = jsonObject[APP_DESCRIPTION_KEY]; } if (jsonObject.contains(APP_THUMBNAIL)) { - requestContext->appThumbnail = jsonObject[APP_THUMBNAIL]; + authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL]; } if (jsonObject.contains(APP_ICON_KEY)) { - requestContext->appIcon = jsonObject[APP_ICON_KEY]; + authRequestContext_->appIcon = jsonObject[APP_ICON_KEY]; } } authMessageProcessor_ = std::make_shared(std::shared_ptr(this)); authRequestState_ = std::shared_ptr(new AuthRequestInitState()); + LOGI("DmAuthManager::AuthenticateDevice authRequestState_ AuthRequestInitState"); authRequestState_->SetAuthManager(std::shared_ptr(this)); - authRequestState_->SetAuthContext(requestContext); + authRequestState_->SetAuthContext(authRequestContext_); + authMessageProcessor_->SetRequestContext(authRequestContext_); authRequestState_->Enter(); - + LOGI("DmAuthManager::AuthenticateDevice authRequestState_ AuthRequestInitState"); // auto authenticateStartTimer = [this]() { // HandleAuthenticateTimeout(); // }; // EventBus::PostTask(authenticateStartTimer, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT); + LOGI("DmAuthManager::AuthenticateDevice complete"); return DM_OK; } @@ -108,14 +117,25 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI LOGI("DmAuthManager::OnSessionOpened sessionId=%d result=%d", sessionId, result); if (sessionSide == AUTH_SESSION_SIDE_SERVER) { if (authResponseState_ == nullptr) { + authMessageProcessor_ = std::make_shared(std::shared_ptr(this)); authResponseState_ = std::shared_ptr(new AuthResponseInitState()); + authResponseState_->SetAuthManager(std::shared_ptr(this)); authResponseState_->Enter(); + hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); } else { //TODO:RESP_AUTH 认证失败,流程终止 } } else { + LOGI("DmAuthManager::OnSessionOpened AUTH_SESSION"); + authResponseState_ = std::shared_ptr(new AuthResponseInitState()); + authResponseState_->SetAuthManager(std::shared_ptr(this)); + authResponseState_->Enter(); + LOGI("DmAuthManager::OnSessionOpened AUTH_SESSION"); if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + authRequestContext_ ->sessionId = sessionId; + authRequestState_->SetAuthContext(authRequestContext_); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); + LOGI("DmAuthManager::OnSessionOpened sessionId"); } else { LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType()); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); @@ -130,18 +150,32 @@ void DmAuthManager::OnSessionClosed(const std::string &pkgName, int32_t sessionI void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message) { + LOGI("DmAuthManager::OnDataReceived complete1"); + if (authResponseState_ == nullptr) { + LOGI("DmAuthManager::authResponseState_ ============"); + } + authResponseContext_ = std::make_shared(); + authResponseContext_ ->sessionId = sessionId; + authResponseState_->SetAuthContext(authResponseContext_); + authMessageProcessor_->SetResponseContext(authResponseContext_); int32_t ret = authMessageProcessor_->ParseMessage(message); if (ret != DM_OK) { LOGE("OnDataReceived, parse message error"); return; } + authResponseContext_ = authMessageProcessor_->GetResponseContext(); + authResponseState_->SetAuthContext(authResponseContext_); + LOGI("DmAuthManager::OnDataReceived complete666666666"); switch (authResponseContext_->msgType) { case MSG_TYPE_NEGOTIATE: + LOGI("DmAuthManager::OnDataReceived complete77777777777"); if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { + LOGI("DmAuthManager::OnDataReceived complete==========="); authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); } else { //状态错误,流程终止 } + LOGI("DmAuthManager::OnDataReceived complete"); break; case MSG_TYPE_REQ_AUTH: //检查状态机状态 @@ -162,8 +196,11 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId } break; case MSG_TYPE_RESP_NEGOTIATE: + LOGI("DmAuthManager::OnDataReceived complete111111111111"); if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) { + LOGI("DmAuthManager::OnDataReceived complete72222222222222222222"); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateDoneState())); + LOGI("DmAuthManager::OnDataReceived complete72222222222222222222"); } else { //状态错误,流程终止 } @@ -177,6 +214,9 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId { //创建群组成功 //发送认证响应消息给请求端 + int32_t pinCode = 123456; + authResponseContext_->code = pinCode; + authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); softbusConnector_->GetSoftbusSession()->SendData(authRequestContext_->sessionId, message); } @@ -196,8 +236,9 @@ void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) { //TODO:检查crypto模块是否适配 //TODO:兼容性处理,兼容与手机的认证 - int32_t ret = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); - if (ret != DM_OK) { + LOGE("DmAuthManager::EstablishAuthChannel is"); + int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + if (sessionId < 0) { LOGE("OpenAuthSession failed, stop the authentication"); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } @@ -205,14 +246,44 @@ void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) void DmAuthManager::StartNegotiate(const int32_t &sessionId) { + LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); //TODO::设置消息等待超时时间 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } +void DmAuthManager::RespNegotiate(const int32_t &sessionId) +{ + LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); + 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); +} + void DmAuthManager::SendAuthRequest(const int32_t &sessionId) { + LOGE("DmAuthManager::EstablishAuthChannel session id"); + if (authResponseContext_->cryptoSupport == true){ + isCryptoSupport_ = true; + } + LOGE("DmAuthManager::EstablishAuthChannel session id"); std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); + LOGE("DmAuthManager::EstablishAuthChannel session id"); //TODO::设置消息等待超时时间 for (auto msg : messageList) { softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); @@ -224,12 +295,19 @@ void DmAuthManager::StartAuthProcess(const int32_t &authType) //1. 收到请求响应,判断用户响应结果 //2. 用户授权同意 //3. 回调给认证实现模块,启动认证 - std::shared_ptr authentication = authenticationMap_[authType]; - authentication->StartAuth(); + // std::shared_ptr authentication = authenticationMap_[authType]; + // authentication->StartAuth(); + std::string groupName = "1234567890"; + CreateGroup(authResponseContext_->requestId, groupName); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestInputState())); } -void DmAuthManager::JoinGroup(const std::string &deviceId) +void DmAuthManager::CreateGroup(int64_t requestId, const std::string &groupName) +{ + hiChainConnector_->CreateGroup(requestId, groupName); +} + +void DmAuthManager::AddMember(const std::string &deviceId) { // hiChainConnector_->AddMember(deviceId); } @@ -244,5 +322,47 @@ void DmAuthManager::AuthenticateFinish() //清理资源,关闭通道 softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); } + +void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) +{ + LOGE("DmAuthManager::GetIsCryptoSupport 111111"); + if (authResponseState_ == nullptr){ + LOGE("DmAuthManager::GetIsCryptoSupport 12222222222222"); + isCryptoSupport = false; + return; + } + LOGE("DmAuthManager::GetIsCryptoSupport 333333333"); + if (authRequestState_ == nullptr){ + LOGE("DmAuthManager::GetIsCryptoSupport44444444"); + if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE){ + LOGE("DmAuthManager::GetIsCryptoSupport 5555555555"); + isCryptoSupport = false; + return; + } + }else { + LOGE("DmAuthManager::GetIsCryptoSupport 6666666666"); + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE){ + LOGE("DmAuthManager::GetIsCryptoSupport 777777777777"); + isCryptoSupport = false; + return; + } + } + + LOGE("DmAuthManager::GetIsCryptoSupport 88888888888888"); + isCryptoSupport = isCryptoSupport_; +} + +void DmAuthManager::SetAuthRequestState(std::shared_ptr authRequestState) +{ + LOGE("DmAuthManager::SetAuthRequestState======= "); + authRequestState_ = authRequestState; +} + +void DmAuthManager::SetAuthResponseState(std::shared_ptr authResponseState) +{ + LOGE("DmAuthManager::SetAuthResponseState=========== "); + authResponseState_ = authResponseState; +} } } \ 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 index 45ca18143..d18822de5 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -18,7 +18,7 @@ #include "dm_constants.h" #include "dm_log.h" #include "dm_anonymous.h" - +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { @@ -37,6 +37,8 @@ SoftbusSession::SoftbusSession() 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"); } } @@ -99,21 +101,44 @@ void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) { LOGE("SendData Start"); - uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MSG_MAX_SIZE + ENCRYPT_TAG_LEN)); - if (buf == nullptr) { - LOGE("SendData: malloc memory failed"); - return DM_MALLOC_ERROR; + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("extrasJson error"); + return DM_FAILED; + } + bool isCryptoSupport = false; + LOGE("SendData Start"); + for (auto & iter : sessionCallbackMap_) { + LOGE("SendData Start1"); + iter.second->GetIsCryptoSupport(isCryptoSupport); + LOGE("SendData Start2"); + } + LOGE("SendData Start"); + if (isCryptoSupport) { + uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MSG_MAX_SIZE + ENCRYPT_TAG_LEN)); + if (buf == nullptr) { + LOGE("SendData: malloc memory failed"); + return DM_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 != DM_OK || outLen > MSG_MAX_SIZE) { + // LOGE("MbedtlsEncrypt data failed"); + // free(buf); + // return ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; + // } + // int32_t ret = SendBytes(sessionId, buf, strlen(buf)); + free(buf); } -// int32_t outLen = 0; -// int32_t ret = EncryptUtils::MbedtlsEncrypt((const uint8_t *)message.c_str(), message.size(), buf, MSG_MAX_SIZE, -// &outLen); -// if (ret != DM_OK || outLen > MSG_MAX_SIZE) { -// LOGE("MbedtlsEncrypt data failed"); -// free(buf); -// return ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; -// } -// int32_t ret = SendBytes(sessionId, buf, strlen(buf)); - free(buf); + LOGE("SendData Start"); + 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; } @@ -123,6 +148,7 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) for (auto & iter : sessionCallbackMap_) { iter.second->OnSessionOpened(iter.first, sessionId, sessionSide, result); } + LOGI("OnSessionOpened, success:"); return DM_OK; } @@ -141,24 +167,39 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 LOGI("OnBytesReceived param check failed"); return; } - uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); - if (buf == nullptr) { - LOGE("SendMsg: malloc memory failed"); - return; + bool isCryptoSupport = false; + for (auto & iter : sessionCallbackMap_) { + iter.second->GetIsCryptoSupport(isCryptoSupport); + } + if (isCryptoSupport){ + LOGI("OnBytesReceived completed111111111"); + uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); + if (buf == nullptr) { + LOGE("SendMsg: malloc memory failed"); + return; + } + // int32_t outLen = 0; + // int32_t ret = EncryptUtils::MbedtlsDecrypt((const uint8_t*)data, dataLen, buf, dataLen, &outLen); + // if (ret != DM_OK || outLen > (int32_t)dataLen) { + // LOGE("MbedtlsDecrypt data failed"); + // free(buf); + // return; + // } + std::string message = (char *)buf; + for (auto & iter : sessionCallbackMap_) { + iter.second->OnDataReceived(iter.first, sessionId, message); + } + free(buf); } -// int32_t outLen = 0; -// int32_t ret = EncryptUtils::MbedtlsDecrypt((const uint8_t*)data, dataLen, buf, dataLen, &outLen); -// if (ret != DM_OK || outLen > (int32_t)dataLen) { -// LOGE("MbedtlsDecrypt data failed"); -// free(buf); -// return; -// } - std::string message = (char *)buf; + LOGI("OnBytesReceived completed22222222"); + char *dataChar = (char *)data; + std::string message = dataChar; + LOGI("OnBytesReceived completed33333333333"); for (auto & iter : sessionCallbackMap_) { + LOGI("OnBytesReceived completed4444444444"); iter.second->OnDataReceived(iter.first, sessionId, message); } - free(buf); - LOGI("OnBytesReceived completed"); + LOGI("OnBytesReceived completed5555555555"); } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index d6e4384ce..ef5174fcb 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -274,15 +274,15 @@ ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) std::string extra = data.ReadString(); std::string deviceId = data.ReadString();; int32_t authType = data.ReadInt32(); - DmDeviceInfo *deviceInfo = (DmDeviceInfo *)data.ReadRawData(sizeof(DmDeviceInfo)); int32_t result = DM_OK; - if (deviceInfo != nullptr) { - result = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, nullptr, extra); - } + + 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; } diff --git a/utils/include/dm_random.h b/utils/include/dm_random.h index 835be8bc8..92ea87523 100644 --- a/utils/include/dm_random.h +++ b/utils/include/dm_random.h @@ -22,6 +22,8 @@ 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 -- Gitee From 47649499465759dd64d93e0c5147ecb0bee1f291 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Sun, 19 Dec 2021 12:56:17 +0800 Subject: [PATCH 039/110] 1:add GetTrustedDeviceListSync();2:change GetTrustedDeviceList();: --- .../kits/js/include/native_devicemanager_js.h | 1 + .../kits/js/src/native_devicemanager_js.cpp | 61 ++++++++++++++++++- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 79a105dd1..00e077818 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -140,6 +140,7 @@ public: 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 UnAuthenticateDevice(napi_env env, napi_callback_info info); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index ee9f1dbd4..1d1b4e8c4 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -985,6 +985,38 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in } } +napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callback_info info) +{ + LOGI("GetTrustedDeviceListSync in"); + napi_value result = nullptr; + napi_value thisVar = nullptr; + DmDeviceInfo deviceInfo; + LOGI("DeviceManager::GetTrustedDeviceListSync 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 == 1, "Wrong number of arguments"); + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + std::string extra = ""; + std::vector devList; + int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceManagerWrapper->bundleName_, extra, devList); + if (ret != 0) { + LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); + return result; + } + LOGI("DeviceManager::GetTrustedDeviceListSync"); + if (devList.size() > 0) + { + for (size_t i= 0; i != devList.size(); ++i) + { + DeviceInfoToJsArray(env, devList, i, result); + } + } + return result; +} + napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_info info) { LOGI("GetTrustedDeviceList in"); @@ -1018,19 +1050,42 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); return promise; } else if (argc == 1) { - return CallDeviceList(env, info, deviceInfoAsyncCallbackInfo); + GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + if(valueType == napi_string)//getTrustedDeviceList(extra: string): Promise>; + { + char extra[32]; + JsObjectToString(env, argv[0], "extra", extra, sizeof(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(valueType == napi_function) + { + return CallDeviceList(env, info, deviceInfoAsyncCallbackInfo); + } + else + { + NAPI_ASSERT(env, true, "Wrong argument type, string or function expected."); + } } else if (argc == 2) { // DmFilterOptions filterOptions; GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); napi_valuetype valueType; napi_typeof(env, argv[0], &valueType); - NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); + LOGE("GetLocalDeviceInfo 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("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); NAPI_ASSERT(env, eventHandleType == napi_function, "Wrong argument type. Object expected."); - LOGE("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); // JsToDmFilterOptions(env, argv[0], filterOptions); // deviceInfoAsyncCallbackInfo->filter = filterOptions; char extra[20]; -- Gitee From c46e61eab3d38ea0c1112d50eec29c7853d39c65 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sun, 19 Dec 2021 15:45:02 +0800 Subject: [PATCH 040/110] =?UTF-8?q?=E9=BB=98=E8=AE=A4=E5=BC=80=E5=90=AF?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E8=A2=AB=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependency/softbus/softbus_connector.cpp | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 7a72df241..1cfd84c89 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -102,19 +102,24 @@ int32_t SoftbusConnector::Init() LOGI("RegNodeDeviceStateCb success."); // TODO:check system properties first + 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_OFF.c_str()); + 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_); + LOGI("service publish result is : %d", ret); } else if (ret >= 0 && strcmp(discoverStatus, DISCOVER_STATUS_ON.c_str()) == 0) { - 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(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); LOGI("service publish result is : %d", ret); } else if (ret >= 0 && strcmp(discoverStatus, DISCOVER_STATUS_OFF.c_str()) == 0) { -- Gitee From acc67ee7ef2a05077f7e99969c2e64234cf44858 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sun, 19 Dec 2021 17:13:45 +0800 Subject: [PATCH 041/110] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E8=B0=83=E7=94=A8?= =?UTF-8?q?=E6=9D=83=E9=99=90=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- interfaces/inner_kits/native_cpp/BUILD.gn | 3 ++ .../native_cpp/src/device_manager_impl.cpp | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 1afa35af8..2beccda7a 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -82,6 +82,9 @@ if (defined(ohos_lite)) { "//third_party/json/include", "//utils/native/base/include", "//utils/system/safwk/native/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + ] sources = [ 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 6cc2428cf..d0a801819 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -30,8 +30,36 @@ #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" +#include "bundle_info.h" +#include "ipc_skeleton.h" +#include "bundle_constants.h" +#include "bundle_mgr_client.h" + +using namespace OHOS::AppExecFwk; +using namespace OHOS::AppExecFwk::Constants; + namespace OHOS { namespace DistributedHardware { +bool isSystemAppCalling(void) +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + if (uid >= ROOT_UID && uid < BASE_SYS_UID) { + LOGE("check permission true for system uid %d", uid); + return true; + } + + std::string bundleName; + BundleMgrClient bundleMgrClient; + bool ret = bundleMgrClient.GetBundleNameForUid(uid, bundleName); + if (ret) { + return false; + } + + BundleInfo bundleInfo; + ret = bundleMgrClient.GetBundleInfo(bundleName, BundleFlag::GET_APPLICATION_INFO_WITH_PERMISSION, bundleInfo); + return (ret && bundleInfo.applicationInfo.isSystemApp); +} + DeviceManagerImpl & DeviceManagerImpl::GetInstance() { static DeviceManagerImpl instance; -- Gitee From 879b3f6bf60110df7a8f913a96d8e95c08a981e1 Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Mon, 20 Dec 2021 19:24:49 +0800 Subject: [PATCH 042/110] =?UTF-8?q?=E5=9B=9E=E8=B0=83=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 1 + .../ipc/model/ipc_notify_dmfa_result_req.h | 42 +++++ ext/pin_auth/src/pin_auth_ui.cpp | 6 +- .../native_cpp/include/device_manager.h | 1 + .../include/device_manager_callback.h | 5 + .../native_cpp/include/device_manager_impl.h | 2 + .../include/notify/device_manager_notify.h | 2 + .../src/ipc/lite/ipc_cmd_parser.cpp | 2 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 2 +- .../src/notify/device_manager_notify.cpp | 11 ++ .../kits/js/include/native_devicemanager_js.h | 10 ++ .../kits/js/src/native_devicemanager_js.cpp | 19 +++ .../include/authentication/dm_auth_manager.h | 10 ++ .../include/device_manager_service_listener.h | 2 + .../include/timer/dm_timer.h | 72 +++++++++ .../src/authentication/auth_ui.cpp | 4 +- .../src/authentication/dm_auth_manager.cpp | 11 +- .../src/device_manager_service_listener.cpp | 11 ++ .../src/ipc/lite/ipc_cmd_parser.cpp | 9 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 8 +- .../src/timer/dm_timer.cpp | 153 ++++++++++++++++++ 21 files changed, 366 insertions(+), 17 deletions(-) create mode 100644 common/include/ipc/model/ipc_notify_dmfa_result_req.h create mode 100644 services/devicemanagerservice/include/timer/dm_timer.h create mode 100644 services/devicemanagerservice/src/timer/dm_timer.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index f1a869d2c..e08976b72 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -119,6 +119,7 @@ namespace DistributedHardware { 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; diff --git a/common/include/ipc/model/ipc_notify_dmfa_result_req.h b/common/include/ipc/model/ipc_notify_dmfa_result_req.h new file mode 100644 index 000000000..e6012aa7a --- /dev/null +++ b/common/include/ipc/model/ipc_notify_dmfa_result_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_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); +public: + std::string GetJsonParam() const + { + return JsonParam_; + } + + void SetJsonParam(std::string& JsonParam) + { + JsonParam_ = JsonParam; + } +private: + std::string JsonParam_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_AUTH_RESULT_REQ_H diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index 6a285beda..b2e72f079 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -28,16 +28,16 @@ PinAuthUi::PinAuthUi() int32_t PinAuthUi::ShowPinDialog() { - LOGI("RequestSession::StartFaService in"); + LOGI("PinAuthUi::StartFaService in"); return SUCCESS; } int32_t PinAuthUi::InputPinDialog() { - LOGI("RequestSession::StartFaService in"); + LOGI("PinAuthUi::StartFaService in"); AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { - LOGE("RequestSession::StartFaService timeout"); + LOGE("PinAuthUi::StartFaService timeout"); return FAIL; } return SUCCESS; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index c80a4ab15..0ed551aca 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -23,6 +23,7 @@ #include "device_manager_callback.h" #include "dm_subscribe_info.h" #include "dm_device_info.h" +#include "ipc_notify_dmfa_result_req.h" namespace OHOS { namespace DistributedHardware { 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 2892970c3..e96c9e582 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -57,6 +57,11 @@ public: 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; +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_CALLBACK_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 629544ef2..47833d418 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -20,6 +20,7 @@ #include "ipc_client_proxy.h" #include "ipc_client_manager.h" #include "dm_device_info.h" +#include "ipc_server_listener.h" namespace OHOS { namespace DistributedHardware { @@ -56,6 +57,7 @@ private: private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); + IpcServerListener ipcServerListener_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 0dc82bfd6..e1986e3ee 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 @@ -56,6 +56,7 @@ public: 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_; @@ -63,6 +64,7 @@ private: std::map>> authenticateCallback_; std::map> verifyAuthCallback_; std::map> dmInitCallback_; + std::map> dmFaCallback_; }; } // 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 6d2ad25e2..cb938c55a 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 @@ -371,7 +371,7 @@ ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) std::string packagename = (const char *)IpcIoPopString(&reply, &len); size_t jsonLen = 0; std::string paramJson = (const char *)IpcIoPopString(&reply, &jsonLen); -// DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); + DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); } } // 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 cd5229070..ffb4bf5a4 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 @@ -445,7 +445,7 @@ ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel &data, MessageParcel &r std::string paramJson = data.ReadString(); LOGI("OnFaCallBack Packagename is %s", packagename.c_str()); LOGI("OnFaCallBack Json is %s", paramJson.c_str()); - // DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); + DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); if (!reply.WriteInt32(DM_OK)) { LOGE("write return failed"); 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 28e2f8db5..cc07e51a4 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 @@ -249,5 +249,16 @@ void DeviceManagerNotify::OnVerifyAuthResult(const std::string &pkgName, const s verifyAuthCallback_[pkgName]->OnVerifyAuthResult(deviceId, resultCode, flag); verifyAuthCallback_.erase(pkgName); } + +void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) +{ + LOGI("DeviceManager OnFaCallback pkgName:%s", pkgName.c_str()); + std::lock_guard autoLock(lock_); + if (dmFaCallback_.count(pkgName) == 0) { + LOGE("DeviceManager DmFaCallback not register"); + return; + } + dmFaCallback_[pkgName]->OnCall(paramJson); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 3b29cfdd4..9747640f4 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -110,6 +110,16 @@ private: std::string bundleName_; }; +class DmNapiDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceManagerFaCallback { +public: + explicit DmNapiDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmNapiDeviceManagerFaCallback() {}; + void OnCall(std::string ¶mJson) override; + +private: + std::string bundleName_; +}; + class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { public: explicit DmNapiAuthenticateCallback(std::string &bundleName) : bundleName_(bundleName) {} diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index b556a7254..bafa02afa 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -811,6 +811,25 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_st } } +void DmNapiDeviceManagerFaCallback::OnCall(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); +} + +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) { diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 8a929bda5..7041fd114 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -30,6 +30,7 @@ #include "auth_request_state.h" #include "auth_response_state.h" #include "auth_message_processor.h" +#include "dm_timer.h" namespace OHOS { namespace DistributedHardware { @@ -37,6 +38,14 @@ namespace DistributedHardware { const std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; const int32_t AUTHENTICATE_TIMEOUT = 120; +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; +} + typedef enum AuthState { AUTH_REQUEST_INIT = 1, AUTH_REQUEST_NEGOTIATE, @@ -150,6 +159,7 @@ private: std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; + std::shared_ptr mMemberJoinTimerPtr_; }; diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index 8851ed98b..d54f218cd 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -20,6 +20,7 @@ #include "dm_device_info.h" #include "ipc_server_listener.h" +#include "ipc_notify_dmfa_result_req.h" namespace OHOS { namespace DistributedHardware { @@ -31,6 +32,7 @@ public: 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_; }; diff --git a/services/devicemanagerservice/include/timer/dm_timer.h b/services/devicemanagerservice/include/timer/dm_timer.h new file mode 100644 index 000000000..ea52ce137 --- /dev/null +++ b/services/devicemanagerservice/include/timer/dm_timer.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 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/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp index a2c68b155..13411169c 100644 --- a/services/devicemanagerservice/src/authentication/auth_ui.cpp +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -28,10 +28,10 @@ AuthUi::AuthUi() int32_t AuthUi::ShowConfirmDialog() { - LOGI("RequestSession::StartFaService in"); + LOGI("AuthUi::StartFaService in"); AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { - LOGE("RequestSession::StartFaService timeout"); + LOGE("AuthUi::StartFaService timeout"); return FAIL; } return SUCCESS; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 4fd5e38fb..fed75695e 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -187,6 +187,7 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) // authRequestState_->TransitionTo(new AuthRequestNetworkState()); // } CancelDisplay(); + mMemberJoinTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT); } void DmAuthManager::HandleAuthenticateTimeout() { @@ -317,11 +318,13 @@ void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) void DmAuthManager::CancelDisplay() { LOGI("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"; - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - ipcServerListener_.SendRequest(SERVER_DEVICEMANAGER_FA_NOTIFY, req, rsp); + DeviceManagerServiceListener::GetInstance().OnFaCall(pkgName, paramJson); + LOGI("Cancel PinCode Display success"); + } } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 26ce7cb6f..09735e653 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -105,5 +105,16 @@ void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName // pReq->SetFlag(flag); 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_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 index 7e9cd5e58..3eef5882b 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -278,12 +278,11 @@ ON_IPC_SERVER_CMD(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo &req, IpcIo &reply) 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::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string packagname = pReq->GetPkgName(); - if (!data.WriteString(packagname)) { - LOGE("write pkgName failed"); - return DM_FLATTEN_OBJECT; - } + std::string paramJson = pReq->GetJsonParam(); + IpcIoPushString(&request, packagname.c_str()); + IpcIoPushString(&request, paramJson.c_str()); return DM_OK; } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 502038752..92ec6564e 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -417,12 +417,18 @@ ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParc ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) { LOGI("OnFaCallBack"); - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + 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; } diff --git a/services/devicemanagerservice/src/timer/dm_timer.cpp b/services/devicemanagerservice/src/timer/dm_timer.cpp new file mode 100644 index 000000000..90c8f1b8b --- /dev/null +++ b/services/devicemanagerservice/src/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::WiteforTimeout, 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::WiteforTimeout() +{ + 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) { + LOGE("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; +} +} +} -- Gitee From e20f434543aa50d7eba1770d4f8ae568c8ca8221 Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Mon, 20 Dec 2021 21:06:18 +0800 Subject: [PATCH 043/110] =?UTF-8?q?=E9=80=BB=E8=BE=91=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ext/pin_auth/src/pin_auth_ui.cpp | 1 - .../native_cpp/src/device_manager_impl.cpp | 2 +- .../include/authentication/dm_auth_manager.h | 3 + .../src/authentication/dm_auth_manager.cpp | 110 ++++++++++++++++-- utils/include/cipher/encrypt_utils.h | 65 +++++++++++ 5 files changed, 169 insertions(+), 12 deletions(-) create mode 100644 utils/include/cipher/encrypt_utils.h diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index b2e72f079..44c12a64f 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -15,7 +15,6 @@ #include "pin_auth_ui.h" #include "dm_ability_manager.h" -#include "dm_log.h" #include "dm_constants.h" namespace OHOS { diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 48055a281..30c27e4ef 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -316,7 +316,7 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &faParam) { - LOGI("DeviceManager::GetAuthenticationParam start"); + LOGI("DeviceManagerImpl::GetFaParam start"); if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INVALID_VALUE; diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 7041fd114..4a2661bd7 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -160,6 +160,9 @@ private: std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; std::shared_ptr mMemberJoinTimerPtr_; + int32_t mPincode_; + std::string mGroupId_; + std::string mGroupName_; }; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index fed75695e..c0be0ced8 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -20,6 +20,7 @@ #include "dm_log.h" #include "dm_constants.h" #include "auth_message_processor.h" +#include "encrypt_utils.h" namespace OHOS { namespace DistributedHardware { @@ -30,6 +31,7 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, LOGI("DmAuthManager constructor"); //TODO: load library so for different auth type hiChainConnector_ = std::make_shared(); + mPincode_ = -1; } DmAuthManager::~DmAuthManager() @@ -106,6 +108,7 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const st 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); + mPincode_ = GeneratePincode(); if (sessionSide == AUTH_SESSION_SIDE_SERVER) { if (authResponseState_ == nullptr) { authResponseState_ = std::shared_ptr(new AuthResponseInitState()); @@ -263,7 +266,7 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) } authParam.authType = AUTH_TYPE_PIN; // Currently, only Support PinCode, authType not save. authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole(); - authParam.pinToken = DmAuthRequestContext::token; + authParam.pinToken = authRequestContext_->token; LOGI("GetAuthenticationParam, role is ABILITY_ROLE_INITIATIVE"); return SUCCESS; } @@ -284,10 +287,7 @@ void DmAuthManager::OnUserOperate(int32_t action) LOGE("authRequestState_ not exist"); return; } - if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { - SoftbusSession::GetInstance().CloseAuthSession(DmAuthRequestContext::sessionId); - return; - } + OnUserReqSessionOperate(action) return; } @@ -295,7 +295,92 @@ void DmAuthManager::OnUserOperate(int32_t action) LOGE("authResponseState_ not exist"); return; } + OnUserRespSessionOperate(action) + +} + +void DmAuthManager::OnUserReqSessionOperate(int32_t action) +{ + if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { + ReqSessionRelease(); + return; + } +} + +void DmAuthManager::ReqSessionRelease() +{ + if (mStatus_ == StatusType::STATUS_FINISH || mStatus_ == StatusType::STATUS_INIT) { + LOGI("session is already closed"); + return; + } + LOGI("close this session"); + mStatus_ = StatusType::STATUS_FINISH; + SoftbusSession::GetInstance().CloseAuthSession(authRequestContext_->sessionId); + LOGI("RequestSession:: close the channel"); +} + +void DmAuthManager::OnUserRespSessionOperate(int32_t action) +{ + switch (action) { + case FaAction::USER_OPERATION_TYPE_ALLOW_AUTH: { + OnUserConfirm(); + break; + } + case FaAction::USER_OPERATION_TYPE_CANCEL_AUTH: { + LOGI("cancle pincode display"); + Release(); + break; + } + case FaAction::USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: { + LOGI("cancle pincode display"); + Release(); + break; + } + case FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: { + LOGI("cancle pincode display"); + Release(); + break; + } + default: { + LOGI("action %d not support", action); + break; + } + } +} + + +void DmAuthManager::Release() +{ + LOGI("ResponseSession::Release in"); + mGroupId_ = ""; + mGroupName_ = ""; + mPincode_ = -1; +} + +void DmAuthManager::OnUserConfirm() +{ + LOGI("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(); + return; + } + UpdateDmFaType(DmFaType::FA_TYPE_UNKNOWN); +} +std::string DmAuthManager::GenerateGroupName() +{ + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string sLocalDeviceID = localDeviceId; + std::string groupName = authRequestContext_->targetPkgName + authRequestContext_->hostPkgName + + sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); + return groupName; } void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) @@ -307,12 +392,12 @@ void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) return; } - authParam.packageName = DmAuthRequestContext::targetPkgName; - authParam.appName = DmAuthRequestContext::appName; - authParam.appDescription = DmAuthRequestContext::appDesc; - authParam.authType = DmAuthRequestContext::authType; + authParam.packageName = authRequestContext_->targetPkgName; + authParam.appName = authRequestContext_->appName; + authParam.appDescription = authRequestContext_->appDesc; + authParam.authType = authRequestContext_->authType; authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION - authParam.pincode = DmAuthResponseContext::code;//获取生成的pincode + authParam.pincode = mPincode_;//获取生成的pincode } void DmAuthManager::CancelDisplay() @@ -326,5 +411,10 @@ void DmAuthManager::CancelDisplay() LOGI("Cancel PinCode Display success"); } + +int32_t DmAuthManager::GeneratePincode() +{ + return EncryptUtils::GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); +} } } \ No newline at end of file diff --git a/utils/include/cipher/encrypt_utils.h b/utils/include/cipher/encrypt_utils.h new file mode 100644 index 000000000..f55c027b7 --- /dev/null +++ b/utils/include/cipher/encrypt_utils.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_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); +private: + typedef struct DmCryptInfo { + const uint8_t *sessionkey; + int32_t sessionkeyLen; + const uint8_t *iv; + int32_t ivLen; + } DmCryptInfo; + + static void MbedtlsGenRootKey(uint8_t *szOut, int32_t szOutLen, int32_t *nOutLen); + static int32_t MbedtlsAesGcmDecrypt(DmCryptInfo *info, const uint8_t *cipherText, + uint32_t cipherTextSize, uint8_t *plain, uint32_t plainLen); + static int32_t MbedtlsAesGcmEncrypt(DmCryptInfo *info, const uint8_t *plainText, + uint32_t plainTextSize, uint8_t *cipherText, uint32_t cipherTextLen); + static void XORBlock(uint8_t *output, const uint8_t *input1, + const uint8_t *input2, const size_t block_size); + static void ByteRightMove(uint8_t *data, size_t dataLen, const uint8_t *inputData, int32_t len, + int32_t count); + static void ByteLeftMove(uint8_t *data, size_t dataLen, const uint8_t *inputData, int32_t len, + int32_t count); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H \ No newline at end of file -- Gitee From 0a2f01baf2c68a7e9c0891cc1ef0628a5adaf0b1 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Tue, 21 Dec 2021 13:31:06 +0800 Subject: [PATCH 044/110] finsh foundations --- common/include/dm_constants.h | 10 +- interfaces/inner_kits/native_cpp/BUILD.gn | 1 - .../native_cpp/src/device_manager_impl.cpp | 1 + .../authentication/auth_message_processor.h | 1 + .../authentication/auth_request_state.h | 14 +-- .../include/authentication/dm_auth_manager.h | 3 + .../dependency/hichain/hichain_connector.h | 12 +- .../hichain/hichain_connector_callback.h | 2 + .../dependency/softbus/softbus_connector.h | 2 +- .../authentication/auth_message_processor.cpp | 45 ++++++- .../src/authentication/auth_request_state.cpp | 34 ++---- .../authentication/auth_response_state.cpp | 9 +- .../src/authentication/dm_auth_manager.cpp | 106 ++++++++++------- .../dependency/hichain/hichain_connector.cpp | 110 +++++++++--------- .../dependency/softbus/softbus_connector.cpp | 16 ++- .../dependency/softbus/softbus_session.cpp | 10 +- .../devicestate/dm_device_state_manager.cpp | 4 +- 17 files changed, 212 insertions(+), 168 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index ad8db383b..4c5872cb0 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -92,7 +92,7 @@ namespace DistributedHardware { 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_ID = "groupId"; const std::string TAG_GROUP_NAME = "GROUPNAME"; const std::string TAG_REQUEST_ID = "REQUESTID"; const std::string TAG_DEVICE_ID = "DEVICEID"; @@ -149,6 +149,14 @@ namespace DistributedHardware { 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"; + const int32_t FAIL = -1; } } #endif diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 2beccda7a..339abe9fe 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -84,7 +84,6 @@ if (defined(ohos_lite)) { "//utils/system/safwk/native/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", - ] sources = [ 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 d0a801819..6b4ed4ca3 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -40,6 +40,7 @@ using namespace OHOS::AppExecFwk::Constants; namespace OHOS { namespace DistributedHardware { + bool isSystemAppCalling(void) { int32_t uid = IPCSkeleton::GetCallingUid(); diff --git a/services/devicemanagerservice/include/authentication/auth_message_processor.h b/services/devicemanagerservice/include/authentication/auth_message_processor.h index f71610996..012863cc7 100644 --- a/services/devicemanagerservice/include/authentication/auth_message_processor.h +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.h @@ -41,6 +41,7 @@ private: 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); private: diff --git a/services/devicemanagerservice/include/authentication/auth_request_state.h b/services/devicemanagerservice/include/authentication/auth_request_state.h index f31c5ff09..b3eaf8208 100644 --- a/services/devicemanagerservice/include/authentication/auth_request_state.h +++ b/services/devicemanagerservice/include/authentication/auth_request_state.h @@ -25,9 +25,7 @@ class DmAuthManager; struct DmAuthRequestContext; class AuthRequestState : public std::enable_shared_from_this{ public: - virtual ~AuthRequestState(){ - LOGE("AuthRequestState111111111111"); - }; + virtual ~AuthRequestState() = default; virtual int32_t GetStateType() = 0; virtual void Enter() = 0; void Leave(); @@ -44,57 +42,47 @@ protected: class AuthRequestInitState : public AuthRequestState { public: - ~AuthRequestInitState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestNegotiateState : public AuthRequestState { public: - ~AuthRequestNegotiateState(){ - LOGE("AuthRequestState22222222222222222"); - }; int32_t GetStateType() override; void Enter() override; }; class AuthRequestNegotiateDoneState : public AuthRequestState { public: - ~AuthRequestNegotiateDoneState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestReplyState : public AuthRequestState { public: - ~AuthRequestReplyState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestInputState : public AuthRequestState { public: - ~AuthRequestInputState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestJoinState : public AuthRequestState { public: - ~AuthRequestJoinState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestNetworkState : public AuthRequestState { public: - ~AuthRequestNetworkState(){}; int32_t GetStateType() override; void Enter() override; }; class AuthRequestFinishState : public AuthRequestState { public: - ~AuthRequestFinishState(){}; int32_t GetStateType() override; void Enter() override; }; diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 8a7db1ec9..18d6d6bed 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -127,13 +127,16 @@ public: void RespNegotiate(const int32_t &sessionId); void SendAuthRequest(const int32_t &sessionId); void StartAuthProcess(const int32_t &authType); + void StartRespAuthProcess(); void CreateGroup(int64_t requestId, const std::string &groupName); 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(); private: void HandleAuthenticateTimeout(); private: diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index ce68ec7c0..de383c418 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -29,14 +29,6 @@ namespace OHOS { namespace DistributedHardware { -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"; - struct GroupInfo { std::string groupName; std::string groupId; @@ -61,7 +53,7 @@ public: 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 AddMember(std::string deviceId, std::string &connectInfo); int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); private: @@ -70,7 +62,7 @@ private: 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::shared_ptr msgResponseAuth); + std::string GetConnectPara(std::string deviceId, std::string reqDeviceId); bool IsGroupCreated(std::string groupName, GroupInfo &groupInfo); bool IsGroupInfoInvalid(GroupInfo &group); private: diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h index b3b7be6e9..1e0bac7aa 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h @@ -23,6 +23,8 @@ 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 diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index eca99fb91..b2e54a9d1 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -42,7 +42,7 @@ public: static void OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason); static void OnSoftbusDiscoverySuccess(int32_t subscribeId); static int32_t GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress); - static ConnectionAddr *GetConnectAddr(const std::string &deviceId); + static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); static bool IsDeviceOnLine(const std::string &deviceId); public: SoftbusConnector(); diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index 44d512f70..eb7e816df 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -117,15 +117,26 @@ void AuthMessageProcessor::CreateSyncGroupMessage(nlohmann::json &json) void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) { + 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[TAG_REPLY] = authResponseContext_->reply; json[TAG_DEVICE_ID] = authResponseContext_->deviceId; - json[TAG_GROUPIDS] = authResponseContext_->deviceId; + json[TAG_GROUPIDS] = authResponseContext_->deviceId; //? json[PIN_CODE_KEY] = authResponseContext_->code; + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %d,%d",authResponseContext_->reply,authResponseContext_->code); + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s",authResponseContext_->deviceId.c_str()); if (authResponseContext_->reply == 0) { json[TAG_NET_ID] = authResponseContext_->networkId; json[TAG_REQUEST_ID] = authResponseContext_->requestId; - json[TAG_GROUP_ID] = authResponseContext_->groupId; + json[TAG_GROUP_ID] = groupId; json[TAG_GROUP_NAME] = authResponseContext_->groupName; + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s",groupId.c_str(),authResponseContext_->groupName.c_str()); } } @@ -138,7 +149,6 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) return DM_FAILED; } //TODO::try to crypto first then parse json - LOGE(" AuthMessageProcessor ParseMessage"); if (!jsonObject.contains(TAG_TYPE)){ LOGE("err json string, first time"); return DM_FAILED; @@ -146,18 +156,19 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) int32_t sliceNum = 0; int32_t msgType = jsonObject[TAG_TYPE]; authResponseContext_->msgType = msgType; - LOGE(" AuthMessageProcessor ParseMessage"); + LOGI("AuthMessageProcessor::ParseAuthRequestMessage======== %d",authResponseContext_->msgType); switch (msgType) { case MSG_TYPE_NEGOTIATE: - LOGE(" AuthMessageProcessor ParseMessage"); ParseNegotiateMessage(jsonObject); - LOGE(" AuthMessageProcessor ParseMessage"); 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]; + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s",authResponseContext_->deviceId.c_str()); sliceNum = jsonObject[TAG_SLICE_NUM]; if ((int32_t)authSplitJsonList_.size() < sliceNum) { authSplitJsonList_.push_back(message); @@ -165,12 +176,32 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) ParseAuthRequestMessage(); } break; + case MSG_TYPE_RESP_AUTH: + ParseAuthResponseMessage(jsonObject); + break; default: break; } return DM_OK; } +void AuthMessageProcessor::ParseAuthResponseMessage(nlohmann::json &json) +{ + LOGI("AuthMessageProcessor::ParseAuthResponseMessage "); + authResponseContext_->reply = json[TAG_REPLY]; + authResponseContext_->deviceId = json[TAG_DEVICE_ID]; + authResponseContext_->deviceId = json[TAG_GROUPIDS]; + authResponseContext_->code = json[PIN_CODE_KEY]; + if (authResponseContext_->reply == 0) { + 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(); @@ -178,6 +209,8 @@ void AuthMessageProcessor::ParseAuthRequestMessage() 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]; diff --git a/services/devicemanagerservice/src/authentication/auth_request_state.cpp b/services/devicemanagerservice/src/authentication/auth_request_state.cpp index c11e5f431..2fff06d98 100644 --- a/services/devicemanagerservice/src/authentication/auth_request_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -29,7 +29,7 @@ void AuthRequestState::Leave() { } void AuthRequestState::SetAuthManager(std::shared_ptr authManager) { - authManager_ = authManager; + authManager_ = std::move(authManager); } // void AuthRequestState::SetLastState(std::shared_ptr state) { @@ -37,7 +37,7 @@ void AuthRequestState::SetAuthManager(std::shared_ptr authManager // } void AuthRequestState::SetAuthContext(std::shared_ptr context) { - context_ = context; + context_ = std::move(context); } std::shared_ptr AuthRequestState::GetAuthContext() { @@ -45,25 +45,15 @@ std::shared_ptr AuthRequestState::GetAuthContext() { } void AuthRequestState::TransitionTo(std::shared_ptr state) { - LOGI("DmAuthManager::OnSessionOpened sessionId"); + LOGE("AuthRequestState::TransitionTo"); state->SetAuthManager(authManager_); - LOGE("DmAuthManager::EstablishAuthChannel session id"); - // state->SetLastState((std::shared_ptr)this); - // LOGE("DmAuthManager::EstablishAuthChannel session id"); - // lastState_ = state; - LOGE("DmAuthManager::EstablishAuthChannel session id"); + authManager_->SetAuthRequestState(state); state->SetAuthContext(context_); - LOGE("DmAuthManager::EstablishAuthChannel session id"); this->Leave(); - LOGE("DmAuthManager::EstablishAuthChannel session id"); state->Enter(); - LOGE("DmAuthManager::EstablishAuthChannel session id"); - authManager_->SetAuthRequestState(state); - LOGI("DmAuthManager::OnSessionOpened sessionId"); } int32_t AuthRequestInitState::GetStateType() { - LOGI("AuthRequestState::GetStateType22222222222 sessionId"); return AuthState::AUTH_REQUEST_INIT; } @@ -72,17 +62,12 @@ void AuthRequestInitState::Enter() { } int32_t AuthRequestNegotiateState::GetStateType() { - LOGI("AuthRequestState::GetStateType111111111 sessionId"); return AuthState::AUTH_REQUEST_NEGOTIATE; } void AuthRequestNegotiateState::Enter() { // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 - // std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); - // softbusSession_->SendData(context_.sessionId, message); - LOGI("DmAuthManager::OnSessionOpened sessionId"); authManager_->StartNegotiate(context_->sessionId); - LOGI("DmAuthManager::OnSessionOpened sessionId"); } int32_t AuthRequestNegotiateDoneState::GetStateType() { @@ -96,9 +81,8 @@ void AuthRequestNegotiateDoneState::Enter() { // authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH); // std::string message; // softbusSession_->SendData(context_.sessionId, message); -LOGE("DmAuthManager::EstablishAuthChannel session id"); - authManager_->SendAuthRequest(context_->sessionId); LOGE("DmAuthManager::EstablishAuthChannel session id"); + authManager_->SendAuthRequest(context_->sessionId); } int32_t AuthRequestReplyState::GetStateType() { @@ -111,7 +95,7 @@ void AuthRequestReplyState::Enter() { //2. 用户授权同意 //3. 回调给认证实现模块,启动认证 - authManager_->StartAuthProcess(context_->authType); + authManager_->StartRespAuthProcess(); } int32_t AuthRequestInputState::GetStateType() { @@ -122,7 +106,9 @@ void AuthRequestInputState::Enter() { // //1. 获取用户输入 // // //2. 验证认证信息 -// authManager_->VerifyAuthentication(); + LOGE("DmAuthManager::AuthRequestInputState"); + std::string test = ""; + authManager_->VerifyAuthentication(test, test); } int32_t AuthRequestJoinState::GetStateType() { @@ -131,6 +117,7 @@ int32_t AuthRequestJoinState::GetStateType() { void AuthRequestJoinState::Enter() { //1. 加入群组 + LOGE("DmAuthManager::AuthRequestJoinState"); authManager_->AddMember(context_->deviceId); } @@ -140,6 +127,7 @@ int32_t AuthRequestNetworkState::GetStateType() { void AuthRequestNetworkState::Enter() { //1. 进行组网 + authManager_->JoinNetwork(); } int32_t AuthRequestFinishState::GetStateType() { diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp index 44b20d9a3..1a14eb20a 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -37,7 +37,7 @@ std::shared_ptr AuthResponseState::GetAuthContext() { void AuthResponseState::SetAuthManager(std::shared_ptr authManager) { - authManager_ = authManager; + authManager_ = std::move(authManager); } // void AuthResponseState::SetLastState(std::shared_ptr state) @@ -51,11 +51,10 @@ void AuthResponseState::TransitionTo(std::shared_ptr state) state->SetAuthManager(authManager_); // state->SetLastState((std::shared_ptr)this); // lastState_ = state; + authManager_->SetAuthResponseState(state); state->SetAuthContext(context_); this->Leave(); state->Enter(); - authManager_->SetAuthResponseState(state); - LOGI("AuthRequestState:: TransitionTo Enter"); } int32_t AuthResponseInitState::GetStateType() @@ -92,6 +91,7 @@ void AuthResponseConfirmState::Enter() //委托授权UI模块进行用户交互 //如果交互成功 // TransitionTo(new AuthResponseGroupState()); + LOGI("AuthRequestState:: AuthResponseConfirmState Enter"); authManager_->StartAuthProcess(context_->authType); } @@ -104,6 +104,9 @@ void AuthResponseGroupState::Enter() { // //1.创建群组, // authManagerPtr_->GetHiChainConnector()->CreateGroup(); + LOGI("AuthRequestState:: AuthResponseGroupState Enter"); + std::string groupName = "1234567890"; + authManager_->CreateGroup(context_->requestId, groupName); } int32_t AuthResponseShowState::GetStateType() diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index ce453a903..4da546a5e 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -20,8 +20,7 @@ #include "dm_log.h" #include "dm_constants.h" #include "auth_message_processor.h" -#include -#include + namespace OHOS { namespace DistributedHardware { @@ -32,13 +31,12 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, //TODO: load library so for different auth type std::string pkgName = "com.ohos.devicemangagerdemo"; sessionSession_->RegisterSessionCallback(pkgName, std::shared_ptr(this)); - hiChainConnector_ = std::make_shared(); + // hiChainConnector_ = std::make_shared(); } DmAuthManager::~DmAuthManager() { LOGI("DmAuthManager destructor"); - LOGI("DmAuthManager destructor11111111111"); } int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) @@ -60,7 +58,7 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au } sessionSession_->UnRegisterSessionCallback(pkgName); sessionSession_->RegisterSessionCallback(pkgName, std::shared_ptr(this)); - hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + // hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); authRequestContext_ = std::make_shared(); authRequestContext_->authType = authType; @@ -85,12 +83,10 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au } authMessageProcessor_ = std::make_shared(std::shared_ptr(this)); authRequestState_ = std::shared_ptr(new AuthRequestInitState()); - LOGI("DmAuthManager::AuthenticateDevice authRequestState_ AuthRequestInitState"); authRequestState_->SetAuthManager(std::shared_ptr(this)); authRequestState_->SetAuthContext(authRequestContext_); authMessageProcessor_->SetRequestContext(authRequestContext_); authRequestState_->Enter(); - LOGI("DmAuthManager::AuthenticateDevice authRequestState_ AuthRequestInitState"); // auto authenticateStartTimer = [this]() { // HandleAuthenticateTimeout(); // }; @@ -106,9 +102,12 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) { + //IF input pincode success; + LOGI("DmAuthManager::VerifyAuthentication"); if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT) { authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); } + LOGI("DmAuthManager::VerifyAuthentication complete"); return DM_OK; } @@ -121,21 +120,19 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI authResponseState_ = std::shared_ptr(new AuthResponseInitState()); authResponseState_->SetAuthManager(std::shared_ptr(this)); authResponseState_->Enter(); + hiChainConnector_ = std::make_shared(); hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); } else { //TODO:RESP_AUTH 认证失败,流程终止 } } else { - LOGI("DmAuthManager::OnSessionOpened AUTH_SESSION"); authResponseState_ = std::shared_ptr(new AuthResponseInitState()); authResponseState_->SetAuthManager(std::shared_ptr(this)); authResponseState_->Enter(); - LOGI("DmAuthManager::OnSessionOpened AUTH_SESSION"); if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { authRequestContext_ ->sessionId = sessionId; authRequestState_->SetAuthContext(authRequestContext_); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); - LOGI("DmAuthManager::OnSessionOpened sessionId"); } else { LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType()); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); @@ -145,15 +142,12 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI 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 complete1"); - if (authResponseState_ == nullptr) { - LOGI("DmAuthManager::authResponseState_ ============"); - } + LOGI("DmAuthManager::OnDataReceived start"); authResponseContext_ = std::make_shared(); authResponseContext_ ->sessionId = sessionId; authResponseState_->SetAuthContext(authResponseContext_); @@ -165,17 +159,13 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId } authResponseContext_ = authMessageProcessor_->GetResponseContext(); authResponseState_->SetAuthContext(authResponseContext_); - LOGI("DmAuthManager::OnDataReceived complete666666666"); switch (authResponseContext_->msgType) { case MSG_TYPE_NEGOTIATE: - LOGI("DmAuthManager::OnDataReceived complete77777777777"); if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { - LOGI("DmAuthManager::OnDataReceived complete==========="); authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); } else { //状态错误,流程终止 } - LOGI("DmAuthManager::OnDataReceived complete"); break; case MSG_TYPE_REQ_AUTH: //检查状态机状态 @@ -196,11 +186,8 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId } break; case MSG_TYPE_RESP_NEGOTIATE: - LOGI("DmAuthManager::OnDataReceived complete111111111111"); if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) { - LOGI("DmAuthManager::OnDataReceived complete72222222222222222222"); authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateDoneState())); - LOGI("DmAuthManager::OnDataReceived complete72222222222222222222"); } else { //状态错误,流程终止 } @@ -214,17 +201,22 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId { //创建群组成功 //发送认证响应消息给请求端 + LOGI("DmAuthManager::OnGroupCreated start"); + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseShowState())); int32_t pinCode = 123456; authResponseContext_->code = pinCode; + authResponseContext_->groupId = groupId; + authResponseContext_->groupName = "1234567890"; + authResponseContext_->reply = 0; authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); - softbusConnector_->GetSoftbusSession()->SendData(authRequestContext_->sessionId, message); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) { -// if (authRequestState_->GetStateType() == AuthRequestJoinState) { -// authRequestState_->TransitionTo(new AuthRequestNetworkState()); +// if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) { +// authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNetworkState())); // } } @@ -236,7 +228,6 @@ void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) { //TODO:检查crypto模块是否适配 //TODO:兼容性处理,兼容与手机的认证 - LOGE("DmAuthManager::EstablishAuthChannel is"); int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); if (sessionId < 0) { LOGE("OpenAuthSession failed, stop the authentication"); @@ -281,9 +272,7 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) if (authResponseContext_->cryptoSupport == true){ isCryptoSupport_ = true; } - LOGE("DmAuthManager::EstablishAuthChannel session id"); std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); - LOGE("DmAuthManager::EstablishAuthChannel session id"); //TODO::设置消息等待超时时间 for (auto msg : messageList) { softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); @@ -297,19 +286,55 @@ void DmAuthManager::StartAuthProcess(const int32_t &authType) //3. 回调给认证实现模块,启动认证 // std::shared_ptr authentication = authenticationMap_[authType]; // authentication->StartAuth(); - std::string groupName = "1234567890"; - CreateGroup(authResponseContext_->requestId, groupName); - authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestInputState())); + LOGI("DmAuthManager:: StartAuthProcess 111"); + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM){ + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseGroupState())); + } + // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestInputState())); +} + +void DmAuthManager::StartRespAuthProcess() +{ + LOGI("DmAuthManager::StartRespAuthProcess StartRespAuthProcess", authResponseContext_->sessionId); + softbusConnector_->GetSoftbusSession()->CloseAuthSession(authResponseContext_->sessionId); + if (authResponseContext_->reply == 0){ + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestInputState())); + return; + } // hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + LOGE("do not accept"); } void DmAuthManager::CreateGroup(int64_t requestId, const std::string &groupName) { + LOGI("DmAuthManager:: CreateGroup"); hiChainConnector_->CreateGroup(requestId, groupName); } void DmAuthManager::AddMember(const std::string &deviceId) { -// hiChainConnector_->AddMember(deviceId); + LOGI("DmAuthManager::AddMember complete"); + 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::string pkgName = "com.ohos.devicemangagerdemo"; + hiChainConnector_ = std::make_shared(); + hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + int32_t ret = hiChainConnector_->AddMember(deviceId, connectInfo); + if (ret != 0){ + return; + } +} + +std::string DmAuthManager::GetConnectAddr(std::string deviceId) +{ + LOGI("DmAuthManager::GetConnectAddr"); + std::string connectAddr; + softbusConnector_->GetConnectAddr(deviceId, connectAddr); + return connectAddr; } void DmAuthManager::JoinNetwork() @@ -325,44 +350,39 @@ void DmAuthManager::AuthenticateFinish() void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) { - LOGE("DmAuthManager::GetIsCryptoSupport 111111"); if (authResponseState_ == nullptr){ - LOGE("DmAuthManager::GetIsCryptoSupport 12222222222222"); isCryptoSupport = false; return; } - LOGE("DmAuthManager::GetIsCryptoSupport 333333333"); if (authRequestState_ == nullptr){ - LOGE("DmAuthManager::GetIsCryptoSupport44444444"); if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE){ - LOGE("DmAuthManager::GetIsCryptoSupport 5555555555"); isCryptoSupport = false; return; } }else { - LOGE("DmAuthManager::GetIsCryptoSupport 6666666666"); if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE){ - LOGE("DmAuthManager::GetIsCryptoSupport 777777777777"); isCryptoSupport = false; return; } } - LOGE("DmAuthManager::GetIsCryptoSupport 88888888888888"); isCryptoSupport = isCryptoSupport_; } void DmAuthManager::SetAuthRequestState(std::shared_ptr authRequestState) { - LOGE("DmAuthManager::SetAuthRequestState======= "); authRequestState_ = authRequestState; } void DmAuthManager::SetAuthResponseState(std::shared_ptr authResponseState) { - LOGE("DmAuthManager::SetAuthResponseState=========== "); authResponseState_ = authResponseState; } + +int32_t DmAuthManager::GetPinCode() +{ + return authResponseContext_->code; +} } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 2fe785688..3f4c4a13c 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -29,7 +29,6 @@ #include "dm_constants.h" #include "dm_random.h" - namespace OHOS { namespace DistributedHardware { void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) @@ -170,7 +169,7 @@ int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vectorGetGroupId(); + jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; -// jsonObj[FIELD_PIN_CODE] = std::to_string(msgResponseAuth->GetPinCode()).c_str(); + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).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(); + 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 deviceGroupManager_->addMemberToGroup(0/*msgResponseAuth->GetRequestId()*/, DM_PKG_NAME.c_str(), - tmpStr.c_str()); + return ret; } void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) @@ -256,22 +265,24 @@ char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, cons LOGE("HiChainAuthCallBack::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; - return nullptr; + int32_t pinCode = 0; + for(auto & iter : hiChainConnectorCallbackMap_) { + pinCode = iter.second->GetPinCode(); + } + 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; } int64_t HiChainConnector::GenRequestId() @@ -280,37 +291,22 @@ int64_t HiChainConnector::GenRequestId() } -//std::string HiChainConnector::GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth) -//{ -// ConnectionAddr *addrInfo = SoftbusAdapter::GetConnectAddr(deviceId); -// if (addrInfo == nullptr) { -// LOGE("HiChainConnector::GetConnectPara addrInfo error"); -// return ""; -// } -// -// LOGE("HiChainConnector::GetConnectPara get addrInfo"); -// nlohmann::json jsonPara; -// jsonPara[DEVICE_ID] = msgResponseAuth->GetDeviceId(); -// if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { -// LOGI("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) { -// LOGI("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) { -// LOGI("HiChainConnector::AddMemeber addr type is br"); -// jsonPara[BR_MAC] = addrInfo->info.br.brMac; -// } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) { -// LOGI("HiChainConnector::AddMemeber addr type is ble"); -// jsonPara[BLE_MAC] = addrInfo->info.ble.bleMac; -// } else { -// LOGE("HiChainConnector::AddMemeber addrInfo not right"); -// return ""; -// } -// return jsonPara.dump(); -//} +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) { diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 1cfd84c89..3a9a4a0de 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -27,6 +27,7 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_device_info.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { @@ -110,7 +111,7 @@ int32_t SoftbusConnector::Init() 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) { @@ -345,7 +346,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddrByType(DeviceInfo *deviceInfo, C return nullptr; } -ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId) +ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) { auto iter = discoveryDeviceInfoMap_.find(deviceId); if (iter == discoveryDeviceInfoMap_.end()) { @@ -357,25 +358,36 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId) 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()); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index d18822de5..13701061e 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -64,7 +64,8 @@ int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) { LOGE("SoftbusSession::OpenAuthSession"); int32_t sessionId = -1; - ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId); + std::string connectAddr; + ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("GetConnectAddr error"); return sessionId; @@ -106,14 +107,12 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) LOGE("extrasJson error"); return DM_FAILED; } + int32_t msgType = jsonObject[TAG_TYPE]; + LOGI("AuthMessageProcessor::ParseAuthRequestMessage msgType = %d",msgType); bool isCryptoSupport = false; - LOGE("SendData Start"); for (auto & iter : sessionCallbackMap_) { - LOGE("SendData Start1"); iter.second->GetIsCryptoSupport(isCryptoSupport); - LOGE("SendData Start2"); } - LOGE("SendData Start"); if (isCryptoSupport) { uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MSG_MAX_SIZE + ENCRYPT_TAG_LEN)); if (buf == nullptr) { @@ -131,7 +130,6 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) // int32_t ret = SendBytes(sessionId, buf, strlen(buf)); free(buf); } - LOGE("SendData Start"); int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); if (ret != DM_OK) { diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index eeaf56d63..54f97dc11 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -38,7 +38,7 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); if (profileAdapter == nullptr){ LOGE("OnDeviceOnline profile adapter is null"); - return; + // return; } DmDeviceState state = DEVICE_STATE_ONLINE; // profileAdapter->RegisterProfileListener(); @@ -50,7 +50,7 @@ void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmD std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); if (profileAdapter == nullptr){ LOGE("OnDeviceOnline profile adapter is null"); - return; + // return; } DmDeviceState state = DEVICE_STATE_OFFLINE; // profileAdapter->UnRegisterProfileListener(); -- Gitee From dd081aba4c9f51123f4c5ac330e3127388620f80 Mon Sep 17 00:00:00 2001 From: lcaidm <15399456112@qq.com> Date: Wed, 22 Dec 2021 11:25:14 +0800 Subject: [PATCH 045/110] =?UTF-8?q?=E6=B5=81=E7=A8=8B=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ext/pin_auth/include/pin_auth_ui.h | 1 + ext/pin_auth/src/pin_auth_ui.cpp | 8 +++++++- .../native_cpp/src/ipc/standard/ipc_cmd_parser.cpp | 2 +- interfaces/kits/js/include/native_devicemanager_js.h | 1 + .../include/authentication/auth_ui.h | 1 + .../include/authentication/dm_auth_manager.h | 11 +++++++++-- .../src/authentication/auth_ui.cpp | 6 ++++++ .../src/device_manager_service.cpp | 3 +-- 8 files changed, 27 insertions(+), 6 deletions(-) diff --git a/ext/pin_auth/include/pin_auth_ui.h b/ext/pin_auth/include/pin_auth_ui.h index ee339b143..ad3fb2a61 100644 --- a/ext/pin_auth/include/pin_auth_ui.h +++ b/ext/pin_auth/include/pin_auth_ui.h @@ -28,6 +28,7 @@ public: int32_t InputPinDialog(); private: + int32_t StartFaService(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index 44c12a64f..f8d6888e9 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -27,11 +27,17 @@ PinAuthUi::PinAuthUi() int32_t PinAuthUi::ShowPinDialog() { - LOGI("PinAuthUi::StartFaService in"); + LOGI("PinAuthUi::ShowPinDialog in"); return SUCCESS; } int32_t PinAuthUi::InputPinDialog() +{ + LOGI("PinAuthUi::InputPinDialog in"); + return StartFaService(); +} + +int32_t PinAuthUi::StartFaService() { LOGI("PinAuthUi::StartFaService in"); AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); 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 ffb4bf5a4..d03c7870f 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 @@ -391,7 +391,7 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr return DM_IPC_TRANSACTION_FAILED; } if (!data.WriteInt32(action)) { - LOGE("write extra failed"); + LOGE("write action failed"); return DM_WRITE_FAILED; } diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 9747640f4..9f2af5535 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -214,6 +214,7 @@ private: DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static napi_value CallDeviceList(napi_env env, napi_callback_info info, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + void OnDmfaCall(std::string ¶mJson); private: napi_env env_; napi_ref wrapper_; diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h index 647ddc218..c1d431ba9 100644 --- a/services/devicemanagerservice/include/authentication/auth_ui.h +++ b/services/devicemanagerservice/include/authentication/auth_ui.h @@ -25,6 +25,7 @@ public: AuthUi(); int32_t ShowConfirmDialog(); private: + int32_t StartFaService(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 4a2661bd7..8a8e41dc4 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -141,11 +141,18 @@ public: void AuthenticateFinish(); int32_t GetAuthenticationParam(DmAuthParam &authParam); void OnUserOperate(int32_t action); - void BuildAuthenticationInfo(DmAuthParam &authParam); - void OnUserOperate(int32_t action); private: void HandleAuthenticateTimeout(); + void OnUserConfirm(); + void OnUserReqSessionOperate(int32_t action); + void OnUserRespSessionOperate(int32_t action); + void ReqSessionRelease(); + std::string GenerateGroupName(); + void Release(); + void CancelDisplay(); + int32_t GeneratePincode(); + void BuildAuthenticationInfo(DmAuthParam &authParam); private: std::shared_ptr softbusConnector_; std::shared_ptr sessionSession_; diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp index 13411169c..c192e8ff4 100644 --- a/services/devicemanagerservice/src/authentication/auth_ui.cpp +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -27,6 +27,12 @@ AuthUi::AuthUi() } int32_t AuthUi::ShowConfirmDialog() +{ + LOGI("AuthUi::ShowConfirmDialog in"); + return StartFaService(); +} + +int32_t AuthUi::StartFaService() { LOGI("AuthUi::StartFaService in"); AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 6154c4875..a8c1d0593 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -195,8 +195,7 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth return DM_INPUT_PARA_EMPTY; } - type = DmAbilityManager::GetInstance().GetDmFaType(); - + type = DmAbilityManager::GetInstance().GetDmFaType(); DmAbilityManager::GetInstance().StartAbilityDone(); DmAuthManager::GetInstance().GetAuthenticationParam(authParam); return DM_OK; -- Gitee From c8277529eb0fdb0b26ce0fd07f9b43d76314a77d Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Thu, 23 Dec 2021 13:07:17 +0800 Subject: [PATCH 046/110] add by weidong.liu@thundersoft.com change1: fix GET_TRUST_DEVICE_LIST IPC server because malloc buff free dump; change2: fix UNAUTHENTICATE_DEVICE IPC server because lost some command. --- .../src/ipc/standard/ipc_cmd_parser.cpp | 42 +++++++++++++++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 30 +++++++++---- 2 files changed, 56 insertions(+), 16 deletions(-) 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 810c6902f..1480b2e6f 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 @@ -28,6 +28,7 @@ #include "ipc_get_trustdevice_req.h" #include "ipc_get_trustdevice_rsp.h" #include "ipc_authenticate_device_req.h" +#include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" #include "ipc_get_local_device_info_rsp.h" namespace OHOS { @@ -90,17 +91,17 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, MessageParcel &reply, std::shared_pt { 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) { - LOGE("GetTrustedDeviceList read node info failed!"); - pRsp->SetErrCode(DM_IPC_TRANSACTION_FAILED); - return DM_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); @@ -228,6 +229,29 @@ ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr< 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 (!data.WriteString(deviceId)) { + LOGE("write extra failed"); + return DM_IPC_FLATTEN_OBJECT; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(UNAUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_SET_REQUEST(VERIFY_AUTHENTICATION, std::shared_ptr pBaseReq, MessageParcel &data) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index ef5174fcb..820dfc681 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -190,21 +190,21 @@ ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) 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()){ - DmDeviceInfo *deviceInfo = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo)*infoNum); for (; !deviceList.empty();){ - *(deviceInfo + infoNum) = deviceList.back(); + deviceInfo = deviceList.back(); deviceList.pop_back(); + + if (!reply.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { + LOGE("write subscribeInfo failed"); + return DM_WRITE_FAILED; + } } - if (!reply.WriteRawData(deviceInfo, sizeof(DmDeviceInfo) * infoNum)) { - LOGE("write subscribeInfo failed"); - return DM_WRITE_FAILED; - } - free(deviceInfo); } if (!reply.WriteInt32(result)) { LOGE("write result failed"); @@ -286,6 +286,22 @@ ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) 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) { std::string authPara = data.ReadString(); -- Gitee From 83480d03283b1ba19ebc88c4abff73094742ccab Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Fri, 24 Dec 2021 17:00:00 +0800 Subject: [PATCH 047/110] added by weidong.liu@thundersoft.com change1: unAuthenticateDevice param change from DeviceIn struct to DeviceId as string; change2: add GetLocalDeviceInfo Async function. --- .../native_cpp/include/device_manager.h | 2 +- .../native_cpp/include/device_manager_impl.h | 2 +- .../native_cpp/src/device_manager_impl.cpp | 11 +- .../kits/js/include/native_devicemanager_js.h | 6 + .../kits/js/src/native_devicemanager_js.cpp | 170 +++++++++++++----- .../dependency/hichain/hichain_connector.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 14 ++ 7 files changed, 154 insertions(+), 53 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index cebaffb65..93eab9821 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -42,7 +42,7 @@ public: 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 DmDeviceInfo &deviceInfo) = 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; }; 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 f7d488d26..1b6ad018f 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -40,7 +40,7 @@ public: 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 DmDeviceInfo &deviceInfo) 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; private: 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 6b4ed4ca3..d71043a9b 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -282,14 +282,16 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ } -int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { - LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s", pkgName.c_str()); - if (pkgName.empty()) { + LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s, deviceId: %s", pkgName.c_str(), deviceId.c_str()); + if (deviceId.empty()) { LOGE("UnAuthenticateDevice error: Invalid para"); return DM_INVALID_VALUE; } + DmDeviceInfo deviceInfo; + strcpy(deviceInfo.deviceId, deviceId.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -306,8 +308,7 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons return DM_IPC_RESPOND_ERROR; } - std::string strDeviceId = deviceInfo.deviceId; - DeviceManagerNotify::GetInstance().UnRegisterAuthenticateCallback(pkgName, strDeviceId); + DeviceManagerNotify::GetInstance().UnRegisterAuthenticateCallback(pkgName, deviceId); LOGI("UnAuthenticateDevice completed, pkgName: %s", pkgName.c_str()); return DM_OK; } diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 00e077818..e29911878 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -54,6 +54,7 @@ struct DeviceInfoAsyncCallbackInfo { napi_value thisVar = nullptr; napi_deferred deferred = nullptr; int32_t status = -1; + int32_t isList = 0; }; struct AuthAsyncCallbackInfo { napi_env env = nullptr; @@ -143,6 +144,7 @@ public: 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); @@ -205,6 +207,10 @@ private: 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_; napi_ref wrapper_; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 1d1b4e8c4..dad9e036f 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -888,6 +888,50 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status } } +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; @@ -897,8 +941,14 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI [](napi_env env, void *data) { (void)env; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->extra, deviceInfoAsyncCallbackInfo->devList); + 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); @@ -911,7 +961,11 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI [](napi_env env, napi_status status, void *data) { (void)status; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - CallGetTrustedDeviceListStatusSync(env, status, deviceInfoAsyncCallbackInfo); + 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); @@ -926,21 +980,31 @@ void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo env, nullptr, resourceName, [](napi_env env, void *data) { DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->extra, deviceInfoAsyncCallbackInfo->devList); + 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", + LOGE("CallAsyncWork for bunderName %s failed, ret %d", deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); deviceInfoAsyncCallbackInfo->status = -1; return; } deviceInfoAsyncCallbackInfo->status = 0; - LOGE("GetTrustedDeviceList status %d", deviceInfoAsyncCallbackInfo->status); + LOGE("CallAsyncWork status %d", deviceInfoAsyncCallbackInfo->status); }, [](napi_env env, napi_status status, void *data) { (void)status; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - CallGetTrustedDeviceListStatus(env, status, deviceInfoAsyncCallbackInfo); + 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); @@ -963,13 +1027,13 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in napi_valuetype eventHandleType = napi_undefined; napi_typeof(env, argv[0], &eventHandleType); if (eventHandleType == napi_function) { - LOGE("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); + 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("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); + LOGE("CallDeviceList for argc %d Type = %d", argc, (int)eventHandleType); // DmFilterOptions filterOptions; napi_deferred deferred; napi_value promise = 0; @@ -1031,8 +1095,9 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i auto *deviceInfoAsyncCallbackInfo = new DeviceInfoAsyncCallbackInfo(); deviceInfoAsyncCallbackInfo->env = env; deviceInfoAsyncCallbackInfo->devList = devList; + deviceInfoAsyncCallbackInfo->isList = 1; deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; - LOGE("GetLocalDeviceInfo for argc %d", argc); + LOGE("GetTrustedDeviceList for argc %d", argc); if(argc == 0) { // DmFilterOptions filterOptions; // memset_s(filterOptions.targetPkgName, sizeof(filterOptions.targetPkgName), 0, @@ -1050,40 +1115,18 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); return promise; } else if (argc == 1) { - GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); - napi_valuetype valueType; - napi_typeof(env, argv[0], &valueType); - if(valueType == napi_string)//getTrustedDeviceList(extra: string): Promise>; - { - char extra[32]; - JsObjectToString(env, argv[0], "extra", extra, sizeof(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(valueType == napi_function) - { - return CallDeviceList(env, info, deviceInfoAsyncCallbackInfo); - } - else - { - NAPI_ASSERT(env, true, "Wrong argument type, string or function expected."); - } + 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("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)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("GetLocalDeviceInfo for argc %d Type = %d", argc, (int)eventHandleType); + LOGE("GetTrustedDeviceList for argc %d Type = %d", argc, (int)eventHandleType); NAPI_ASSERT(env, eventHandleType == napi_function, "Wrong argument type. Object expected."); // JsToDmFilterOptions(env, argv[0], filterOptions); @@ -1124,23 +1167,58 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback 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_ONE); + GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); napi_typeof(env, argv[0], &deviceInfoType); - NAPI_ASSERT(env, deviceInfoType == napi_object, "Wrong argument type. Object expected."); - - DmDeviceInfo deviceInfo; - JsToDmDeviceInfo(env, argv[0], deviceInfo); - + 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_, - deviceInfo); + 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); @@ -1595,10 +1673,12 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) napi_value dmClass = nullptr; 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), diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index de383c418..483f2b5c1 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -56,9 +56,9 @@ public: int32_t AddMember(std::string deviceId, std::string &connectInfo); int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); + void GetRelatedGroups(std::string DeviceId, std::vector &groupList); private: int64_t GenRequestId(); - void GetRelatedGroups(std::string DeviceId, std::vector &groupList); 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); diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 4da546a5e..881a13a1d 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -97,6 +97,20 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au 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; + } + std::string groupId = ""; + std::vector groupList; + hiChainConnector_->GetRelatedGroups(deviceId, groupList); + if(groupList.size() > 0){ + groupId = groupList.front().groupId; + } + //groupId = authResponseContext_->groupId; + LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s", authResponseContext_->groupId.c_str(), deviceId.c_str()); + hiChainConnector_->DeleteGroup(groupId); + return DM_OK; } -- Gitee From a67ad24d675dd305ba43437b717c19e012dddbba Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Fri, 24 Dec 2021 18:58:04 +0800 Subject: [PATCH 048/110] =?UTF-8?q?=E7=BC=96=E8=AF=91=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ext/pin_auth/BUILD.gn | 2 +- .../native_cpp/include/device_manager.h | 1 - .../native_cpp/include/device_manager_impl.h | 3 +- .../native_cpp/include/dm_device_info.h | 2 + .../native_cpp/src/device_manager_impl.cpp | 5 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 6 +- .../kits/js/include/native_devicemanager_js.h | 2 +- .../kits/js/src/native_devicemanager_js.cpp | 2 +- services/devicemanagerservice/BUILD.gn | 18 +++-- .../include/ability/dm_ability_manager.h | 4 +- .../authentication/auth_message_processor.h | 2 + .../include/authentication/dm_auth_manager.h | 12 ++-- .../dependency/hichain/hichain_connector.h | 2 +- .../include/device_manager_service.h | 2 + .../src/ability/lite/dm_ability_manager.cpp | 1 - .../ability/standard/dm_ability_manager.cpp | 9 ++- .../authentication/auth_message_processor.cpp | 1 - .../src/authentication/dm_auth_manager.cpp | 65 +++++++++++-------- .../dependency/hichain/hichain_connector.cpp | 4 +- .../src/device_manager_service.cpp | 8 +-- utils/include/cipher/encrypt_utils.h | 65 ------------------- 21 files changed, 90 insertions(+), 126 deletions(-) delete mode 100644 utils/include/cipher/encrypt_utils.h diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index b84625d6f..b21f1334f 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -22,7 +22,7 @@ import("//foundation/distributedhardware/devicemanager/devicemanager.gni") shared_library("devicemanagerext_pin_auth") { include_dirs = [ "${common_path}/include", - "${services_path}/include/adapter/", + "${services_path}/include/ability/", ] include_dirs += [ diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 0ed551aca..c80a4ab15 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -23,7 +23,6 @@ #include "device_manager_callback.h" #include "dm_subscribe_info.h" #include "dm_device_info.h" -#include "ipc_notify_dmfa_result_req.h" namespace OHOS { namespace DistributedHardware { 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 47833d418..13d60d9c6 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -20,7 +20,7 @@ #include "ipc_client_proxy.h" #include "ipc_client_manager.h" #include "dm_device_info.h" -#include "ipc_server_listener.h" + namespace OHOS { namespace DistributedHardware { @@ -57,7 +57,6 @@ private: private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); - IpcServerListener ipcServerListener_; }; } // namespace DistributedHardware } // namespace OHOS 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 a391bf896..00e5b67a2 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -17,6 +17,7 @@ #define OHOS_DM_DEVICE_INFO_H #include +#include "dm_app_image_info.h" #define DM_MAX_DEVICE_ID_LEN (96) #define DM_MAX_DEVICE_NAME_LEN (128) @@ -65,6 +66,7 @@ typedef struct DmAuthParam { int32_t pincode; int32_t direction; int32_t pinToken; + DmAppImageInfo imageinfo; } DmAuthParam; typedef struct DmFaParam { 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 30c27e4ef..fd7aaba0f 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -30,6 +30,7 @@ #include "ipc_authenticate_device_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" +#include "ipc_set_useroperation_req.h" namespace OHOS { namespace DistributedHardware { @@ -317,6 +318,7 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &faParam) { LOGI("DeviceManagerImpl::GetFaParam start"); + DmFaParam dmFaParam; if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INVALID_VALUE; @@ -327,7 +329,8 @@ int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &faParam if (ipcClientProxy_->SendRequest(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { return DM_IPC_SEND_REQUEST_FAILED; } - faParam = rsp->GetDmFaParam(); + dmFaParam = rsp->GetDmFaParam(); + faParam = dmFaParam.authParam; return DM_OK; } 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 d03c7870f..201ee6e1c 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -32,6 +32,9 @@ #include "ipc_authenticate_device_req.h" #include "ipc_verify_authenticate_req.h" #include "ipc_get_local_device_info_rsp.h" +#include "ipc_get_dmfaparam_rsp.h" +#include "ipc_set_useroperation_req.h" + namespace OHOS { namespace DistributedHardware { ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, MessageParcel &data) @@ -348,7 +351,7 @@ ON_IPC_READ_RESPONSE(SERVER_GET_DMFA_INFO, MessageParcel &reply, std::shared_ptr authParam.direction = reply.ReadInt32(); authParam.authType = reply.ReadInt32(); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - authParam.pinToken = reply.ReadInt32(); + authParam.authToken = reply.ReadInt32(); dmFaParam.authParam = authParam; dmFaParam.type = *type; pRsp->SetDmFaParam(dmFaParam); @@ -371,7 +374,6 @@ ON_IPC_READ_RESPONSE(SERVER_GET_DMFA_INFO, MessageParcel &reply, std::shared_ptr if (appThumbnailLen > 0) { appThumbBuffer = (uint8_t *)reply.ReadRawData(appThumbnailLen); } - authParam.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); dmFaParam.authParam = authParam; dmFaParam.type = *type; pRsp->SetDmFaParam(dmFaParam); diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 9f2af5535..36450d685 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -203,6 +203,7 @@ public: 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); 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[]); @@ -214,7 +215,6 @@ private: DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static napi_value CallDeviceList(napi_env env, napi_callback_info info, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); - void OnDmfaCall(std::string ¶mJson); private: napi_env env_; napi_ref wrapper_; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index bafa02afa..c1103a7e4 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -352,7 +352,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, napi_value extraInfo = nullptr; napi_create_object(env, &extraInfo); SetValueInt32(env, "direction", authParam.direction, extraInfo); - SetValueInt32(env, "authToken", authParam.authToken, extraInfo); + SetValueInt32(env, "pinToken", authParam.pinToken, extraInfo); if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 1bd3ba0ed..9d526e2bb 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -23,9 +23,10 @@ if (defined(ohos_lite)) { executable("devicemanagerservice") { include_dirs = [ "include", - "include/ability", "include/adapter", "include/authentication", + "include/ability", + "include/timer", "include/deviceinfo", "include/devicestate", "include/discovery", @@ -62,11 +63,12 @@ if (defined(ohos_lite)) { ] sources = [ - "src/ability/lite/dm_ability_manager.cpp", "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", "src/adapter/lite/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", + "src/ability/lite/dm_ability_manager.cpp", + "src/timer/dm_timer.cpp", "src/authentication/auth_message_processor.cpp", "src/authentication/auth_request_state.cpp", "src/authentication/auth_response_state.cpp", @@ -107,12 +109,14 @@ if (defined(ohos_lite)) { ohos_shared_library("devicemanagerservice") { include_dirs = [ "include", - "include/ability", "include/adapter", "include/authentication", + "include/ability", + "include/timer", "include/deviceinfo", "include/devicestate", "include/discovery", + "include/dependency/commonevent", "include/dependency/hichain", "include/dependency/softbus", "include/dependency/eventbus", @@ -129,6 +133,8 @@ if (defined(ohos_lite)) { "${innerkits_path}/native_cpp/include/ipc/standard", "//utils/native/base/include", "//utils/system/safwk/native/include", + "//base/notification/ces_standard/frameworks/core/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/security/deviceauth/interfaces/innerkits", "//base/startup/syspara_lite/interfaces/kits", "//base/startup/syspara_lite/adapter/native/syspara/include", @@ -136,8 +142,9 @@ if (defined(ohos_lite)) { ] sources = [ - "src/ability/standard/dm_ability_manager.cpp", "src/device_manager_service.cpp", + "src/ability/standard/dm_ability_manager.cpp", + "src/timer/dm_timer.cpp", "src/device_manager_service_listener.cpp", "src/adapter/standard/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", @@ -148,6 +155,7 @@ if (defined(ohos_lite)) { "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", "src/dependency/eventbus/event_bus.cpp", + "src/dependency/commonevent/event_manager_adapt.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", @@ -174,6 +182,8 @@ if (defined(ohos_lite)) { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "appexecfwk_standard:appexecfwk_base", "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h index 0db1b7cdb..4b95b7de8 100644 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ b/services/devicemanagerservice/include/ability/dm_ability_manager.h @@ -24,6 +24,7 @@ #include "single_instance.h" #include "dm_device_info.h" +#include "dm_auth_manager.h" namespace OHOS { namespace DistributedHardware { @@ -48,12 +49,11 @@ typedef enum FaAction { } FaAction; class DmAbilityManager { -DECLARE_SINGLE_INSTANCE(DmAbilityManager); public: AbilityRole GetAbilityRole(); AbilityStatus StartAbility(AbilityRole role); void StartAbilityDone(); - const DmFaType &GetDmFaType() const; + DmFaType GetDmFaType(); void SetDmFaType(const DmFaType &type); private: void waitForTimeout(uint32_t timeout_s); diff --git a/services/devicemanagerservice/include/authentication/auth_message_processor.h b/services/devicemanagerservice/include/authentication/auth_message_processor.h index 1a71a0d9d..006a7dad1 100644 --- a/services/devicemanagerservice/include/authentication/auth_message_processor.h +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.h @@ -19,6 +19,8 @@ #include #include #include "nlohmann/json.hpp" +#include "crypto_adapter.h" +#include "dm_auth_manager.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 8a8e41dc4..e512a977e 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -20,6 +20,7 @@ #include #include "authentication.h" +#include "dm_ability_manager.h" #include "dm_device_info.h" #include "softbus_session.h" #include "device_manager_service_listener.h" @@ -96,7 +97,7 @@ typedef struct DmAuthRequestContext { std::string appThumbnail; std::string token; std::vector syncGroupList; -} ; +} DmAuthRequestContext ; typedef struct DmAuthResponseContext { std::string deviceId; @@ -116,6 +117,8 @@ typedef struct DmAuthResponseContext { class AuthMessageProcessor; class DmAuthManager final : public ISoftbusSessionCallback, public IHiChainConnectorCallback, public std::enable_shared_from_this { +public: + static DmAuthManager& GetInstance(); public: DmAuthManager(std::shared_ptr softbusConnector, std::shared_ptr listener); @@ -128,8 +131,6 @@ public: 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); - int32_t GetDisplayOwner(); - void CancelDisplay(); //auth state machine void EstablishAuthChannel(const std::string &deviceId); @@ -153,6 +154,7 @@ private: void CancelDisplay(); int32_t GeneratePincode(); void BuildAuthenticationInfo(DmAuthParam &authParam); + void UpdateDmFaType(DmFaType type); private: std::shared_ptr softbusConnector_; std::shared_ptr sessionSession_; @@ -168,10 +170,8 @@ private: std::shared_ptr authMessageProcessor_; std::shared_ptr mMemberJoinTimerPtr_; int32_t mPincode_; - std::string mGroupId_; + int32_t mGroupId_; std::string mGroupName_; - - }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index ce68ec7c0..1820e9bc6 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -64,8 +64,8 @@ public: int32_t AddMember(std::string deviceId, std::string connectInfo); int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); -private: int64_t GenRequestId(); +private: void GetRelatedGroups(std::string DeviceId, std::vector &groupList); void SyncGroups(std::string deviceId, std::vector &remoteGroupIdList); void GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList); diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index 618dbebf7..1dacbaa2c 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -24,6 +24,7 @@ #include "dm_device_state_manager.h" #include "dm_discovery_manager.h" #include "dm_device_info.h" +#include "dm_ability_manager.h" #include "softbus_connector.h" #include "single_instance.h" @@ -50,6 +51,7 @@ private: std::shared_ptr discoveryMgr_; std::shared_ptr softbusConnector_; std::shared_ptr listener_; + std::shared_ptr abilityMgr_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp index d8c9a369f..1570551ba 100644 --- a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(DmAbilityManager); AbilityRole DmAbilityManager::GetAbilityRole() { diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp index a77000cf4..a5f9a6993 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -15,7 +15,6 @@ #include "dm_ability_manager.h" -#include "dm_auth_manager.h" #include "ability_manager_client.h" #include "ability_record.h" #include "ability_manager_service.h" @@ -26,12 +25,12 @@ #include "single_instance.h" #include "dm_log.h" + namespace OHOS { namespace DistributedHardware { namespace { const int32_t ABILITY_START_TIMEOUT = 3; // 3 second } -IMPLEMENT_SINGLE_INSTANCE(DmAbilityManager); AbilityRole DmAbilityManager::GetAbilityRole() { @@ -54,12 +53,12 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) mAbilityStatus_ = role; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + // 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) ? - DmAuthManager::GetInstance().GetDisplayOwner() : DISPLAY_OWNER_SYSTEM; + DISPLAY_OWNER_OTHER : DISPLAY_OWNER_SYSTEM; mStatus_ = AbilityStatus::ABILITY_STATUS_START; AAFwk::Want want; @@ -89,7 +88,7 @@ void DmAbilityManager::waitForTimeout(uint32_t timeout_s) sem_timedwait(&mSem_, &ts); } -const DmFaType &DmAbilityManager::GetDmFaType() const +DmFaType DmAbilityManager::GetDmFaType() { return mDmFaType_; } diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index b39b809c1..6a3bf3b0d 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -17,7 +17,6 @@ #include "dm_log.h" #include "dm_constants.h" -#include "dm_auth_manager.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index c0be0ced8..fd25c60d7 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -18,9 +18,9 @@ #include "nlohmann/json.hpp" #include "dm_log.h" +#include "dm_random.h" #include "dm_constants.h" #include "auth_message_processor.h" -#include "encrypt_utils.h" namespace OHOS { namespace DistributedHardware { @@ -32,6 +32,7 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, //TODO: load library so for different auth type hiChainConnector_ = std::make_shared(); mPincode_ = -1; + mGroupId_ = -1; } DmAuthManager::~DmAuthManager() @@ -190,6 +191,10 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) // authRequestState_->TransitionTo(new AuthRequestNetworkState()); // } CancelDisplay(); + if (!mMemberJoinTimerPtr_) { + std::string mMemberJoinTimerName = "mMemberJoinTimer"; + mMemberJoinTimerPtr_ = std::make_shared(mMemberJoinTimerName); + } mMemberJoinTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT); } @@ -250,14 +255,11 @@ void DmAuthManager::AuthenticateFinish() softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); } -int32_t DmAuthManager::GetDisplayOwner() -{ - return displayOwner_; -} int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) { - AbilityRole role = DmAbilityManager::GetInstance().GetAbilityRole(); + std::shared_ptr abilityMgr_ = std::make_shared();; + AbilityRole role = abilityMgr_->GetAbilityRole(); LOGI("GetAuthenticationParam:: role = %d", (int32_t)role); if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { if (authRequestState_ == nullptr) { @@ -265,8 +267,8 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) return FAIL; } authParam.authType = AUTH_TYPE_PIN; // Currently, only Support PinCode, authType not save. - authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole(); - authParam.pinToken = authRequestContext_->token; + authParam.direction = (int32_t)abilityMgr_->GetAbilityRole(); + authParam.authToken = authRequestContext_->token; LOGI("GetAuthenticationParam, role is ABILITY_ROLE_INITIATIVE"); return SUCCESS; } @@ -287,7 +289,7 @@ void DmAuthManager::OnUserOperate(int32_t action) LOGE("authRequestState_ not exist"); return; } - OnUserReqSessionOperate(action) + OnUserReqSessionOperate(action); return; } @@ -295,7 +297,7 @@ void DmAuthManager::OnUserOperate(int32_t action) LOGE("authResponseState_ not exist"); return; } - OnUserRespSessionOperate(action) + OnUserRespSessionOperate(action); } @@ -309,13 +311,8 @@ void DmAuthManager::OnUserReqSessionOperate(int32_t action) void DmAuthManager::ReqSessionRelease() { - if (mStatus_ == StatusType::STATUS_FINISH || mStatus_ == StatusType::STATUS_INIT) { - LOGI("session is already closed"); - return; - } LOGI("close this session"); - mStatus_ = StatusType::STATUS_FINISH; - SoftbusSession::GetInstance().CloseAuthSession(authRequestContext_->sessionId); + sessionSession_->CloseAuthSession(authRequestContext_->sessionId); LOGI("RequestSession:: close the channel"); } @@ -352,7 +349,7 @@ void DmAuthManager::OnUserRespSessionOperate(int32_t action) void DmAuthManager::Release() { LOGI("ResponseSession::Release in"); - mGroupId_ = ""; + mGroupId_ = -1; mGroupName_ = ""; mPincode_ = -1; } @@ -361,11 +358,9 @@ void DmAuthManager::OnUserConfirm() { LOGI("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_); + hiChainConnector_->RegisterHiChainCallback(mGroupName_,shared_from_this()); + mGroupId_ = hiChainConnector_->GenRequestId(); + int32_t ret = hiChainConnector_->CreateGroup(mGroupId_, mGroupName_); if (ret != SUCCESS) { CancelDisplay(); return; @@ -373,10 +368,27 @@ void DmAuthManager::OnUserConfirm() UpdateDmFaType(DmFaType::FA_TYPE_UNKNOWN); } +void DmAuthManager::UpdateDmFaType(DmFaType type) +{ + switch (type) + { + case DmFaType::FA_TYPE_CONWIFI: + LOGE("ConfignetRequest::UpdateDmFaType SetDmFaType : FA_TYPE_CONWIFI"); + break; + case DmFaType::FA_TYPE_UNKNOWN: + LOGE("ConfignetRequest::UpdateDmFaType SetDmFaType : FA_TYPE_UNKNOWN"); + break; + default: + break; + } + std::shared_ptr abilityMgr_ = std::make_shared();; + abilityMgr_->SetDmFaType(type); +} + std::string DmAuthManager::GenerateGroupName() { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + // GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; std::string groupName = authRequestContext_->targetPkgName + authRequestContext_->hostPkgName + sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); @@ -386,7 +398,8 @@ std::string DmAuthManager::GenerateGroupName() void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) { LOGI("BuildAuthenticationInfo in"); - authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole(); + std::shared_ptr abilityMgr_ = std::make_shared();; + authParam.direction = (int32_t)abilityMgr_->GetAbilityRole(); if (authRequestState_ == nullptr) { LOGE("BuildAuthenticationInfo authRequestState_ is nullptr"); return; @@ -407,14 +420,14 @@ void DmAuthManager::CancelDisplay() jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PICODE_DISPLAY; std::string paramJson = jsonObj.dump(); std::string pkgName = "com.ohos.devicemanagerui"; - DeviceManagerServiceListener::GetInstance().OnFaCall(pkgName, paramJson); + listener_->OnFaCall(pkgName, paramJson); LOGI("Cancel PinCode Display success"); } int32_t DmAuthManager::GeneratePincode() { - return EncryptUtils::GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); } } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 2fe785688..e1925e3d9 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -105,7 +105,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou } LOGI("HiChainConnector::CreateGroup requestId %lld", requestId); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + // GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; @@ -179,7 +179,7 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string connectInf } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + // GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); // std::string connectInfo = GetConnectPara(deviceId, msgResponseAuth); nlohmann::json jsonObj; diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index a8c1d0593..0666e68ea 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -195,9 +195,9 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth return DM_INPUT_PARA_EMPTY; } - type = DmAbilityManager::GetInstance().GetDmFaType(); - DmAbilityManager::GetInstance().StartAbilityDone(); - DmAuthManager::GetInstance().GetAuthenticationParam(authParam); + type = abilityMgr_->GetDmFaType(); + abilityMgr_->StartAbilityDone(); + authMgr_->GetAuthenticationParam(authParam); return DM_OK; } @@ -208,7 +208,7 @@ int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t act return DM_INPUT_PARA_EMPTY; } - DmAuthManager::GetInstance().OnUserOperate(action); + authMgr_->OnUserOperate(action); return DM_OK; } } // namespace DistributedHardware diff --git a/utils/include/cipher/encrypt_utils.h b/utils/include/cipher/encrypt_utils.h deleted file mode 100644 index f55c027b7..000000000 --- a/utils/include/cipher/encrypt_utils.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_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); -private: - typedef struct DmCryptInfo { - const uint8_t *sessionkey; - int32_t sessionkeyLen; - const uint8_t *iv; - int32_t ivLen; - } DmCryptInfo; - - static void MbedtlsGenRootKey(uint8_t *szOut, int32_t szOutLen, int32_t *nOutLen); - static int32_t MbedtlsAesGcmDecrypt(DmCryptInfo *info, const uint8_t *cipherText, - uint32_t cipherTextSize, uint8_t *plain, uint32_t plainLen); - static int32_t MbedtlsAesGcmEncrypt(DmCryptInfo *info, const uint8_t *plainText, - uint32_t plainTextSize, uint8_t *cipherText, uint32_t cipherTextLen); - static void XORBlock(uint8_t *output, const uint8_t *input1, - const uint8_t *input2, const size_t block_size); - static void ByteRightMove(uint8_t *data, size_t dataLen, const uint8_t *inputData, int32_t len, - int32_t count); - static void ByteLeftMove(uint8_t *data, size_t dataLen, const uint8_t *inputData, int32_t len, - int32_t count); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_ENCRYPT_UTILS_H \ No newline at end of file -- Gitee From 32396a5673a3f1b70901df518fcfee50a22ea6be Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Fri, 24 Dec 2021 22:00:48 +0800 Subject: [PATCH 049/110] =?UTF-8?q?=E5=BC=80=E5=85=B3=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependency/softbus/softbus_connector.h | 13 ++- .../dependency/softbus/softbus_connector.cpp | 97 +++++++++++-------- 2 files changed, 65 insertions(+), 45 deletions(-) diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index b2e54a9d1..3dfcd729e 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -41,6 +41,7 @@ public: 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); @@ -62,9 +63,15 @@ private: static void CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo); static ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); private: - INodeStateCb softbusNodeStateCb_; - IDiscoveryCallback softbusDiscoveryCallback_; - IPublishCallback softbusPublishCallback_; + 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_; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 3a9a4a0de..5b552ef98 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -32,53 +32,32 @@ namespace OHOS { namespace DistributedHardware { -IPublishCallback PublishCallback = { - .OnPublishSuccess = SoftbusConnector::OnPublishSuccess, - .OnPublishFail = SoftbusConnector::OnPublishFail -}; - -void ParameterChgCallback(const char *key, const char *value, void *context) -{ - int32_t ret; - if (strcmp(value, DISCOVER_STATUS_ON.c_str()) == 0) { - 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(DM_PKG_NAME.c_str(), &dmPublishInfo, &PublishCallback); - LOGI("service publish result is : %d", ret); - } else if (strcmp(value, DISCOVER_STATUS_OFF.c_str()) == 0) { - ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); - LOGI("service unpublish result is : %d", ret); - } -} - +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() { - LOGI("SoftbusConnector constructor"); - softbusPublishCallback_ = { - .OnPublishSuccess = SoftbusConnector::OnPublishSuccess, - .OnPublishFail = SoftbusConnector::OnPublishFail - }; - softbusDiscoveryCallback_ = { - .OnDeviceFound = SoftbusConnector::OnSoftbusDeviceFound, - .OnDiscoverFailed = SoftbusConnector::OnSoftbusDiscoveryFailed, - .OnDiscoverySuccess = SoftbusConnector::OnSoftbusDiscoverySuccess - }; - softbusNodeStateCb_ = { - .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED, - .onNodeOnline = SoftbusConnector::OnSoftBusDeviceOnline, - .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, - .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged - }; softbusSession_ = std::make_shared(); Init(); } @@ -119,16 +98,25 @@ int32_t SoftbusConnector::Init() 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(), ParameterChgCallback, nullptr); + ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); LOGI("register Watch Parameter result is : %d"); return ret; } @@ -522,5 +510,30 @@ void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) 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 -- Gitee From 35b08bb721f2d9d4292144c4acc3b65b5b6eba83 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Sat, 25 Dec 2021 17:45:45 +0800 Subject: [PATCH 050/110] Fix UnAuthenticateDevice bug --- .../dependency/softbus/softbus_connector.h | 1 + .../src/authentication/dm_auth_manager.cpp | 15 +++++++++++++-- .../src/dependency/softbus/softbus_connector.cpp | 15 +++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index b2e54a9d1..8c964b744 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -44,6 +44,7 @@ public: 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 GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info, int32_t infoLen); public: SoftbusConnector(); ~SoftbusConnector(); diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 881a13a1d..ff8ab7d50 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -101,14 +101,25 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st 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(deviceId, groupList); + hiChainConnector_->GetRelatedGroups(deviceUdid, groupList); if(groupList.size() > 0){ groupId = groupList.front().groupId; } //groupId = authResponseContext_->groupId; - LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s", authResponseContext_->groupId.c_str(), deviceId.c_str()); + LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s, deviceUdid=%s", authResponseContext_->groupId.c_str(), + deviceId.c_str(), deviceUdid.c_str()); hiChainConnector_->DeleteGroup(groupId); return DM_OK; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 3a9a4a0de..83eff0cbd 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -265,6 +265,21 @@ int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) 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; +} + bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) { NodeBasicInfo *info = nullptr; -- Gitee From df0af9f39798afc766b42efd40cbdab7da896c3d Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sat, 25 Dec 2021 23:34:56 +0800 Subject: [PATCH 051/110] =?UTF-8?q?PIN=E7=A0=81=E8=AE=A4=E8=AF=81so?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 12 +- devicemanager.gni | 2 +- ext/config/json_config.h | 80 +++++ ext/pin_auth/BUILD.gn | 46 +-- ext/pin_auth/include/pin_auth.h | 6 +- ext/pin_auth/include/pin_auth_ui.h | 1 - ext/pin_auth/src/pin_auth.cpp | 23 ++ ext/pin_auth/src/pin_auth_ui.cpp | 13 + ohos.build | 3 +- services/devicemanagerservice/BUILD.gn | 2 + .../include/adapter/crypto_adapter.h | 3 +- .../include/adapter/decision_adapter.h | 3 +- .../include/adapter/profile_adapter.h | 2 +- .../include/authentication/authentication.h | 4 +- .../include/config_manager.h | 85 +++++ .../adapter/standard/dm_adapter_manager.cpp | 111 +----- .../src/config_manager.cpp | 332 ++++++++++++++++++ 17 files changed, 583 insertions(+), 145 deletions(-) create mode 100644 ext/config/json_config.h create mode 100644 services/devicemanagerservice/include/config_manager.h create mode 100644 services/devicemanagerservice/src/config_manager.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 4c5872cb0..8f2053820 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -29,12 +29,12 @@ namespace DistributedHardware { const std::string DISCOVER_STATUS_ON = "1"; const std::string DISCOVER_STATUS_OFF = "0"; - const std::string DS_SO_NAME = "libdevicemanagerservice_ds_adapter.z.so"; - const std::string DP_SO_NAME = "libdevicemanagerservice_dp_adapter.z.so"; - const std::string CRYPTO_SO_NAME = "ibdevicemanagerservice_crypto_adapter.z.so"; - const std::string CREATE_IDECISION = "CreateIDecisionAdapter"; - const std::string CREATE_IPROFILE = "CreateIProfileAdapter"; - const std::string CREATE_ICRYPTO = "CreateICryptoAdapterFuncPtr"; + 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; diff --git a/devicemanager.gni b/devicemanager.gni index b226ba5a8..7487a8b32 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -16,7 +16,7 @@ devicemanager_path = "//foundation/distributedhardware/devicemanager" common_path = "${devicemanager_path}/common" utils_path = "${devicemanager_path}/utils" -services_path = "${devicemanager_path}/services" +services_path = "${devicemanager_path}/services/devicemanagerservice" innerkits_path = "${devicemanager_path}/interfaces/inner_kits" ext_path = "${devicemanager_path}/ext" diff --git a/ext/config/json_config.h b/ext/config/json_config.h new file mode 100644 index 000000000..f048ce162 --- /dev/null +++ b/ext/config/json_config.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.so", + "soPath": "/system/lib/" + }, + { + "name": "device_profile", + "type": "PROFILE", + "version": "1.0", + "funcName": "CreateDeviceProfileObject", + "soName": "libdevicemanager_dp_adapter.so", + "soPath": "/system/lib/" + } + ] +})"; + +const std::string authJsonConfigString = +R"({ + "devicemanager_auth_components": [ + { + "name": "pin_auth", + "type": "AUTHENTICATE", + "version": "1.0", + "authType": "pin", + "funcName": "CreatePinAuthObject", + "soName": "libdevicemanagerext_pin_auth.z.so", + "soPath": "/system/lib/" + }, + { + "name": "QRcode_auth", + "type": "AUTHENTICATE", + "version": "1.0", + "authType": "QRcode", + "funcName": "CreateQRcodeAuthObject", + "soName": "libdevicemanager_qrcodeauth.z.so", + "soPath": "/system/lib/" + }, + { + "name": "nfc_auth", + "type": "AUTHENTICATE", + "version": "1.0", + "authType": "nfc", + "funcName": "CreateNfcAuthObject", + "soName": "libdevicemanager_nfcauth.z.so", + "soPath": "/system/lib/" + } + ] +})"; + +} // namespace DistributedHardware +} // namespace OHOS +#endif \ No newline at end of file diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index b84625d6f..9b67853f4 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -19,26 +19,32 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -shared_library("devicemanagerext_pin_auth") { - include_dirs = [ - "${common_path}/include", - "${services_path}/include/adapter/", - ] - - include_dirs += [ - ] - - sources = [ - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerext\"", - "LOG_DOMAIN=0xD004100", - ] - - deps = [ +if (defined(ohos_lite)) { - ] +} else { + ohos_shared_library("devicemanagerext_pin_auth") { + include_dirs = [ + "include", + "${common_path}/include", + "${services_path}/include/adapter", + "${services_path}/include/authentication", + ] + + sources = [ + "src/pin_auth.cpp", + "src/pin_auth_ui.cpp" + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerext\"", + "LOG_DOMAIN=0xD004100", + ] + + subsystem_name = "distributedhardware" + + part_name = "device_manager_base" + } } + diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h index 14c9f2bbf..91368a615 100644 --- a/ext/pin_auth/include/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.h @@ -18,6 +18,7 @@ #include #include +#include "pin_auth_ui.h" #include "authentication.h" namespace OHOS { @@ -26,12 +27,13 @@ class PinAuth : public IAuthentication { public: PinAuth(); ~PinAuth(); - int32_t ShowAuthInfo(); - int32_t StartAuth(); + int32_t ShowAuthInfo() override; + int32_t StartAuth() override; private: 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 index ee339b143..4597afbdf 100644 --- a/ext/pin_auth/include/pin_auth_ui.h +++ b/ext/pin_auth/include/pin_auth_ui.h @@ -16,7 +16,6 @@ #ifndef OHOS_DM_PIN_AUTH_UI_H #define OHOS_DM_PIN_AUTH_UI_H - #include namespace OHOS { diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 2882905a0..17c778c7b 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -16,9 +16,32 @@ #include "pin_auth.h" #include "dm_constants.h" +#include + namespace OHOS { namespace DistributedHardware { +PinAuth::PinAuth() +{ + +} +PinAuth::~PinAuth() +{ +} + +int32_t PinAuth::ShowAuthInfo() +{ + return 0; +} + +int32_t PinAuth::StartAuth() +{ + return 0; +} + +extern "C" IAuthentication* CreatePinAuthObject (void) { + return new PinAuth; +} } } diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index a8e440ca9..a2d801794 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -19,6 +19,19 @@ namespace OHOS { namespace DistributedHardware { +PinAuthUi::PinAuthUi() +{ + +} + +int32_t PinAuthUi::ShowPinDialog() +{ + return 0; +} +int32_t InputPinDialog() +{ + return 0; +} } } diff --git a/ohos.build b/ohos.build index b12a0744e..cc05623b0 100644 --- a/ohos.build +++ b/ohos.build @@ -22,7 +22,8 @@ "//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" ], "test_list": [ "//foundation/distributedhardware/devicemanager/test:test" diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 804f60a3a..ed5a5ad2d 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -125,6 +125,7 @@ if (defined(ohos_lite)) { "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/ipc", "${innerkits_path}/native_cpp/include/ipc/standard", + "${ext_path}/config", "//utils/native/base/include", "//utils/system/safwk/native/include", "//base/notification/ces_standard/frameworks/core/include", @@ -136,6 +137,7 @@ if (defined(ohos_lite)) { ] sources = [ + "src/config_manager.cpp", "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", "src/adapter/standard/dm_adapter_manager.cpp", diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h index 4876ae1ec..cd1e2e0f1 100644 --- a/services/devicemanagerservice/include/adapter/crypto_adapter.h +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.h @@ -17,7 +17,6 @@ #define OHOS_DM_CRYPTO_ADAPTER_H #include -#include namespace OHOS { namespace DistributedHardware { @@ -32,7 +31,7 @@ public: int32_t plainTextLen, int32_t *outLen) = 0; }; -using CreateICryptoAdapterFuncPtr = std::shared_ptr (*)(void); +using CreateICryptoAdapterFuncPtr = ICryptoAdapter* (*)(void); } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/adapter/decision_adapter.h b/services/devicemanagerservice/include/adapter/decision_adapter.h index b820dabbf..c46d115f3 100644 --- a/services/devicemanagerservice/include/adapter/decision_adapter.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.h @@ -18,7 +18,6 @@ #include #include -#include #include "dm_device_info.h" @@ -33,7 +32,7 @@ public: virtual int32_t SortDeviceList(std::vector &infoList, const std::string &sortOptions) = 0; }; -using CreateIDecisionAdapterFuncPtr = std::shared_ptr (*)(void); +using CreateIDecisionAdapterFuncPtr = IDecisionAdapter* (*)(void); } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index b41c056eb..d53d3c504 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -25,7 +25,7 @@ public: virtual int32_t UnRegisterProfileListener() = 0; }; -using CreateIProfileAdapterFuncPtr = std::shared_ptr (*)(void); +using CreateIProfileAdapterFuncPtr = IProfileAdapter* (*)(void); } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h index 09a496f9e..c1d9c493a 100644 --- a/services/devicemanagerservice/include/authentication/authentication.h +++ b/services/devicemanagerservice/include/authentication/authentication.h @@ -16,7 +16,6 @@ #ifndef OHOS_DM_AUTHENTICATION_H #define OHOS_DM_AUTHENTICATION_H - namespace OHOS { namespace DistributedHardware { class IAuthentication { @@ -25,6 +24,9 @@ public: virtual int32_t ShowAuthInfo() = 0; virtual int32_t StartAuth() = 0; }; + +using CreateIAuthAdapterFuncPtr = IAuthentication* (*)(void); } // namespace DistributedHardware } // namespace OHOS + #endif // OHOS_DM_AUTHENTICATION_H diff --git a/services/devicemanagerservice/include/config_manager.h b/services/devicemanagerservice/include/config_manager.h new file mode 100644 index 000000000..17288aa3b --- /dev/null +++ b/services/devicemanagerservice/include/config_manager.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "decision_adapter.h" +#include "profile_adapter.h" +#include "crypto_adapter.h" +#include "authentication.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 { + std::string name; + std::string type; + std::string version; + std::string authType; + std::string funcName; + std::string soName; + std::string soPath; +} AuthSoLoadInfo; + +class DmConfigManager final { +public: + static DmConfigManager& GetInstance(); +public: + ~DmConfigManager(); + void GetAllAuthType (std::vector& allAuthType); + const AdapterSoLoadInfo* GetAdapterSoLoadInfo(const std::string& soName); + const AuthSoLoadInfo* GetAuthSoLoadInfo(const std::string& soName); + std::shared_ptr GetDecisionAdapter(const std::string& soName); + std::shared_ptr GetProfileAdapter(const std::string& soName); + std::shared_ptr GetCryptoAdapter(const std::string& soName); + std::shared_ptr GetAuthAdapter(const std::string& soName); +private: + DmConfigManager(); + DmConfigManager(const DmConfigManager&) = delete; + DmConfigManager& operator= (const DmConfigManager&) = delete; + DmConfigManager(DmConfigManager&&) = delete; + DmConfigManager& operator= (DmConfigManager&&) = delete; +private: + std::mutex authAdapterMutex_; + std::mutex cryptoAdpaterMutex_; + std::mutex decisionAdpaterMutex_; + std::mutex profileAdpaterMutex_; + std::map soAdapterLoadInfo_; + std::map soAuthLoadInfo_; + std::map> decisionAdapterPtr_; + std::map> profileAdapterPtr_; + std::map> cryptoAdapterPtr_; + std::map> authAdapterPtr_; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_OHOS_DM_CONFIG_MANAGER_H \ No newline at end of file diff --git a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp index fede2d727..83381debe 100644 --- a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp @@ -34,127 +34,22 @@ DmAdapterManager::DmAdapterManager() DmAdapterManager::~DmAdapterManager() { - void *so_handle = nullptr; - so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (so_handle != nullptr) { - dlclose(so_handle); - } - - so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (so_handle != nullptr) { - dlclose(so_handle); - } - - so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (so_handle != nullptr) { - dlclose(so_handle); - } LOGI("DmAdapterManager destructor"); } std::shared_ptr DmAdapterManager::GetDecisionAdapter() { - void *so_handle = nullptr; - so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (so_handle != nullptr) - { - LOGI("GetDecisionAdapter: %s has been loaded\n", DS_SO_NAME.c_str()); - if (decisionAdapterPtr_ != nullptr) { - return decisionAdapterPtr_; - } - - CreateIDecisionAdapterFuncPtr func = (CreateIDecisionAdapterFuncPtr)dlsym(so_handle, CREATE_IDECISION.c_str()); - if (dlerror() == nullptr || func == nullptr) { - LOGE("GetDecisionAdapter:Create function is not exist"); - return nullptr; - } - decisionAdapterPtr_ = func(); - return decisionAdapterPtr_; - } else { - void *so_handle = dlopen(DS_SO_NAME.c_str(), RTLD_NOW); - if (so_handle == nullptr) { - LOGE( "GetDecisionAdapter:load so %s failed.\n", DS_SO_NAME.c_str()); - return nullptr; - } - - CreateIDecisionAdapterFuncPtr func = (CreateIDecisionAdapterFuncPtr)dlsym(so_handle, CREATE_IDECISION.c_str()); - if (dlerror() == nullptr || func == nullptr) { - LOGE("GetDecisionAdapter:Create function is not exist"); - return nullptr; - } - decisionAdapterPtr_ = func(); - return decisionAdapterPtr_; - } + return nullptr; } std::shared_ptr DmAdapterManager::GetProfileAdapter() { - void *so_handle = nullptr; - so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (so_handle != nullptr) - { - LOGI("GetProfileAdapter: %s has been loaded\n", DP_SO_NAME.c_str()); - if (profileAdapterPtr_ != nullptr) { - return profileAdapterPtr_; - } - - CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr)dlsym(so_handle, CREATE_IPROFILE.c_str()); - if (dlerror() == nullptr || func == nullptr) { - LOGE("GetProfileAdapter:Create function is not exist"); - return nullptr; - } - profileAdapterPtr_ = func(); - return profileAdapterPtr_; - } else { - void *so_handle = dlopen(DP_SO_NAME.c_str(), RTLD_NOW); - if (so_handle == nullptr) { - LOGE( "GetProfileAdapter:load so %s failed.\n", DP_SO_NAME.c_str()); - return nullptr; - } - - CreateIProfileAdapterFuncPtr func = (CreateIProfileAdapterFuncPtr)dlsym(so_handle, CREATE_IPROFILE.c_str()); - if (dlerror() == nullptr || func == nullptr) { - LOGE("GetProfileAdapter:Create function is not exist"); - return nullptr; - } - profileAdapterPtr_ = func(); - return profileAdapterPtr_; - } + return nullptr; } std::shared_ptr DmAdapterManager::GetCryptoAdapter() { - void *so_handle = nullptr; - so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (so_handle != nullptr) - { - LOGI("GetCryptoAdapter: %s has been loaded\n", CRYPTO_SO_NAME.c_str()); - if (cryptoAdapterPtr_ != nullptr) { - return cryptoAdapterPtr_; - } - - CreateICryptoAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr)dlsym(so_handle, CREATE_ICRYPTO.c_str()); - if (dlerror() == nullptr || func == nullptr) { - LOGE("GetCryptoAdapter:Create function is not exist"); - return nullptr; - } - cryptoAdapterPtr_ = func(); - return cryptoAdapterPtr_; - } else { - void *so_handle = dlopen(CRYPTO_SO_NAME.c_str(), RTLD_NOW); - if (so_handle == nullptr) { - LOGE( "GetCryptoAdapter:load so %s failed.\n", CRYPTO_SO_NAME.c_str()); - return nullptr; - } - - CreateICryptoAdapterFuncPtr func = (CreateICryptoAdapterFuncPtr)dlsym(so_handle, CREATE_ICRYPTO.c_str()); - if (dlerror() == nullptr || func == nullptr) { - LOGE("GetCryptoAdapter:Create function is not exist"); - return nullptr; - } - cryptoAdapterPtr_ = func(); - return cryptoAdapterPtr_; - } + return nullptr; } } } diff --git a/services/devicemanagerservice/src/config_manager.cpp b/services/devicemanagerservice/src/config_manager.cpp new file mode 100644 index 000000000..a84bdc748 --- /dev/null +++ b/services/devicemanagerservice/src/config_manager.cpp @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_log.h" +#include "json_config.h" +#include "dm_constants.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 || + soLoadInfo[i].authType.size() == 0) { + LOGE("adapter json config string exist invalid members"); + continue; + } + soAuthLoadInfo_[soLoadInfo[i].soName] = 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: %s", soLoadInfo[i].authType.c_str()); + } + } 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"); +} + +void DmConfigManager::GetAllAuthType (std::vector& allAuthType) +{ + std::set authType; + for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) { + if ((iter->second).authType == AUTH_LOAD_JSON_KEY) { + authType.insert((iter->second).authType); + } + } + + allAuthType.clear(); + for (auto iter = authType.begin(); iter != authType.end(); iter++) { + allAuthType.push_back(*iter); + } +} + +const AdapterSoLoadInfo* DmConfigManager::GetAdapterSoLoadInfo(const std::string& soName) +{ + if (soAdapterLoadInfo_.find(soName) != soAdapterLoadInfo_.end()) { + return &soAdapterLoadInfo_[soName]; + } + return nullptr; +} + +const AuthSoLoadInfo* DmConfigManager::GetAuthSoLoadInfo(const std::string& soName) +{ + if (soAuthLoadInfo_.find(soName) != soAuthLoadInfo_.end()) { + return &soAuthLoadInfo_[soName]; + } + return nullptr; +} + +std::shared_ptr DmConfigManager::GetDecisionAdapter(const std::string& soName) +{ + auto soInfoIter = soAdapterLoadInfo_.find(soName); + if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != DECISION_JSON_TYPE_KEY) { + LOGE("not find so info or type not match"); + return nullptr; + } + + std::unique_lock locker(decisionAdpaterMutex_); + 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) +{ + auto soInfoIter = soAdapterLoadInfo_.find(soName); + if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != PROFILE_JSON_TYPE_KEY) { + LOGE("not find so info or type not match"); + return nullptr; + } + + std::unique_lock locker(profileAdpaterMutex_); + 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) +{ + auto soInfoIter = soAdapterLoadInfo_.find(soName); + if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != CPYPTO_JSON_TYPE_KEY) { + LOGE("not find so info or type not match"); + return nullptr; + } + + std::unique_lock locker(cryptoAdpaterMutex_); + 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]; +} + +std::shared_ptr DmConfigManager::GetAuthAdapter(const std::string& soName) +{ + auto soInfoIter = soAuthLoadInfo_.find(soName); + if (soInfoIter == soAuthLoadInfo_.end() || (soInfoIter->second).type != AUTH_JSON_TYPE_KEY) { + LOGE("not find so info or type not match"); + return nullptr; + } + + std::unique_lock locker(authAdapterMutex_); + auto ptrIter = authAdapterPtr_.find(soName); + if (ptrIter != authAdapterPtr_.end()) { + return authAdapterPtr_[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 auth so %s failed", soName.c_str()); + return nullptr; + } + } + + dlerror(); + auto func = (CreateIAuthAdapterFuncPtr)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 iAuthentication(func()); + authAdapterPtr_[soName] = iAuthentication; + return authAdapterPtr_[soName]; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file -- Gitee From 32b128d771d2553a246703e5a905dff991cbc588 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sun, 26 Dec 2021 21:33:23 +0800 Subject: [PATCH 052/110] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=9D=83=E9=99=90?= =?UTF-8?q?=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 1 + .../native_cpp/include/device_manager_impl.h | 2 + .../native_cpp/src/device_manager_impl.cpp | 74 +++++++++++++++++-- 3 files changed, 71 insertions(+), 6 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 8f2053820..c0c8f82b9 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -56,6 +56,7 @@ namespace DistributedHardware { DM_UNINIT_FAILED, DM_POINT_NULL, DM_INPUT_PARA_EMPTY, + DM_NOT_SYSTEM_APP, DM_INVALID_VALUE, DM_FLATTEN_OBJECT, DM_MALLOC_ERROR, 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 1b6ad018f..2b605f64b 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -50,6 +50,8 @@ private: 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/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index d71043a9b..4ed51f388 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -41,24 +41,31 @@ using namespace OHOS::AppExecFwk::Constants; namespace OHOS { namespace DistributedHardware { -bool isSystemAppCalling(void) +bool DeviceManagerImpl::isSystemAppCalling(void) { int32_t uid = IPCSkeleton::GetCallingUid(); if (uid >= ROOT_UID && uid < BASE_SYS_UID) { LOGE("check permission true for system uid %d", uid); return true; } - + std::string bundleName; BundleMgrClient bundleMgrClient; bool ret = bundleMgrClient.GetBundleNameForUid(uid, bundleName); - if (ret) { + if (!ret) { + LOGE("get bundle name failed"); return false; } - + BundleInfo bundleInfo; - ret = bundleMgrClient.GetBundleInfo(bundleName, BundleFlag::GET_APPLICATION_INFO_WITH_PERMISSION, bundleInfo); - return (ret && bundleInfo.applicationInfo.isSystemApp); + ret = bundleMgrClient.GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + if (!ret) { + LOGE("get bundle info failed"); + return false; + } + + LOGI("app caller uid is: %d, bundleInfo is: %s", uid, bundleName.c_str()); + return bundleInfo.applicationInfo.isSystemApp; } DeviceManagerImpl & DeviceManagerImpl::GetInstance() @@ -70,6 +77,11 @@ DeviceManagerImpl & DeviceManagerImpl::GetInstance() 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) { LOGE("InitDeviceManager error: Invalid parameter"); return DM_INVALID_VALUE; @@ -89,6 +101,11 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) { 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()) { LOGE("UnInitDeviceManager error: Invalid parameter"); return DM_INVALID_VALUE; @@ -109,6 +126,11 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons std::vector &deviceList) { 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()) { LOGE("GetTrustedDeviceList error: Invalid para"); return DM_INVALID_VALUE; @@ -138,6 +160,11 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons 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); @@ -162,6 +189,11 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, std::shared_ptr callback) { 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) { LOGE("RegisterDevStateCallback error: Invalid para"); return DM_INVALID_VALUE; @@ -175,6 +207,11 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) { 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()) { LOGE("UnRegisterDevStateCallback error: Invalid para"); return DM_INVALID_VALUE; @@ -189,6 +226,11 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons const std::string &extra, std::shared_ptr callback) { 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) { LOGE("StartDeviceDiscovery error: Invalid para"); return DM_INVALID_VALUE; @@ -221,6 +263,11 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { 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()) { LOGE("StopDeviceDiscovery error: Invalid para"); return DM_INVALID_VALUE; @@ -252,6 +299,11 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ const std::string &extra, std::shared_ptr callback) { 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()) { LOGE("AuthenticateDevice error: Invalid para"); return DM_INVALID_VALUE; @@ -285,6 +337,11 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s, deviceId: %s", pkgName.c_str(), deviceId.c_str()); + if (!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; @@ -317,6 +374,11 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons 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()) { LOGE("VerifyAuthentication error: Invalid para"); return DM_INVALID_VALUE; -- Gitee From f0d4bf430ffe304288e26875ee9fa0323708ba8d Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Mon, 27 Dec 2021 16:29:58 +0800 Subject: [PATCH 053/110] abnormal branch --- common/include/dm_constants.h | 7 + services/devicemanagerservice/BUILD.gn | 4 + .../authentication/auth_message_processor.h | 7 +- .../authentication/auth_request_state.h | 7 +- .../authentication/auth_response_state.h | 6 +- .../include/authentication/dm_auth_manager.h | 10 +- .../dependency/hichain/hichain_connector.h | 3 +- .../include/dependency/timer/dm_timer.h | 72 +++++ .../include/discovery/dm_discovery_manager.h | 7 +- .../authentication/auth_message_processor.cpp | 54 +++- .../src/authentication/auth_request_state.cpp | 66 +++- .../authentication/auth_response_state.cpp | 44 ++- .../src/authentication/dm_auth_manager.cpp | 285 +++++++++++++----- .../dependency/hichain/hichain_connector.cpp | 18 ++ .../dependency/softbus/softbus_connector.cpp | 5 + .../dependency/softbus/softbus_session.cpp | 12 +- .../src/dependency/timer/dm_timer.cpp | 153 ++++++++++ .../src/discovery/dm_discovery_manager.cpp | 19 +- 18 files changed, 645 insertions(+), 134 deletions(-) create mode 100644 services/devicemanagerservice/include/dependency/timer/dm_timer.h create mode 100644 services/devicemanagerservice/src/dependency/timer/dm_timer.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index c0c8f82b9..c69cd1b89 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -50,6 +50,7 @@ namespace DistributedHardware { enum { DM_OK = 0, DM_FAILED = 1000, + DM_TIME_OUT, DM_NOT_INIT, DM_INT_MULTIPLE, DM_INIT_FAILED, @@ -76,6 +77,11 @@ namespace DistributedHardware { 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_SOFTBUS_FAILED = 3000, DM_SOFTBUS_CREATE_SESSION_SERVER_FAILED, DM_HICHAIN_FAILED = 4000, @@ -97,6 +103,7 @@ namespace DistributedHardware { 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"; diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index ed5a5ad2d..0752be1c9 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -31,6 +31,7 @@ if (defined(ohos_lite)) { "include/dependency/hichain", "include/dependency/softbus", # "include/dependency/eventbus", + "include/dependency/timer", "include/ipc", "include/ipc/lite", "${common_path}/include", @@ -72,6 +73,7 @@ if (defined(ohos_lite)) { "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", # "src/dependency/eventbus/event_bus.cpp", + "src/dependency/timer/dm_timer.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", @@ -114,6 +116,7 @@ if (defined(ohos_lite)) { "include/dependency/hichain", "include/dependency/softbus", "include/dependency/eventbus", + "include/dependency/timer", "include/ipc", "include/ipc/standard", "include/eventbus", @@ -153,6 +156,7 @@ if (defined(ohos_lite)) { "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/ipc/standard/ipc_cmd_parser.cpp", "src/ipc/standard/ipc_server_listener.cpp", "src/ipc/standard/ipc_server_client_proxy.cpp", diff --git a/services/devicemanagerservice/include/authentication/auth_message_processor.h b/services/devicemanagerservice/include/authentication/auth_message_processor.h index 012863cc7..11c5a119b 100644 --- a/services/devicemanagerservice/include/authentication/auth_message_processor.h +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.h @@ -29,13 +29,14 @@ class ICryptoAdapter; class AuthMessageProcessor { public: AuthMessageProcessor(std::shared_ptr authMgr); - virtual ~AuthMessageProcessor() = default; + ~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); @@ -44,8 +45,10 @@ private: 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::shared_ptr authMgr_; + std::weak_ptr authMgr_; std::shared_ptr cryptoAdapter_; std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; diff --git a/services/devicemanagerservice/include/authentication/auth_request_state.h b/services/devicemanagerservice/include/authentication/auth_request_state.h index b3eaf8208..95e6aa173 100644 --- a/services/devicemanagerservice/include/authentication/auth_request_state.h +++ b/services/devicemanagerservice/include/authentication/auth_request_state.h @@ -25,7 +25,10 @@ class DmAuthManager; struct DmAuthRequestContext; class AuthRequestState : public std::enable_shared_from_this{ public: - virtual ~AuthRequestState() = default; + virtual ~AuthRequestState(){ + authManager_.reset(); + LOGE("~AuthRequestState"); + }; virtual int32_t GetStateType() = 0; virtual void Enter() = 0; void Leave(); @@ -35,7 +38,7 @@ public: void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); protected: - std::shared_ptr authManager_; + std::weak_ptr authManager_; // std::shared_ptr lastState_; std::shared_ptr context_; }; diff --git a/services/devicemanagerservice/include/authentication/auth_response_state.h b/services/devicemanagerservice/include/authentication/auth_response_state.h index a54ecb3ec..e8f50d0ab 100644 --- a/services/devicemanagerservice/include/authentication/auth_response_state.h +++ b/services/devicemanagerservice/include/authentication/auth_response_state.h @@ -25,7 +25,9 @@ class DmAuthManager; struct DmAuthResponseContext; class AuthResponseState : public std::enable_shared_from_this { public: - virtual ~AuthResponseState() = default; + virtual ~AuthResponseState(){ + authManager_.reset(); + }; virtual int32_t GetStateType() = 0; virtual void Enter() = 0; void Leave(); @@ -35,7 +37,7 @@ public: void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); protected: - std::shared_ptr authManager_; + std::weak_ptr authManager_; // std::shared_ptr lastState_; std::shared_ptr context_; }; diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 18d6d6bed..0c3c84ff4 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -29,13 +29,11 @@ #include "auth_request_state.h" #include "auth_response_state.h" #include "auth_message_processor.h" +#include "dm_timer.h" namespace OHOS { namespace DistributedHardware { -const std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; -const int32_t AUTHENTICATE_TIMEOUT = 120; - typedef enum AuthState { AUTH_REQUEST_INIT = 1, AUTH_REQUEST_NEGOTIATE, @@ -70,6 +68,7 @@ enum DmMsgType : int32_t { typedef struct DmAuthRequestContext { int32_t authType; + std::string localDeviceId; std::string deviceId; std::string deviceName; std::string deviceTypeId; @@ -85,12 +84,14 @@ typedef struct DmAuthRequestContext { 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; @@ -137,7 +138,6 @@ public: void SetAuthRequestState(std::shared_ptr authRequestState); void SetAuthResponseState(std::shared_ptr authResponseState); int32_t GetPinCode(); -private: void HandleAuthenticateTimeout(); private: std::shared_ptr softbusConnector_; @@ -151,6 +151,8 @@ private: std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; + std::map> timerMap_; + std::shared_ptr data_; bool isCryptoSupport_ = false; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 483f2b5c1..c0c8896a1 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -56,9 +56,10 @@ public: int32_t AddMember(std::string deviceId, std::string &connectInfo); int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); - void GetRelatedGroups(std::string DeviceId, std::vector &groupList); + int32_t IsDevicesInGroup(std::string hostDevice, std::string peerDevice); private: int64_t GenRequestId(); + void GetRelatedGroups(std::string DeviceId, std::vector &groupList); 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); 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..ea52ce137 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 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/include/discovery/dm_discovery_manager.h b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h index cbac75997..06fb6549d 100644 --- a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h @@ -20,13 +20,10 @@ #include #include "softbus_connector.h" #include "device_manager_service_listener.h" - +#include "dm_timer.h" namespace OHOS { namespace DistributedHardware { -const std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout"; -const int32_t DISCOVERY_TIMEOUT = 120; - typedef struct DmDiscoveryContext { std::string pkgName; std::string extra; @@ -42,13 +39,13 @@ public: 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); -private: 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 diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index eb7e816df..7b02c726f 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -27,6 +27,11 @@ AuthMessageProcessor::AuthMessageProcessor(std::shared_ptr authMg LOGI("AuthMessageProcessor constructor"); } +AuthMessageProcessor::~AuthMessageProcessor() +{ + authMgr_.reset(); +} + std::vector AuthMessageProcessor::CreateAuthRequestMessage() { LOGI("AuthMessageProcessor::CreateAuthRequestMessage start."); @@ -91,6 +96,9 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) case MSG_TYPE_RESP_AUTH: CreateResponseAuthMessage(jsonObj); break; + case MSG_TYPE_REQ_AUTH_TERMINATE: + CreateResponseFinishMessage(jsonObj); + break; default: break; } @@ -106,6 +114,7 @@ void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) json[TAG_CRYPTO_NAME] = cryptoAdapter_->GetName(); json[TAG_CRYPTO_VERSION] = cryptoAdapter_->GetVersion(); json[TAG_DEVICE_ID] = authRequestContext_->deviceId; + json[TAG_LOCAL_DEVICE_ID] = authRequestContext_->localDeviceId; } } @@ -117,21 +126,21 @@ void AuthMessageProcessor::CreateSyncGroupMessage(nlohmann::json &json) void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) { - 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[TAG_REPLY] = authResponseContext_->reply; json[TAG_DEVICE_ID] = authResponseContext_->deviceId; - json[TAG_GROUPIDS] = authResponseContext_->deviceId; //? - json[PIN_CODE_KEY] = authResponseContext_->code; + // 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; @@ -140,6 +149,11 @@ void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) } } +void AuthMessageProcessor::CreateResponseFinishMessage(nlohmann::json &json) +{ + json[TAG_REPLY] = authResponseContext_->reply; +} + int32_t AuthMessageProcessor::ParseMessage(const std::string &message) { LOGE(" AuthMessageProcessor ParseMessage"); @@ -179,20 +193,28 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) 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_->deviceId = json[TAG_GROUPIDS]; - authResponseContext_->code = json[PIN_CODE_KEY]; + // 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]; @@ -234,6 +256,9 @@ void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) if (json.contains(TAG_DEVICE_ID)) { authResponseContext_->deviceId = json[TAG_DEVICE_ID]; } + if (json.contains(TAG_LOCAL_DEVICE_ID)) { + authResponseContext_->localDeviceId = json[TAG_LOCAL_DEVICE_ID]; + } } void AuthMessageProcessor::SetRequestContext(std::shared_ptr authRequestContext) @@ -250,5 +275,10 @@ std::shared_ptr AuthMessageProcessor::GetResponseContext( { return authResponseContext_; } + +std::shared_ptr AuthMessageProcessor::GetRequestContext() +{ + return authRequestContext_; +} } } \ 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 index 2fff06d98..df353d3f0 100644 --- a/services/devicemanagerservice/src/authentication/auth_request_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -46,8 +46,13 @@ std::shared_ptr AuthRequestState::GetAuthContext() { void AuthRequestState::TransitionTo(std::shared_ptr state) { LOGE("AuthRequestState::TransitionTo"); - state->SetAuthManager(authManager_); - authManager_->SetAuthRequestState(state); + 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(); @@ -58,7 +63,12 @@ int32_t AuthRequestInitState::GetStateType() { } void AuthRequestInitState::Enter() { - authManager_->EstablishAuthChannel(context_->deviceId); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->EstablishAuthChannel(context_->deviceId); } int32_t AuthRequestNegotiateState::GetStateType() { @@ -67,7 +77,12 @@ int32_t AuthRequestNegotiateState::GetStateType() { void AuthRequestNegotiateState::Enter() { // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 - authManager_->StartNegotiate(context_->sessionId); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->StartNegotiate(context_->sessionId); } int32_t AuthRequestNegotiateDoneState::GetStateType() { @@ -81,8 +96,12 @@ void AuthRequestNegotiateDoneState::Enter() { // authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH); // std::string message; // softbusSession_->SendData(context_.sessionId, message); - LOGE("DmAuthManager::EstablishAuthChannel session id"); - authManager_->SendAuthRequest(context_->sessionId); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->SendAuthRequest(context_->sessionId); } int32_t AuthRequestReplyState::GetStateType() { @@ -95,7 +114,12 @@ void AuthRequestReplyState::Enter() { //2. 用户授权同意 //3. 回调给认证实现模块,启动认证 - authManager_->StartRespAuthProcess(); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->StartRespAuthProcess(); } int32_t AuthRequestInputState::GetStateType() { @@ -108,7 +132,12 @@ void AuthRequestInputState::Enter() { // //2. 验证认证信息 LOGE("DmAuthManager::AuthRequestInputState"); std::string test = ""; - authManager_->VerifyAuthentication(test, test); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->VerifyAuthentication(test, test); } int32_t AuthRequestJoinState::GetStateType() { @@ -118,7 +147,12 @@ int32_t AuthRequestJoinState::GetStateType() { void AuthRequestJoinState::Enter() { //1. 加入群组 LOGE("DmAuthManager::AuthRequestJoinState"); - authManager_->AddMember(context_->deviceId); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->AddMember(context_->deviceId); } int32_t AuthRequestNetworkState::GetStateType() { @@ -127,7 +161,12 @@ int32_t AuthRequestNetworkState::GetStateType() { void AuthRequestNetworkState::Enter() { //1. 进行组网 - authManager_->JoinNetwork(); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->JoinNetwork(); } int32_t AuthRequestFinishState::GetStateType() { @@ -137,7 +176,12 @@ int32_t AuthRequestFinishState::GetStateType() { void AuthRequestFinishState::Enter() { //1. 清理资源 //2. 通知对端认证结束,并关闭认证通道 - authManager_->AuthenticateFinish(); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->AuthenticateFinish(); } } } diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp index 1a14eb20a..75f8a8b09 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -48,10 +48,15 @@ void AuthResponseState::SetAuthManager(std::shared_ptr authManage void AuthResponseState::TransitionTo(std::shared_ptr state) { LOGI("AuthRequestState:: TransitionTo"); - state->SetAuthManager(authManager_); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + state->SetAuthManager(stateAuthManager); // state->SetLastState((std::shared_ptr)this); // lastState_ = state; - authManager_->SetAuthResponseState(state); + stateAuthManager->SetAuthResponseState(state); state->SetAuthContext(context_); this->Leave(); state->Enter(); @@ -64,7 +69,7 @@ int32_t AuthResponseInitState::GetStateType() void AuthResponseInitState::Enter() { - LOGI("AuthRequestState:: AuthResponseInitState Enter"); + LOGI("AuthResponse:: AuthResponseInitState Enter"); //1.认证通道建立后,进入该状态 } @@ -77,8 +82,13 @@ void AuthResponseNegotiateState::Enter() { //1.收到协商消息后进入 - //2. 获取本地加解密模块信息,并回复消息 - authManager_->RespNegotiate(context_->sessionId); + //2. 获取本地加解密模块信息,并回复消 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->RespNegotiate(context_->sessionId); } int32_t AuthResponseConfirmState::GetStateType() @@ -91,8 +101,13 @@ void AuthResponseConfirmState::Enter() //委托授权UI模块进行用户交互 //如果交互成功 // TransitionTo(new AuthResponseGroupState()); - LOGI("AuthRequestState:: AuthResponseConfirmState Enter"); - authManager_->StartAuthProcess(context_->authType); + LOGI("AuthResponse:: AuthResponseConfirmState Enter"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->StartAuthProcess(context_->authType); } int32_t AuthResponseGroupState::GetStateType() @@ -104,9 +119,14 @@ void AuthResponseGroupState::Enter() { // //1.创建群组, // authManagerPtr_->GetHiChainConnector()->CreateGroup(); - LOGI("AuthRequestState:: AuthResponseGroupState Enter"); + LOGI("AuthResponse:: AuthResponseGroupState Enter"); std::string groupName = "1234567890"; - authManager_->CreateGroup(context_->requestId, groupName); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->CreateGroup(context_->requestId, groupName); } int32_t AuthResponseShowState::GetStateType() @@ -130,6 +150,12 @@ void AuthResponseFinishState::Enter() //1.结束UI显示 //2.清理资源,结束状态机 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->AuthenticateFinish(); } } } diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index ff8ab7d50..09fd16bd1 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -20,17 +20,41 @@ #include "dm_log.h" #include "dm_constants.h" #include "auth_message_processor.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"; + + 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; +} +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 + data_ = std::shared_ptr(this); std::string pkgName = "com.ohos.devicemangagerdemo"; - sessionSession_->RegisterSessionCallback(pkgName, std::shared_ptr(this)); + sessionSession_->RegisterSessionCallback(pkgName, data_); // hiChainConnector_ = std::make_shared(); } @@ -42,6 +66,7 @@ DmAuthManager::~DmAuthManager() 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); @@ -57,9 +82,10 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au return DM_AUTH_BUSINESS_BUSY; } sessionSession_->UnRegisterSessionCallback(pkgName); - sessionSession_->RegisterSessionCallback(pkgName, std::shared_ptr(this)); + sessionSession_->RegisterSessionCallback(pkgName, data_); // hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + authMessageProcessor_ = std::make_shared(data_); authRequestContext_ = std::make_shared(); authRequestContext_->authType = authType; authRequestContext_->deviceId = deviceId; @@ -81,56 +107,39 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au authRequestContext_->appIcon = jsonObject[APP_ICON_KEY]; } } - authMessageProcessor_ = std::make_shared(std::shared_ptr(this)); + authRequestState_ = std::shared_ptr(new AuthRequestInitState()); - authRequestState_->SetAuthManager(std::shared_ptr(this)); + authRequestState_->SetAuthManager(data_); authRequestState_->SetAuthContext(authRequestContext_); - authMessageProcessor_->SetRequestContext(authRequestContext_); authRequestState_->Enter(); -// auto authenticateStartTimer = [this]() { -// HandleAuthenticateTimeout(); -// }; -// EventBus::PostTask(authenticateStartTimer, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT); + 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; - } - //groupId = authResponseContext_->groupId; - LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s, deviceUdid=%s", authResponseContext_->groupId.c_str(), - deviceId.c_str(), deviceUdid.c_str()); - hiChainConnector_->DeleteGroup(groupId); - return DM_OK; } int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) { - //IF input pincode success; LOGI("DmAuthManager::VerifyAuthentication"); - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT) { + timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + int32_t pinCode = 123456; + int32_t times = 0; + if (pinCode == authResponseContext_->code && authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT){ authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); + }else if (pinCode != authResponseContext_->code && times < 3) { + times++; + //TODO input again + }else { + authResponseContext_->reply = AuthState::AUTH_REQUEST_JOIN; + authRequestContext_->reason = DM_AUTH_INPUT_FAILED; + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + return DM_FAILED; } LOGI("DmAuthManager::VerifyAuthentication complete"); return DM_OK; @@ -141,25 +150,30 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI LOGI("DmAuthManager::OnSessionOpened sessionId=%d result=%d", sessionId, result); if (sessionSide == AUTH_SESSION_SIDE_SERVER) { if (authResponseState_ == nullptr) { - authMessageProcessor_ = std::make_shared(std::shared_ptr(this)); + authMessageProcessor_ = std::make_shared(data_); authResponseState_ = std::shared_ptr(new AuthResponseInitState()); - authResponseState_->SetAuthManager(std::shared_ptr(this)); + authResponseState_->SetAuthManager(data_); authResponseState_->Enter(); hiChainConnector_ = std::make_shared(); - hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + hiChainConnector_->RegisterHiChainCallback(pkgName, data_); + authResponseContext_ = std::make_shared(); } else { - //TODO:RESP_AUTH 认证失败,流程终止 + return; } } else { - authResponseState_ = std::shared_ptr(new AuthResponseInitState()); - authResponseState_->SetAuthManager(std::shared_ptr(this)); - authResponseState_->Enter(); if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + hiChainConnector_ = std::make_shared(); + hiChainConnector_->RegisterHiChainCallback(pkgName, data_); 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()); + authResponseContext_ = std::make_shared(); + authResponseContext_->reply = AuthState::AUTH_REQUEST_INIT; + authRequestContext_->reason = DM_AUTH_STATE_FAILED; authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } } @@ -173,9 +187,7 @@ void DmAuthManager::OnSessionClosed(const std::string &pkgName, int32_t sessionI void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message) { LOGI("DmAuthManager::OnDataReceived start"); - authResponseContext_ = std::make_shared(); authResponseContext_ ->sessionId = sessionId; - authResponseState_->SetAuthContext(authResponseContext_); authMessageProcessor_->SetResponseContext(authResponseContext_); int32_t ret = authMessageProcessor_->ParseMessage(message); if (ret != DM_OK) { @@ -183,38 +195,51 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId return; } authResponseContext_ = authMessageProcessor_->GetResponseContext(); - authResponseState_->SetAuthContext(authResponseContext_); + 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) { 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_INIT || authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT || + authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { 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_INIT || authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestReplyState())); } else { - //状态错误,流程终止 + LOGE("Device manager auth state error"); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } 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"); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } + break; + case MSG_TYPE_REQ_AUTH_TERMINATE: + if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); + } else { + LOGE("Device manager auth state error"); } break; default: @@ -227,6 +252,16 @@ 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); + } authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseShowState())); int32_t pinCode = 123456; authResponseContext_->code = pinCode; @@ -236,17 +271,40 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &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) { -// if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) { -// authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNetworkState())); -// } + 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) @@ -256,6 +314,9 @@ void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) 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())); } } @@ -263,14 +324,34 @@ void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) void DmAuthManager::StartNegotiate(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); + DmDeviceInfo localDevice; + softbusConnector_->GetLocalDeviceInfo(localDevice); + authRequestContext_->localDeviceId = localDevice.deviceId; + int32_t ret = hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); + if (ret != DM_OK){ + LOGE("DmAuthManager::EstablishAuthChannel device is in group"); + authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE; + authRequestContext_->reason = DM_AUTH_DEVICE_AUTHED; + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + return; + } std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); - //TODO::设置消息等待超时时间 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); + int32_t ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); + if (ret != DM_OK){ + LOGE("DmAuthManager::EstablishAuthChannel device is in group"); + authResponseContext_->reply = DM_AUTH_PEER_REJECT; + return; + } + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); if (jsonObject.is_discarded()){ @@ -294,14 +375,17 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) 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; } std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); - //TODO::设置消息等待超时时间 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 &authType) @@ -309,24 +393,32 @@ void DmAuthManager::StartAuthProcess(const int32_t &authType) //1. 收到请求响应,判断用户响应结果 //2. 用户授权同意 //3. 回调给认证实现模块,启动认证 - // std::shared_ptr authentication = authenticationMap_[authType]; - // authentication->StartAuth(); - LOGI("DmAuthManager:: StartAuthProcess 111"); - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM){ + LOGI("DmAuthManager:: StartAuthProcess"); + authResponseContext_->reply = 0; + if (authResponseContext_->reply == DM_OK && 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); } - // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestInputState())); } void DmAuthManager::StartRespAuthProcess() { LOGI("DmAuthManager::StartRespAuthProcess StartRespAuthProcess", authResponseContext_->sessionId); - softbusConnector_->GetSoftbusSession()->CloseAuthSession(authResponseContext_->sessionId); + timerMap_[CONFIRM_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); if (authResponseContext_->reply == 0){ + 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())); - return; - } // hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); - LOGE("do not accept"); + }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(int64_t requestId, const std::string &groupName) @@ -337,7 +429,7 @@ void DmAuthManager::CreateGroup(int64_t requestId, const std::string &groupName) void DmAuthManager::AddMember(const std::string &deviceId) { - LOGI("DmAuthManager::AddMember complete"); + LOGI("DmAuthManager::AddMember start"); nlohmann::json jsonObject; jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId; jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName; @@ -345,9 +437,9 @@ void DmAuthManager::AddMember(const std::string &deviceId) jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; std::string connectInfo = jsonObject.dump(); - std::string pkgName = "com.ohos.devicemangagerdemo"; - hiChainConnector_ = std::make_shared(); - hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + 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; @@ -365,16 +457,61 @@ std::string DmAuthManager::GetConnectAddr(std::string deviceId) 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() { - //清理资源,关闭通道 - softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); + LOGI("DmAuthManager::AuthenticateFinish start"); + if (authRequestState_ == nullptr){ + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW){ + //todo close show pin dialog + } + authResponseContext_ = nullptr; + authResponseState_ = nullptr; + authMessageProcessor_ = nullptr; + }else if(authRequestState_ != nullptr){ + std::string flag = ""; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + if (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN){ + listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, + DM_AUTH_INPUT_FAILED, flag); + } + + if (authResponseContext_->reply == AuthState::AUTH_REQUEST_FINISH){ + listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, + DM_OK, flag); + } + + listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, authRequestContext_->token, + authResponseContext_->reply, std::to_string(authRequestContext_->reason)); + + sessionSession_->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; + hiChainConnector_ = nullptr; + authRequestState_ = nullptr; + authMessageProcessor_ = nullptr; + } + LOGI("DmAuthManager::AuthenticateFinish complete"); } void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) { + LOGI("DmAuthManager::GetIsCryptoSupport start"); if (authResponseState_ == nullptr){ isCryptoSupport = false; return; diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 3f4c4a13c..5a882dd12 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -355,6 +355,24 @@ void HiChainConnector::GetSyncGroupList(std::vector &groupList, std:: } } +int32_t 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 DM_FAILED; + } + } + } + return DM_OK; +} + bool HiChainConnector::IsGroupInfoInvalid(GroupInfo &group) { if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC || diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 7c4da878a..228983edf 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -437,10 +437,15 @@ void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason 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_) { diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 13701061e..2e6fa04c8 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -153,9 +153,9 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) void SoftbusSession::OnSessionClosed(int32_t sessionId) { LOGI("OnSessionClosed, sessionId:%d", sessionId); - for (auto & iter : sessionCallbackMap_) { - iter.second->OnSessionClosed(iter.first, sessionId); - } + // for (auto & iter : sessionCallbackMap_) { + // iter.second->OnSessionClosed(iter.first, sessionId); + // } } void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) @@ -170,7 +170,6 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 iter.second->GetIsCryptoSupport(isCryptoSupport); } if (isCryptoSupport){ - LOGI("OnBytesReceived completed111111111"); uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); if (buf == nullptr) { LOGE("SendMsg: malloc memory failed"); @@ -189,15 +188,12 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 } free(buf); } - LOGI("OnBytesReceived completed22222222"); char *dataChar = (char *)data; std::string message = dataChar; - LOGI("OnBytesReceived completed33333333333"); for (auto & iter : sessionCallbackMap_) { - LOGI("OnBytesReceived completed4444444444"); iter.second->OnDataReceived(iter.first, sessionId, message); } - LOGI("OnBytesReceived completed5555555555"); + LOGI("OnBytesReceived completed"); } } // namespace DistributedHardware 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..a9e5518ea --- /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::WiteforTimeout, 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::WiteforTimeout() +{ + 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; +} +} +} diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index fced39c0f..6dfa1f368 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -20,6 +20,19 @@ namespace OHOS { namespace DistributedHardware { +namespace{ + std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout"; + int32_t DISCOVERY_TIMEOUT = 120; +} +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) @@ -48,10 +61,8 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId}; discoveryContextMap_.emplace(pkgName, context); softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(this)); -// auto discoveryTimer = [this]() { -// HandleDiscoveryTimeout(); -// }; -// EventBus::PostTask(discoveryTimer, DISCOVERY_TIMEOUT_TASK, DISCOVERY_TIMEOUT); + std::shared_ptr discoveryTimer_ = std::make_shared(DISCOVERY_TIMEOUT_TASK); + discoveryTimer_->Start(DISCOVERY_TIMEOUT, TimeOut, this); return softbusConnector_->StartDiscovery(subscribeInfo); } -- Gitee From cc931aeda54c73193074a3f85a39e943d95e1eff Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Mon, 27 Dec 2021 17:07:48 +0800 Subject: [PATCH 054/110] 11 --- .../include/authentication/dm_auth_manager.h | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index e69de29bb..811e0e0f4 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_AUTH_MANAGER_H +#define OHOS_DM_AUTH_MANAGER_H + +#include +#include + +#include "authentication.h" +#include "dm_ability_manager.h" +#include "dm_device_info.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" + +namespace OHOS { +namespace DistributedHardware { + +const std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; +const int32_t AUTHENTICATE_TIMEOUT = 120; + +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; +} + +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 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; + std::vector syncGroupList; +} DmAuthRequestContext ; + +typedef struct DmAuthResponseContext { + int32_t authType; + std::string deviceId; + 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; + 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: + static DmAuthManager& GetInstance(); +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 &pkgName, 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(int64_t requestId, const std::string &groupName); + void AddMember(const std::string &deviceId); + std::string GetConnectAddr(std::string deviceId); + void JoinNetwork(); + void AuthenticateFinish(); + int32_t GetAuthenticationParam(DmAuthParam &authParam); + void OnUserOperate(int32_t action); + void GetIsCryptoSupport(bool &isCryptoSupport); + void SetAuthRequestState(std::shared_ptr authRequestState); + void SetAuthResponseState(std::shared_ptr authResponseState); + int32_t GetPinCode(); +private: + void HandleAuthenticateTimeout(); + void OnUserConfirm(); + void OnUserReqSessionOperate(int32_t action); + void OnUserRespSessionOperate(int32_t action); + void ReqSessionRelease(); + std::string GenerateGroupName(); + void Release(); + void CancelDisplay(); + int32_t GeneratePincode(); + void BuildAuthenticationInfo(DmAuthParam &authParam); + void UpdateDmFaType(DmFaType type); +private: + std::shared_ptr softbusConnector_; + std::shared_ptr sessionSession_; + std::shared_ptr hiChainConnector_; + std::shared_ptr listener_; + std::shared_ptr adapterMgr_; + std::map> authenticationMap_; + int32_t displayOwner_ = 0; + std::shared_ptr authRequestState_ = nullptr; + std::shared_ptr authResponseState_ = nullptr; + std::shared_ptr authRequestContext_; + std::shared_ptr authResponseContext_; + std::shared_ptr authMessageProcessor_; + std::shared_ptr mMemberJoinTimerPtr_; + int32_t mPincode_; + int32_t mGroupId_; + std::string mGroupName_; + bool isCryptoSupport_ = false; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_H -- Gitee From 92e85282f246441ad00f8d30449171d940c45c6a Mon Sep 17 00:00:00 2001 From: "jia.li" Date: Mon, 27 Dec 2021 19:17:55 +0800 Subject: [PATCH 055/110] TDD --- test/unittest/BUILD.gn | 90 ++++- .../UTTest_device_manager_service.cpp | 121 ++++++ test/unittest/UTTest_device_manager_service.h | 30 ++ test/unittest/UTTest_hichain_connector.cpp | 225 +++++++++++ test/unittest/UTTest_hichain_connector.h | 36 ++ test/unittest/UTTest_softbus_connector.cpp | 357 ++++++++++++++++++ test/unittest/UTTest_softbus_connector.h | 40 ++ test/unittest/UTTest_softbus_session.cpp | 170 +++++++++ test/unittest/UTTest_softbus_session.h | 34 ++ 9 files changed, 1100 insertions(+), 3 deletions(-) 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_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 diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 7a5cb96f7..27c0e381d 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -18,7 +18,14 @@ module_out_path = "deviceManager_stander/inner_kits" group("unittest") { testonly = true - deps = [ ":device_manager_impl_test" ] + deps = [ ":device_manager_impl_test", + ":UTTest_dm_discovery_manager", + ":UTTest_device_manager_service", + ":UTTest_softbus_connector", + ":UTTest_softbus_session", + ":UTTest_hichain_connector", + + ] } ## UnitTest device_manager_impl_test {{{ @@ -32,6 +39,59 @@ ohos_unittest("device_manager_impl_test") { ## 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_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_discovery_manager {{{ +ohos_unittest("UTTest_dm_discovery_manager") { + module_out_path = module_out_path + + sources = [ "UTTest_dm_discovery_manager.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_dm_discovery_manager }}} ## Build device_manager_test_common.a {{{ config("device_manager_test_common_public_config") { include_dirs = [ @@ -47,9 +107,30 @@ config("device_manager_test_common_public_config") { "${common_path}/include/ipc/model", "${utils_path}/include", "${utils_path}/include/ipc/standard", + "${services_path}/include", + "${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/dsoftbus/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", + "//base/security/deviceauth/interfaces/innerkits", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/deviceinfo/", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/devicestate", + "//foundation/multimedia/histreamer/engine/pipeline/core", ] - cflags = [ +cflags = [ "-Wall", "-Werror", "-g3", @@ -69,10 +150,13 @@ ohos_static_library("device_manager_test_common") { "${utils_path}:devicemanagerutils", "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//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", + "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager", ] } -## Build device_manager_test_common.a }}} +## Build device_manager_test_common.a }}} \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp new file mode 100644 index 000000000..133f250e4 --- /dev/null +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -0,0 +1,121 @@ +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "UTTest_device_manager_service.h" + + +namespace OHOS +{ +namespace DistributedHardware +{ + +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); + +void DeviceManagerImplTest::SetUp() +{ +} + +void DeviceManagerImplTest::TearDown() +{ +} + +void DeviceManagerImplTest::SetUpTestCase() +{ +} + +void DeviceManagerImplTest::TearDownTestCase() +{ +} +namespace +{ + + +HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery1, testing::ext::TestSize.Level0) +{ + 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); + // ASSERT_NE(ret,DM_NOT_INIT); +} +HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + DmSubscribeInfo subscribeInfo; + std::string extra = "test"; + // DeviceManagerService::GetInstance().Init(); + int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + pkgName = "1com.ohos.test1"; + ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + ASSERT_NE(ret, DM_DISCOVERY_REPEATED); +} + +HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery1, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 1; + int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + EXPECT_EQ(ret, DM_NOT_INIT); +} +HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo1, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + //DeviceManagerService::GetInstance().Init(); + int ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo2, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeviceManagerService::GetInstance().Init(); + int ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, 0); +} +HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, 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); +} + +HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery2, 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); +} +HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery3, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 1; + int32_t freq = -1; + int32_t mode = -1; + int32_t medium = -1; + DmSubscribeInfo testInfo = { + .subscribeId = 1, + .mode = (DmDiscoverMode)mode, + .medium = (DmExchangeMedium)medium, + .freq = (DmExchangeFreq)freq, + .isSameAccount = true, + .isWakeRemote = true, + .capability = "osdCapability", + }; + std::string extra = "test"; + DeviceManagerService::GetInstance().Init(); + DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, testInfo, extra); + int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + EXPECT_TRUE(ret != DM_OK); +} + + + +} +} +} diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h new file mode 100644 index 000000000..1d0ad1e69 --- /dev/null +++ b/test/unittest/UTTest_device_manager_service.h @@ -0,0 +1,30 @@ +#ifndef OHOS_UTTEST_DM_SERVICE_H +#define OHOS_UTTEST_DM_SERVICE_H + + +#include +#include +#include +#include + +#include "dm_auth_manager.h" +#include "dm_device_info_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "softbus_connector.h" +#include "single_instance.h" +#include "device_manager_service.h" +#include "device_manager_service_listener.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; +}; +}} +#endif // OHOS_DM_SERVICE_H diff --git a/test/unittest/UTTest_hichain_connector.cpp b/test/unittest/UTTest_hichain_connector.cpp new file mode 100644 index 000000000..ffe00dbf7 --- /dev/null +++ b/test/unittest/UTTest_hichain_connector.cpp @@ -0,0 +1,225 @@ +#include "hichain_connector.h" + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +#include "parameter.h" + +#include "hichain_connector_callback.h" +#include "dm_anonymous.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_random.h" +#include "UTTest_hichain_connector.h" +namespace OHOS +{ +namespace DistributedHardware +{ +void DeviceManagerImplTest::SetUp() +{ + // DmDiscoveryManage *m_DmDiscoveryManage; +} + +void DeviceManagerImplTest::TearDown() +{ +} + +void DeviceManagerImplTest::SetUpTestCase() +{ +} + +void DeviceManagerImplTest::TearDownTestCase() +{ +} +namespace +{ + +HWTEST_F(DeviceManagerImplTest, CreateGroup1, testing::ext::TestSize.Level0) +{ + int64_t requestId = 123456; + std::string groupName = "lijia"; + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector-> deviceGroupManager_ = nullptr; + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_INVALID_VALUE); +} + + +HWTEST_F(DeviceManagerImplTest, CreateGroup2, testing::ext::TestSize.Level0) +{ + int64_t requestId = 233444; + std::string groupName; + std::string DM_PKG_NAME = " "; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, CreateGroup3, testing::ext::TestSize.Level0) +{ + int64_t requestId = 123456; + std::string groupName = "lijia"; + // std::string DM_PKG_NAME = " "; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_OK); +} + + +HWTEST_F(DeviceManagerImplTest, GetGroupInfo1, 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); +} +HWTEST_F(DeviceManagerImplTest, GetGroupInfo2, testing::ext::TestSize.Level0) +{ + std::shared_ptr hichainConnector = std::make_shared(); + std::string groupName = " "; + 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); +} + +HWTEST_F(DeviceManagerImplTest, GetGroupInfo3, 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); + std::cout << "ret= " << ret << std ::endl; + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid1, testing::ext::TestSize.Level0) +{ + GroupInfo group; + group.groupName = "dkdkkdkdk"; + group.groupId = 1; + group.groupOwner = "ohos.disware.devicemanagersdsdss"; + group.groupType = 1; + group.groupVisibility = -1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, true); +} + +HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid2, testing::ext::TestSize.Level0) +{ + GroupInfo group; + group.groupName = "lijia"; + group.groupId = 1; + group.groupOwner = "ohos.disware.devicemanagersdsdss"; + group.groupType = 1; + group.groupVisibility = 1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, true); +} + +HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid3, testing::ext::TestSize.Level0) +{ + GroupInfo group; + group.groupName = "lijia"; + group.groupId = -1; + group.groupName = "ohos.distributedhardware.devicemanager"; + group.groupType = 0; + group.groupVisibility = -1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, true); +} + + +HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup1, testing::ext::TestSize.Level0) + +{ + std::string groupId = "1746"; + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + // dmSubscribeInfo.capability = -1290002262 ; + std::shared_ptr hichainConnector = std::make_shared(); + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + + if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { + deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; + } + int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup2, 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); +} + +HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup3, testing::ext::TestSize.Level0) + +{ + std::string groupId = "123445"; + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + // dmSubscribeInfo.capability = -1290002262 ; + std::shared_ptr hichainConnector = std::make_shared(); + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); + EXPECT_EQ(ret, 0); +} +HWTEST_F(DeviceManagerImplTest, GenRequestId1, testing::ext::TestSize.Level0) +{ + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GenRequestId(); + std::cout << "ret= " << ret << std ::endl; + EXPECT_TRUE (ret != 0); +} + + + +} + +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_hichain_connector.h b/test/unittest/UTTest_hichain_connector.h new file mode 100644 index 000000000..4e926ee08 --- /dev/null +++ b/test/unittest/UTTest_hichain_connector.h @@ -0,0 +1,36 @@ +#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_discovery_manager.h" +#include "dm_device_state_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; +}; + + +} +} +#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..af0c96239 --- /dev/null +++ b/test/unittest/UTTest_softbus_connector.cpp @@ -0,0 +1,357 @@ +#include "softbus_connector.h" + +#include +#include +#include +#include + +#include "parameter.h" +#include "system_ability_definition.h" + +#include "dm_log.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "UTTest_softbus_connector.h" + +namespace OHOS +{ +namespace DistributedHardware +{ +void DeviceManagerImplTest::SetUp() +{ + // DmDiscoveryManage *m_DmDiscoveryManage; +} + +void DeviceManagerImplTest::TearDown() +{ +} + +void DeviceManagerImplTest::SetUpTestCase() +{ +} + +void DeviceManagerImplTest::TearDownTestCase() +{ +} +namespace +{ + + +static std::shared_ptr softbusConnector = std::make_shared(); +HWTEST_F(DeviceManagerImplTest, Init1, testing::ext::TestSize.Level0) +{ + std::string DM_PKG_NAME = " "; + // char discoverStatus[10] = "not exist"; + int ret = softbusConnector->Init(); + EXPECT_FALSE (ret != DM_OK); +} +HWTEST_F(DeviceManagerImplTest, Init2, testing::ext::TestSize.Level0) +{ + int ret = softbusConnector->Init(); + EXPECT_FALSE (ret = DM_OK); +} +HWTEST_F(DeviceManagerImplTest, Init3, testing::ext::TestSize.Level0) +{ + // char discoverStatus = '0'; + int ret = softbusConnector->Init(); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, RegisterSoftbusDiscoveryCallback1, 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(nullptr)); + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 1); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, RegisterSoftbusDiscoveryCallback2, 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_)); + // softbusConnector->discoveryDeviceInfoMap_; + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 1); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, RegisterSoftbusDiscoveryCallback3, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + 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_)); + // softbusConnector->discoveryDeviceInfoMap_; + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 1); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusDiscoveryCallback1, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + //std::shared_ptr listener_ = std::make_shared(); + //std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); + int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); + // softbusConnector->discoveryDeviceInfoMap_; + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 0); + EXPECT_EQ(ret, DM_OK); + // softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(discoveryMgr_)); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusDiscoveryCallback2, 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_); + softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(nullptr)); + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 1); + int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); + // softbusConnector->discoveryDeviceInfoMap_; + int ret2 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret2, 0); + EXPECT_EQ(ret, DM_OK); + // softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(discoveryMgr_)); +} +HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusDiscoveryCallback3, 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_); + softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(discoveryMgr_)); + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 1); + int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); + // softbusConnector->discoveryDeviceInfoMap_; + int ret2 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + EXPECT_EQ(ret2, 0); + EXPECT_EQ(ret, DM_OK); +} + +// HWTEST_F(DeviceManagerImplTest, RegisterSoftbusStateCallback2, 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_); +// std::cout << "11111111111"; +// std::shared_ptr deviceState = std::make_shared(softbusConnector, listener); +// std::cout << "111111112222222222111"; +// int ret = softbusConnector->RegisterSoftbusStateCallback(pkgName, std::shared_ptr(deviceState)); +// std::cout << "1111111133333333333333111"; +// // softbusConnector->discoveryDeviceInfoMap_; +// int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); +// EXPECT_EQ(ret1, 1); +// EXPECT_EQ(ret, DM_OK); +// softbusConnector->UnRegisterSoftbusStateCallback(pkgName); +// } + +// HWTEST_F(DeviceManagerImplTest, RegisterSoftbusStateCallback3, testing::ext::TestSize.Level0) +// { +// std::string pkgName = ""; +// std::shared_ptr listener = std::make_shared(); +// std::cout << "11111111444444111"; +// // std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); +// std::shared_ptr deviceState = std::make_shared(softbusConnector, listener); +// std::cout << "1111111777771111"; +// int ret = softbusConnector->RegisterSoftbusStateCallback(pkgName, std::shared_ptr(deviceState)); +// // softbusConnector->discoveryDeviceInfoMap_; +// std::cout << "111111111199999991"; +// int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); +// EXPECT_EQ(ret1, 1); +// EXPECT_EQ(ret, DM_OK); +// softbusConnector->UnRegisterSoftbusStateCallback(pkgName); +// } + + +HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusStateCallback1, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + //std::shared_ptr listener_ = std::make_shared(); + //std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); + int ret = softbusConnector->UnRegisterSoftbusStateCallback(pkgName); + // softbusConnector->discoveryDeviceInfoMap_; + int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 0); + EXPECT_EQ(ret, DM_OK); +} +HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusStateCallback2, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + //std::shared_ptr listener_ = std::make_shared(); + //std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); + int ret = softbusConnector->UnRegisterSoftbusStateCallback(pkgName); + // softbusConnector->discoveryDeviceInfoMap_; + int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); + EXPECT_EQ(ret1, 0); + EXPECT_EQ(ret, DM_OK); +} +HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList1, testing::ext::TestSize.Level0) +{ + // std::string pkgName = "com.softbus.test"; + std::vector deviceInfoList; + std::string pkgName = ""; + int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); + std::cout << "ret = " << ret << std::endl; + EXPECT_EQ(ret, DM_OK); +} +HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList2, testing::ext::TestSize.Level0) +{ + std::vector deviceInfoList; + std::string pkgName = "com.softbus.test"; + int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); + std::cout << "ret = " << ret << std::endl; + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList3, testing::ext::TestSize.Level0) +{ + std::vector deviceInfoList; + std::string pkgName = "com.softbus.test"; + std::string DM_PKG_NAME = " "; + int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); + std::cout << "ret= " << ret << std::endl; + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo1, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + DmDeviceInfo deviceInfo; + int ret = softbusConnector->GetLocalDeviceInfo(deviceInfo); + std::cout << "ret= " << ret << std::endl; + EXPECT_EQ(ret, DM_OK); +} +HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo2, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.softbus.test"; + DmDeviceInfo deviceInfo; + int ret = softbusConnector->GetLocalDeviceInfo(deviceInfo); + std::cout << "ret = " << ret << std::endl; + EXPECT_EQ(ret, DM_OK); +} +HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo3, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.softbus.test"; + DmDeviceInfo deviceInfo; + std::string DM_PKG_NAME = " "; + int ret =softbusConnector->GetLocalDeviceInfo(deviceInfo); + EXPECT_EQ(ret, DM_OK); +} +HWTEST_F(DeviceManagerImplTest, StartDiscovery1, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.softbus.test"; + std::string DM_PKG_NAME = ""; +// std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; + DmSubscribeInfo dmSubscribeInfo; + int ret = softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::cout << "ret = " << ret << std::endl; + EXPECT_EQ(ret, DM_DISCOVERY_FAILED); +} +HWTEST_F(DeviceManagerImplTest, StartDiscovery2, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; +// std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; + DmSubscribeInfo dmSubscribeInfo; + int ret = softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::cout << "ret = " << ret << std::endl; + EXPECT_EQ(ret, DM_DISCOVERY_FAILED); +} +HWTEST_F(DeviceManagerImplTest, StartDiscovery3, testing::ext::TestSize.Level0) +{ + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1; + dmSubscribeInfo.mode = DM_DISCOVER_MODE_PASSIVE; + /** Service subscription medium. For details, see {@link DmExchangeMedium}. */ + dmSubscribeInfo.medium = DM_COAP; + /** Service subscription frequency. For details, see {@link DmExchangeFreq}. */ + dmSubscribeInfo.freq = DM_MID; + /** only find the device with the same account */ + dmSubscribeInfo.isSameAccount = true; + /** find the sleeping devices */ + dmSubscribeInfo.isWakeRemote = false; + // std::string pkgName = ""; + // std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; + int ret = softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::cout << "ret = " << ret << std::endl; + EXPECT_EQ(ret, DM_DISCOVERY_FAILED); +} +HWTEST_F(DeviceManagerImplTest, StopDiscovery1, testing::ext::TestSize.Level0) +{ + std::string DM_PKG_NAME = ""; + uint16_t subscribeId = 1; + int ret = softbusConnector->StopDiscovery(subscribeId); + EXPECT_TRUE(ret != 0); +} + +// HWTEST_F(DeviceManagerImplTest, StopDiscovery2, testing::ext::TestSize.Level0) +// { +// std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; +// uint16_t subscribeId = 1; +// +// int ret = softbusConnector->StopDiscovery(subscribeId); +// EXPECT_EQ(ret, DM_OK); +// } +HWTEST_F(DeviceManagerImplTest, StopDiscovery3, testing::ext::TestSize.Level0) +{ + uint16_t subscribeId = 1; + int ret = softbusConnector->StopDiscovery(subscribeId); + std::cout << "ret= "<IsDeviceOnLine(deviceId); + EXPECT_EQ(ret, false); +} +HWTEST_F(DeviceManagerImplTest, IsDeviceOnLine2, testing::ext::TestSize.Level0) + +{ + std::string deviceId = "145677"; + std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; + bool ret = softbusConnector->IsDeviceOnLine(deviceId); + EXPECT_EQ(ret, false); +} +HWTEST_F(DeviceManagerImplTest, IsDeviceOnLine3, testing::ext::TestSize.Level0) +{ + + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + + if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { + deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; + } + + bool ret = softbusConnector->IsDeviceOnLine(deviceId); + EXPECT_EQ(ret, false); +} + + + + + +} +} +} \ 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..09373e381 --- /dev/null +++ b/test/unittest/UTTest_softbus_connector.h @@ -0,0 +1,40 @@ +#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 "softbus_bus_center.h" +#include "discovery_service.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "softbus_state_callback.h" +#include "softbus_discovery_callback.h" +#include "softbus_session.h" +#include "softbus_connector.h" +#include "device_manager_service_listener.h" +#include "dm_discovery_manager.h" +#include "dm_device_state_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; +}; +} +} +#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..9d56f0733 --- /dev/null +++ b/test/unittest/UTTest_softbus_session.cpp @@ -0,0 +1,170 @@ + +#include "softbus_connector.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_anonymous.h" +#include "nlohmann/json.hpp" +#include "UTTest_softbus_session.h" +#include "softbus_session.h" + + +namespace OHOS +{ +namespace DistributedHardware +{ + +void DeviceManagerImplTest::SetUp() +{ +} + +void DeviceManagerImplTest::TearDown() +{ +} + +void DeviceManagerImplTest::SetUpTestCase() +{ +} + +void DeviceManagerImplTest::TearDownTestCase() +{ +} +namespace +{ + +std::shared_ptr softbusSession = std::make_shared(); +HWTEST_F(DeviceManagerImplTest, OpenAuthSession1, testing::ext::TestSize.Level0) +{ + std::string deviceId = ""; + int ret = softbusSession->OpenAuthSession(deviceId); + EXPECT_EQ(ret, -1); +} +HWTEST_F(DeviceManagerImplTest, OpenAuthSession2, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + + if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { + deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; + } + + // std::string deviceId = "SoftbusConnector::discoveryCallbackMap_[pkgName]"; + std::string DM_SESSION_NAME = ""; + int ret = softbusSession->OpenAuthSession(deviceId); + EXPECT_EQ(ret, -1); +} +HWTEST_F(DeviceManagerImplTest, OpenAuthSession3, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + + if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { + deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; + } + + std::string DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; + int ret = softbusSession->OpenAuthSession(deviceId); + EXPECT_EQ(ret, -1); +} +HWTEST_F(DeviceManagerImplTest, SendData1, testing::ext::TestSize.Level0) +{ + std::string message = ""; + int32_t sessionId = -1; + int ret = softbusSession->SendData(sessionId, message); + EXPECT_EQ(ret, DM_FAILED); +} +HWTEST_F(DeviceManagerImplTest, SendData2, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObj; + jsonObj[TAG_VER] = DM_ITF_VER; + std::string msgType; + jsonObj[TAG_TYPE] = msgType; + std::string message = jsonObj.dump(); + int32_t sessionId = -1; + int ret = softbusSession->SendData(sessionId, message); + EXPECT_EQ(ret, DM_FAILED); +} +HWTEST_F(DeviceManagerImplTest, SendData3, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObj; + std::string msgType; + jsonObj[TAG_VER] = DM_ITF_VER; + jsonObj[TAG_TYPE] = msgType; + std::string message = jsonObj.dump(); + int32_t sessionId = 1; + int ret = softbusSession->SendData(sessionId, message); + EXPECT_EQ(ret, DM_FAILED); +} + + + + +HWTEST_F(DeviceManagerImplTest, OnSessionOpened1, testing::ext::TestSize.Level0) +{ + int result = 0; + int32_t sessionId = -1; + int ret = softbusSession->OnSessionOpened(sessionId, result); + + EXPECT_EQ(ret, DM_OK); +} +HWTEST_F(DeviceManagerImplTest, OnSessionOpened2, testing::ext::TestSize.Level0) +{ + int result = 0; + + int32_t sessionId = 0; + int ret = softbusSession->OnSessionOpened(sessionId, result); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, OnSessionOpened3, testing::ext::TestSize.Level0) +{ + int result = 0; + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + + if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { + deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; + } + int32_t sessionId = softbusSession->OpenAuthSession(deviceId); + int ret = softbusSession->OnSessionOpened(sessionId, result); + EXPECT_EQ(ret, DM_OK); +} + +} +} +} diff --git a/test/unittest/UTTest_softbus_session.h b/test/unittest/UTTest_softbus_session.h new file mode 100644 index 000000000..77ada094a --- /dev/null +++ b/test/unittest/UTTest_softbus_session.h @@ -0,0 +1,34 @@ +#ifndef OHOS_UTTest_DM_SOFTBUS_SESSION_H +#define OHOS_UTTest_DM_SOFTBUS_SESSION_H + + +#include "softbus_session.h" +#include +#include +#include +#include +#include +#include +#include +#include "session.h" +#include "inner_session.h" +#include "softbus_session_callback.h" +#include "device_manager_service_listener.h" +#include "dm_discovery_manager.h" +#include "dm_device_state_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; +}; +} +} +#undef private +#undef protected +#endif \ No newline at end of file -- Gitee From 238c32774ce30f0d3eb980a18f7198b917f29ec7 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Tue, 28 Dec 2021 11:36:44 +0800 Subject: [PATCH 056/110] submit by weidong.liu@thundersoft.com change: restore unAuthentication func from xiaocong merged --- .../dependency/hichain/hichain_connector.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 27 ++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index c0c8896a1..a2f05503b 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -57,9 +57,9 @@ public: int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); int32_t IsDevicesInGroup(std::string hostDevice, std::string peerDevice); + void GetRelatedGroups(std::string DeviceId, std::vector &groupList); private: int64_t GenRequestId(); - void GetRelatedGroups(std::string DeviceId, std::vector &groupList); 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); diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 09fd16bd1..ef39c0452 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -121,6 +121,31 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au 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; + } + //groupId = authResponseContext_->groupId; + LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s, deviceUdid=%s", authResponseContext_->groupId.c_str(), + deviceId.c_str(), deviceUdid.c_str()); + hiChainConnector_->DeleteGroup(groupId); + return DM_OK; } @@ -547,4 +572,4 @@ int32_t DmAuthManager::GetPinCode() return authResponseContext_->code; } } -} \ No newline at end of file +} -- Gitee From 5d8ca1d916ad79b67e0492c354f575986fdc3619 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Wed, 29 Dec 2021 10:48:48 +0800 Subject: [PATCH 057/110] submit by weidong.liu@thundersoft.com change: fix hiChainConnector_ ptr when UnAuthenticateDevice because it was released --- .../src/authentication/dm_auth_manager.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index ef39c0452..13056e51f 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -137,15 +137,19 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st std::string groupId = ""; std::vector groupList; + hiChainConnector_ = std::make_shared(); 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; - LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s, deviceUdid=%s", authResponseContext_->groupId.c_str(), - deviceId.c_str(), deviceUdid.c_str()); - hiChainConnector_->DeleteGroup(groupId); - + hiChainConnector_ = nullptr; return DM_OK; } -- Gitee From 807bb8fc93db24b03f1c168d04ac349e0296002a Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Mon, 3 Jan 2022 12:01:40 +0800 Subject: [PATCH 058/110] =?UTF-8?q?ui=E6=8B=89=E8=B5=B7=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 1 - .../include/ipc/model/ipc_get_dmfaparam_rsp.h | 6 +- devicemanager.gni | 2 +- ext/pin_auth/BUILD.gn | 34 ++- .../include/ability/dm_ability_manager.h | 77 +++-- ext/pin_auth/include/pin_auth.h | 3 +- ext/pin_auth/include/pin_auth_ui.h | 5 +- .../src/ability/lite/dm_ability_manager.cpp | 52 ++++ .../ability/standard/dm_ability_manager.cpp | 102 +++++++ ext/pin_auth/src/pin_auth.cpp | 9 +- ext/pin_auth/src/pin_auth_ui.cpp | 16 +- .../native_cpp/include/dm_device_info.h | 10 - .../native_cpp/src/device_manager_impl.cpp | 9 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 38 +-- .../src/ipc/standard/ipc_client_manager.cpp | 2 + .../src/ipc/standard/ipc_cmd_parser.cpp | 210 ++++++------- .../kits/js/include/native_devicemanager_js.h | 1 + .../kits/js/src/native_devicemanager_js.cpp | 40 ++- services/devicemanagerservice/BUILD.gn | 6 +- .../include/ability/dm_ability_manager.h | 6 - .../include/authentication/auth_ui.h | 5 +- .../include/authentication/authentication.h | 4 +- .../include/authentication/dm_auth_manager.h | 47 +-- .../dependency/hichain/hichain_connector.h | 3 +- .../include/device_manager_service.h | 2 +- .../ability/standard/dm_ability_manager.cpp | 22 +- .../authentication/auth_message_processor.cpp | 5 + .../src/authentication/auth_request_state.cpp | 3 +- .../authentication/auth_response_state.cpp | 8 +- .../src/authentication/auth_ui.cpp | 5 +- .../src/authentication/dm_auth_manager.cpp | 289 +++++++----------- .../dependency/hichain/hichain_connector.cpp | 20 +- .../dependency/softbus/softbus_connector.cpp | 5 + .../src/device_manager_service.cpp | 12 +- .../src/ipc/lite/ipc_server_listener.cpp | 4 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 117 ++++--- .../src/timer/dm_timer.cpp | 153 ---------- 37 files changed, 647 insertions(+), 686 deletions(-) rename services/devicemanagerservice/include/timer/dm_timer.h => ext/pin_auth/include/ability/dm_ability_manager.h (42%) 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 delete mode 100644 services/devicemanagerservice/src/timer/dm_timer.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 6f62f980a..1dd59532d 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -172,7 +172,6 @@ namespace DistributedHardware { const std::string BLE_MAC = "BLE_MAC"; const std::string ETH_IP = "ETH_IP"; const std::string ETH_PORT = "ETH_PORT"; - const int32_t FAIL = -1; } } #endif diff --git a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h index ccc8ed836..d79008ddd 100644 --- a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h +++ b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h @@ -24,17 +24,17 @@ namespace DistributedHardware { class IpcGetDmFaParamRsp : public IpcRsp { DECLARE_IPC_MODEL(IpcGetDmFaParamRsp); public: - const DmFaParam& GetDmFaParam() const + const DmAuthParam& GetDmAuthParam() const { return dmFaParam_; } - void SetDmFaParam(DmFaParam &dmFaParam) + void SetDmAuthParam(DmAuthParam &dmFaParam) { dmFaParam_ = dmFaParam; } private: - DmFaParam dmFaParam_; + DmAuthParam dmFaParam_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/devicemanager.gni b/devicemanager.gni index b226ba5a8..7487a8b32 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -16,7 +16,7 @@ devicemanager_path = "//foundation/distributedhardware/devicemanager" common_path = "${devicemanager_path}/common" utils_path = "${devicemanager_path}/utils" -services_path = "${devicemanager_path}/services" +services_path = "${devicemanager_path}/services/devicemanagerservice" innerkits_path = "${devicemanager_path}/interfaces/inner_kits" ext_path = "${devicemanager_path}/ext" diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index 9b67853f4..6ab4f8db5 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -27,12 +27,40 @@ if (defined(ohos_lite)) { "include", "${common_path}/include", "${services_path}/include/adapter", + "${ext_path}/pin_auth/include/ability", "${services_path}/include/authentication", + "${utils_path}/include", ] sources = [ "src/pin_auth.cpp", - "src/pin_auth_ui.cpp" + "src/pin_auth_ui.cpp", + "src/ability/standard/dm_ability_manager.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", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "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", + "startup_l2:syspara_watchagent", ] defines = [ @@ -45,6 +73,4 @@ if (defined(ohos_lite)) { part_name = "device_manager_base" } -} - - +} \ No newline at end of file diff --git a/services/devicemanagerservice/include/timer/dm_timer.h b/ext/pin_auth/include/ability/dm_ability_manager.h similarity index 42% rename from services/devicemanagerservice/include/timer/dm_timer.h rename to ext/pin_auth/include/ability/dm_ability_manager.h index ea52ce137..dd39026ec 100644 --- a/services/devicemanagerservice/include/timer/dm_timer.h +++ b/ext/pin_auth/include/ability/dm_ability_manager.h @@ -13,60 +13,51 @@ * limitations under the License. */ -#ifndef TIMER_H -#define TIMER_H -#include -#include -#include -#include -#include -#include -#include -#include +#ifndef OHOS_DM_ABILITY_MANAGER_H +#define OHOS_DM_ABILITY_MANAGER_H -#include "dm_log.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 +}; -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, +enum AbilityStatus : int32_t { + ABILITY_STATUS_FAILED = 0, + ABILITY_STATUS_SUCCESS = 1, + ABILITY_STATUS_START = 2 }; -class DmTimer { -public: - DmTimer(std::string &name); - ~DmTimer(); - DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data); - void Stop(int32_t code); - void WiteforTimeout(); +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 { +public: + AbilityRole GetAbilityRole(); + AbilityStatus StartAbility(AbilityRole role); + void StartAbilityDone(); private: - int32_t CreateTimeFd(); - void Release(); + void waitForTimeout(uint32_t timeout_s); 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_; + sem_t mSem_; + AbilityStatus mStatus_; + AbilityRole mAbilityStatus_; }; -} -} +} // namespace DistributedHardware +} // namespace OHOS #endif - diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h index 91368a615..556663d58 100644 --- a/ext/pin_auth/include/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.h @@ -20,6 +20,7 @@ #include #include "pin_auth_ui.h" #include "authentication.h" +#include "dm_ability_manager.h" namespace OHOS { namespace DistributedHardware { @@ -28,7 +29,7 @@ public: PinAuth(); ~PinAuth(); int32_t ShowAuthInfo() override; - int32_t StartAuth() override; + int32_t StartAuth(std::shared_ptr dmAbilityManager) override; private: std::shared_ptr pinAuthUi_; diff --git a/ext/pin_auth/include/pin_auth_ui.h b/ext/pin_auth/include/pin_auth_ui.h index 72ffef99a..d98f9763a 100644 --- a/ext/pin_auth/include/pin_auth_ui.h +++ b/ext/pin_auth/include/pin_auth_ui.h @@ -17,6 +17,7 @@ #define OHOS_DM_PIN_AUTH_UI_H #include +#include "dm_ability_manager.h" namespace OHOS { namespace DistributedHardware { @@ -24,10 +25,12 @@ class PinAuthUi { public: PinAuthUi(); int32_t ShowPinDialog(); - int32_t InputPinDialog(); + int32_t InputPinDialog(std::shared_ptr dmAbilityManager); private: int32_t StartFaService(); +private: + std::shared_ptr dmAbilityMgr_ ; }; } // namespace DistributedHardware } // namespace OHOS 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..1570551ba --- /dev/null +++ b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_ability_manager.h" + +#include "semaphore.h" + +#include "dm_constants.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_); +} +} +} 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..089b4c17f --- /dev/null +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_ability_manager.h" + +#include "ability_manager_client.h" +#include "ability_record.h" +#include "ability_manager_service.h" +#include "parameter.h" +#include "semaphore.h" + +#include "dm_constants.h" +#include "single_instance.h" +#include "dm_log.h" + + +namespace OHOS { +namespace DistributedHardware { +namespace { +const int32_t ABILITY_START_TIMEOUT = 3; // 3 second +} + +AbilityRole DmAbilityManager::GetAbilityRole() +{ + return mAbilityStatus_; +} + +AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) +{ + LOGI("pinauthui StartAbility, role %d", (int32_t)role); + std::string roleStr; + if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { + roleStr = "initiative"; + } else if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { + roleStr = "passive"; + } else { + LOGE("StartAbility, failed, role unknown"); + return AbilityStatus::ABILITY_STATUS_FAILED; + } + + LOGI("StartAbility, role %s", roleStr.c_str()); + mAbilityStatus_ = role; + LOGI("pinauthui StartAbility, mAbilityStatus_ :%d", (int32_t)mAbilityStatus_); + + 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) ? + DISPLAY_OWNER_OTHER : DISPLAY_OWNER_SYSTEM; + + mStatus_ = AbilityStatus::ABILITY_STATUS_START; + AAFwk::Want want; + AppExecFwk::ElementName element(deviceId, bundleName, abilityName); + want.SetElement(element); + LOGI("StartAbility, displayOwner %d", displayOwner); + // if (displayOwner == DISPLAY_OWNER_OTHER) { + // LOGI("StartAbility, other display no need to start ability"); + // return AbilityStatus::ABILITY_STATUS_SUCCESS; + // } + AAFwk::AbilityManagerClient::GetInstance()->Connect(); + ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); + if (result == OHOS::ERR_OK) { + LOGI("Start Ability succeed"); + } else { + 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_); +} +} +} diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 010b60be0..9124181f9 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace DistributedHardware { PinAuth::PinAuth() { + LOGI("PinAuth constructor"); } @@ -33,12 +34,14 @@ PinAuth::~PinAuth() int32_t PinAuth::ShowAuthInfo() { - return 0; + LOGI("PinAuth::ShowAuthInfo in"); + return pinAuthUi_->ShowPinDialog(); } -int32_t PinAuth::StartAuth() +int32_t PinAuth::StartAuth(std::shared_ptr dmAbilityManager) { - return 0; + LOGI("PinAuth::StartAuth in"); + return pinAuthUi_->InputPinDialog(dmAbilityManager); } extern "C" IAuthentication* CreatePinAuthObject (void) { diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index b890a75a5..b3ce28a8c 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -16,6 +16,7 @@ #include "pin_auth_ui.h" #include "dm_ability_manager.h" #include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { @@ -31,16 +32,20 @@ int32_t PinAuthUi::ShowPinDialog() return SUCCESS; } -int32_t PinAuthUi::InputPinDialog() +int32_t PinAuthUi::InputPinDialog(std::shared_ptr dmAbilityManager) { LOGI("PinAuthUi::InputPinDialog in"); + if (dmAbilityMgr_ == nullptr) { + LOGI("PinAuthUi::dmAbilityMgr_ is null"); + dmAbilityMgr_ = dmAbilityManager; + } return StartFaService(); } int32_t PinAuthUi::StartFaService() { LOGI("PinAuthUi::StartFaService in"); - AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); + AbilityStatus status = dmAbilityMgr_->StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { LOGE("PinAuthUi::StartFaService timeout"); return FAIL; @@ -48,12 +53,5 @@ int32_t PinAuthUi::StartFaService() return SUCCESS; } - return 0; -} - -int32_t InputPinDialog() -{ - return 0; -} } } 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 00e5b67a2..ff58e67d0 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -50,12 +50,6 @@ typedef struct DmDeviceInfo { uint16_t deviceTypeId; } DmDeviceInfo; -typedef enum DmFaType { - FA_TYPE_UNKNOWN = 0X00, - FA_TYPE_AUTH = 0x01, - FA_TYPE_CONWIFI = 0x02, -} DmFaType; - typedef struct DmAuthParam { std::string authToken; std::string packageName; @@ -69,10 +63,6 @@ typedef struct DmAuthParam { DmAppImageInfo imageinfo; } DmAuthParam; -typedef struct DmFaParam { - DmFaType type; - DmAuthParam authParam; -}DmFaParam; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_DEVICE_INFO_H 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 2bd001ef6..1a3c85b41 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -407,10 +407,9 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons return DM_OK; } -int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &faParam) +int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &dmFaParam) { LOGI("DeviceManagerImpl::GetFaParam start"); - DmFaParam dmFaParam; if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INVALID_VALUE; @@ -418,11 +417,13 @@ int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &faParam std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); + LOGI("DeviceManagerImpl::GetFaParam start 1"); if (ipcClientProxy_->SendRequest(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { + LOGI("DeviceManagerImpl::GetFaParam start 2"); return DM_IPC_SEND_REQUEST_FAILED; } - dmFaParam = rsp->GetDmFaParam(); - faParam = dmFaParam.authParam; + LOGI("DeviceManagerImpl::GetFaParam start 3"); + dmFaParam = rsp->GetDmAuthParam(); return DM_OK; } 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 cb938c55a..863b0efc5 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 @@ -206,6 +206,25 @@ ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo& request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName= pReq->GetPkgName(); + 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_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; +} + ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply) { size_t len = 0; @@ -346,25 +365,6 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply) // return DM_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 DM_OK; -} - -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DM_OK; -} - ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) { size_t len = 0; 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 e06705763..c071e1508 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 @@ -129,8 +129,10 @@ int32_t IpcClientManager::UnInit(const std::string &pkgName) 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)) { + LOGE("IpcClientManager::SendRequest DM_SERVICE_NOT_READY"); return DM_SERVICE_NOT_READY; } return dmInterface_->SendCmd(cmdCode, req, rsp); 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 36f99bc9b..836121d0b 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 @@ -273,6 +273,104 @@ ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, MessageParcel &reply, std::shared_pt 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 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(); + + // 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->SetDmAuthParam(authParam); + return DM_OK; +} + +ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_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_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 DM_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 DM_OK; +//} + +ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); @@ -357,118 +455,6 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) 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 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); - DmFaParam dmFaParam; - DmAuthParam authParam; - size_t dmFaTypeSize = sizeof(DmFaType); - DmFaType *type = (DmFaType*)reply.ReadRawData(dmFaTypeSize); - LOGI("dmfa %d", *type); - if(*type == FA_TYPE_AUTH){ - LOGI("dmfa2 %d", *type); - authParam.direction = reply.ReadInt32(); - authParam.authType = reply.ReadInt32(); - if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - authParam.authToken = reply.ReadInt32(); - dmFaParam.authParam = authParam; - dmFaParam.type = *type; - pRsp->SetDmFaParam(dmFaParam); - return DM_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); - } - dmFaParam.authParam = authParam; - dmFaParam.type = *type; - pRsp->SetDmFaParam(dmFaParam); - LOGI("dmfa3 %d", *type); - } - return DM_OK; -} - -ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_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_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 DM_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 DM_OK; -//} - -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) { diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 87d1767ba..4fdbc9b77 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -48,6 +48,7 @@ struct DeviceInfoAsyncCallbackInfo { 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; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 35a82bf6d..6f00537ec 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -347,17 +347,25 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam, napi_value ¶mResult) { LOGI("DmAuthParamToJsAuthParam in"); - SetValueInt32(env, "authType", authParam.authType, paramResult); + LOGI("DmAuthParamToJsAuthParam direction1: %d", authParam.direction); + LOGI("DmAuthParamToJsAuthParam authToken: %s", authParam.authToken.c_str()); 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", atoi(authParam.authToken.c_str()), extraInfo); + LOGI("DmAuthParamToJsAuthParam direction2: %d", authParam.direction); if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; } - + LOGI("DmAuthParamToJsAuthParam SetValueUtf8String in"); + LOGI("DmAuthParamToJsAuthParam get packageName : %s", authParam.packageName.c_str()); + LOGI("DmAuthParamToJsAuthParam get appName : %s", authParam.appName.c_str()); + LOGI("DmAuthParamToJsAuthParam get appDescription : %s", authParam.appDescription.c_str()); + LOGI("DmAuthParamToJsAuthParam get business : %d", authParam.business); + LOGI("DmAuthParamToJsAuthParam get pinCode : %d", authParam.pincode); SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); SetValueUtf8String(env, "appName", authParam.appName, extraInfo); SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); @@ -365,7 +373,9 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); napi_set_named_property(env, paramResult, "extraInfo", extraInfo); + LOGI("DmAuthParamToJsAuthParam get appIconLen in"); size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); + LOGI("DmAuthParamToJsAuthParam get appIconLen : %d", appIconLen); if (appIconLen > 0) { void *appIcon = nullptr; napi_value appIconBuffer = nullptr; @@ -379,7 +389,9 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, } } + LOGI("DmAuthParamToJsAuthParam get appThumbnailLen in"); size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); + LOGI("DmAuthParamToJsAuthParam get appThumbnailLen : %d", appThumbnailLen); if (appThumbnailLen > 0) { void *appThumbnail = nullptr; napi_value appThumbnailBuffer = nullptr; @@ -772,20 +784,23 @@ napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_call NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); - + LOGI("GetAuthenticationParamSync in 1"); DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - + LOGI("GetAuthenticationParamSync in 2"); DmAuthParam authParam; + LOGI("GetAuthenticationParamSync in 22"); int32_t ret = DeviceManager::GetInstance().GetFaParam(deviceManagerWrapper->bundleName_, authParam); + LOGI("GetAuthenticationParamSync in 3"); if (ret != 0) { LOGE("GetAuthenticationParam for %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); napi_get_undefined(env, &resultParam); return resultParam; } - + LOGI("GetAuthenticationParamSync in 4"); napi_create_object(env, &resultParam); + LOGI("GetAuthenticationParamSync direction: %d", authParam.direction); DmAuthParamToJsAuthParam(env, authParam, resultParam); return resultParam; } @@ -1040,6 +1055,8 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in // filterOptions.sortType = (DmDeviceSortType)sortType; // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + 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); @@ -1058,6 +1075,9 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in deviceInfoAsyncCallbackInfo->deferred = deferred; // JsToDmFilterOptions(env, argv[0], filterOptions); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + char extraString[20]; + JsObjectToString(env, argv[0], "extra", extraString, sizeof(extraString)); + deviceInfoAsyncCallbackInfo->extra = extraString; CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); return promise; } @@ -1120,6 +1140,8 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i // filterOptions.sortType = (DmDeviceSortType)sortType; // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + std::string extra = ""; + deviceInfoAsyncCallbackInfo->extra = extra; napi_deferred deferred; napi_value promise = 0; napi_create_promise(env, &deferred, &promise); @@ -1143,6 +1165,9 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i // JsToDmFilterOptions(env, argv[0], filterOptions); // deviceInfoAsyncCallbackInfo->filter = filterOptions; + 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); @@ -1346,7 +1371,7 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf //TODO:get real authType int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, - extra, authCallback); + extraString, authCallback); if (ret != 0) { LOGE("AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); @@ -1692,6 +1717,7 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) 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) diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 94125cdf4..8430f2d7b 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -26,7 +26,6 @@ if (defined(ohos_lite)) { "include/adapter", "include/authentication", "include/ability", - "include/timer", "include/deviceinfo", "include/devicestate", "include/discovery", @@ -69,8 +68,8 @@ if (defined(ohos_lite)) { "src/adapter/lite/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", "src/ability/lite/dm_ability_manager.cpp", - "src/timer/dm_timer.cpp", "src/authentication/auth_message_processor.cpp", + "src/authentication/auth_ui.cpp", "src/authentication/auth_request_state.cpp", "src/authentication/auth_response_state.cpp", "src/deviceinfo/dm_device_info_manager.cpp", @@ -114,7 +113,6 @@ if (defined(ohos_lite)) { "include/adapter", "include/authentication", "include/ability", - "include/timer", "include/deviceinfo", "include/devicestate", "include/discovery", @@ -149,10 +147,10 @@ if (defined(ohos_lite)) { "src/config_manager.cpp", "src/device_manager_service.cpp", "src/ability/standard/dm_ability_manager.cpp", - "src/timer/dm_timer.cpp", "src/device_manager_service_listener.cpp", "src/adapter/standard/dm_adapter_manager.cpp", "src/authentication/dm_auth_manager.cpp", + "src/authentication/auth_ui.cpp", "src/authentication/auth_message_processor.cpp", "src/authentication/auth_request_state.cpp", "src/authentication/auth_response_state.cpp", diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h index 4b95b7de8..dd39026ec 100644 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ b/services/devicemanagerservice/include/ability/dm_ability_manager.h @@ -20,11 +20,8 @@ #include #include #include -#include "nlohmann/json.hpp" #include "single_instance.h" -#include "dm_device_info.h" -#include "dm_auth_manager.h" namespace OHOS { namespace DistributedHardware { @@ -53,8 +50,6 @@ public: AbilityRole GetAbilityRole(); AbilityStatus StartAbility(AbilityRole role); void StartAbilityDone(); - DmFaType GetDmFaType(); - void SetDmFaType(const DmFaType &type); private: void waitForTimeout(uint32_t timeout_s); @@ -62,7 +57,6 @@ private: sem_t mSem_; AbilityStatus mStatus_; AbilityRole mAbilityStatus_; - DmFaType mDmFaType_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h index c1d431ba9..0639bb8f9 100644 --- a/services/devicemanagerservice/include/authentication/auth_ui.h +++ b/services/devicemanagerservice/include/authentication/auth_ui.h @@ -17,15 +17,18 @@ #define OHOS_DM_AUTH_UI_H #include +#include "dm_ability_manager.h" namespace OHOS { namespace DistributedHardware { class AuthUi { public: AuthUi(); - int32_t ShowConfirmDialog(); + int32_t ShowConfirmDialog(std::shared_ptr dmAbilityManager); private: int32_t StartFaService(); +private: + std::shared_ptr dmAbilityMgr_ ; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h index c1d9c493a..d68118306 100644 --- a/services/devicemanagerservice/include/authentication/authentication.h +++ b/services/devicemanagerservice/include/authentication/authentication.h @@ -16,13 +16,15 @@ #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() = 0; + virtual int32_t StartAuth(std::shared_ptr dmAbilityManager) = 0; }; using CreateIAuthAdapterFuncPtr = IAuthentication* (*)(void); diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 9027e5f99..27d024686 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -32,24 +32,11 @@ #include "auth_response_state.h" #include "auth_message_processor.h" #include "dm_timer.h" +#include "auth_ui.h" namespace OHOS { namespace DistributedHardware { -<<<<<<< HEAD -const std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; -const int32_t AUTHENTICATE_TIMEOUT = 120; - -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; -} - -======= ->>>>>>> 2a5ceded594bd3ff65ff07fb404946015c90869e typedef enum AuthState { AUTH_REQUEST_INIT = 1, AUTH_REQUEST_NEGOTIATE, @@ -117,6 +104,13 @@ typedef struct DmAuthResponseContext { 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; @@ -125,8 +119,6 @@ typedef struct DmAuthResponseContext { class AuthMessageProcessor; class DmAuthManager final : public ISoftbusSessionCallback, public IHiChainConnectorCallback, public std::enable_shared_from_this { -public: - static DmAuthManager& GetInstance(); public: DmAuthManager(std::shared_ptr softbusConnector, std::shared_ptr listener); @@ -152,23 +144,17 @@ public: std::string GetConnectAddr(std::string deviceId); void JoinNetwork(); void AuthenticateFinish(); - int32_t GetAuthenticationParam(DmAuthParam &authParam); - void OnUserOperate(int32_t action); void GetIsCryptoSupport(bool &isCryptoSupport); void SetAuthRequestState(std::shared_ptr authRequestState); void SetAuthResponseState(std::shared_ptr authResponseState); int32_t GetPinCode(); void HandleAuthenticateTimeout(); - void OnUserConfirm(); - void OnUserReqSessionOperate(int32_t action); - void OnUserRespSessionOperate(int32_t action); - void ReqSessionRelease(); - std::string GenerateGroupName(); - void Release(); void CancelDisplay(); int32_t GeneratePincode(); - void BuildAuthenticationInfo(DmAuthParam &authParam); - void UpdateDmFaType(DmFaType type); + void ShowConfigDialog(); + void ShowAuthInfoDialog(); + void ShowStartAuthDialog(); + int32_t GetAuthenticationParam(DmAuthParam &authParam); private: std::shared_ptr softbusConnector_; std::shared_ptr sessionSession_; @@ -176,21 +162,14 @@ private: std::shared_ptr listener_; std::shared_ptr adapterMgr_; std::map> authenticationMap_; - int32_t displayOwner_ = 0; std::shared_ptr authRequestState_ = nullptr; std::shared_ptr authResponseState_ = nullptr; std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; -<<<<<<< HEAD - std::shared_ptr mMemberJoinTimerPtr_; - int32_t mPincode_; - int32_t mGroupId_; - std::string mGroupName_; -======= std::map> timerMap_; std::shared_ptr data_; ->>>>>>> 2a5ceded594bd3ff65ff07fb404946015c90869e + std::shared_ptr dmAbilityMgr_ ; bool isCryptoSupport_ = false; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 2996bf695..a2f05503b 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -57,10 +57,9 @@ public: int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); int32_t IsDevicesInGroup(std::string hostDevice, std::string peerDevice); + void GetRelatedGroups(std::string DeviceId, std::vector &groupList); private: - void GetRelatedGroups(std::string DeviceId, std::vector &groupList); int64_t GenRequestId(); - void GetRelatedGroups(std::string DeviceId, std::vector &groupList); 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); diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index 1dacbaa2c..b7f740156 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -41,7 +41,7 @@ public: 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 &pkgName, const std::string &authParam); - int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam, DmFaType &type); + int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam); int32_t SetUserOperation(std::string &pkgName, int32_t action); private: bool intFlag_ = false; diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp index a5f9a6993..fae78740b 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -49,11 +49,11 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) return AbilityStatus::ABILITY_STATUS_FAILED; } - LOGE("StartAbility, role %s", roleStr.c_str()); + LOGI("StartAbility, role %s", roleStr.c_str()); mAbilityStatus_ = role; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - // GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string deviceId = localDeviceId; std::string bundleName = "com.ohos.devicemanagerui"; std::string abilityName = "com.ohos.devicemanagerui.MainAbility"; @@ -64,11 +64,14 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) AAFwk::Want want; AppExecFwk::ElementName element(deviceId, bundleName, abilityName); want.SetElement(element); - if (displayOwner == DISPLAY_OWNER_OTHER) { - return AbilityStatus::ABILITY_STATUS_SUCCESS; - } + LOGI("StartAbility, displayOwner %d", displayOwner); + // if (displayOwner == DISPLAY_OWNER_OTHER) { + // LOGI("StartAbility, other display no need to start ability"); + // return AbilityStatus::ABILITY_STATUS_SUCCESS; + // } AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); + LOGI("StartAbility, AAFwk running"); if (result == OHOS::ERR_OK) { LOGI("Start Ability succeed"); } else { @@ -88,15 +91,6 @@ void DmAbilityManager::waitForTimeout(uint32_t timeout_s) sem_timedwait(&mSem_, &ts); } -DmFaType DmAbilityManager::GetDmFaType() -{ - return mDmFaType_; -} - -void DmAbilityManager::SetDmFaType(const DmFaType &type) -{ - mDmFaType_ = type; -} void DmAbilityManager::StartAbilityDone() { diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index 3a4a51acc..4ad748c1d 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -17,6 +17,7 @@ #include "dm_log.h" #include "dm_constants.h" +#include "dm_auth_manager.h" namespace OHOS { namespace DistributedHardware { @@ -181,6 +182,10 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) } 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) { diff --git a/services/devicemanagerservice/src/authentication/auth_request_state.cpp b/services/devicemanagerservice/src/authentication/auth_request_state.cpp index df353d3f0..d00b65f74 100644 --- a/services/devicemanagerservice/src/authentication/auth_request_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -131,13 +131,12 @@ void AuthRequestInputState::Enter() { // // //2. 验证认证信息 LOGE("DmAuthManager::AuthRequestInputState"); - std::string test = ""; std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } - stateAuthManager->VerifyAuthentication(test, test); + stateAuthManager->ShowStartAuthDialog(); } int32_t AuthRequestJoinState::GetStateType() { diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp index 75f8a8b09..e3c22de6c 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -107,7 +107,7 @@ void AuthResponseConfirmState::Enter() LOGE("AuthRequestState::authManager_ null"); return; } - stateAuthManager->StartAuthProcess(context_->authType); + stateAuthManager->ShowConfigDialog(); } int32_t AuthResponseGroupState::GetStateType() @@ -137,6 +137,12 @@ int32_t AuthResponseShowState::GetStateType() void AuthResponseShowState::Enter() { //1.委托认证实现模块进行用户交互 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return; + } + stateAuthManager->ShowAuthInfoDialog(); } diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp index c192e8ff4..bdf2a5147 100644 --- a/services/devicemanagerservice/src/authentication/auth_ui.cpp +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -26,16 +26,17 @@ AuthUi::AuthUi() LOGI("AuthUi constructor"); } -int32_t AuthUi::ShowConfirmDialog() +int32_t AuthUi::ShowConfirmDialog(std::shared_ptr dmAbilityManager) { LOGI("AuthUi::ShowConfirmDialog in"); + dmAbilityMgr_ = dmAbilityManager; return StartFaService(); } int32_t AuthUi::StartFaService() { LOGI("AuthUi::StartFaService in"); - AbilityStatus status = DmAbilityManager::GetInstance().StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); + AbilityStatus status = dmAbilityMgr_->StartAbility(AbilityRole::ABILITY_ROLE_PASSIVE); if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { LOGE("AuthUi::StartFaService timeout"); return FAIL; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index ad5457de4..a719b4bb5 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -20,9 +20,13 @@ #include "dm_log.h" #include "dm_random.h" #include "dm_constants.h" +#include "config_manager.h" #include "auth_message_processor.h" +#include "dm_ability_manager.h" +#include "auth_ui.h" namespace OHOS { namespace DistributedHardware { + namespace{ std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; std::string NEGOTIATE_TIMEOUT_TASK = "negotiateTimeoutTask"; @@ -37,7 +41,9 @@ namespace{ int32_t NEGOTIATE_TIMEOUT = 10; int32_t INPUT_TIMEOUT = 60; int32_t ADD_TIMEOUT = 10; + int32_t CANCEL_PICODE_DISPLAY = 1; } + static void TimeOut(void *data){ LOGE("time out "); DmAuthManager *authMgr = (DmAuthManager*)data; @@ -53,9 +59,6 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, { LOGI("DmAuthManager constructor"); //TODO: load library so for different auth type - hiChainConnector_ = std::make_shared(); - mPincode_ = -1; - mGroupId_ = -1; data_ = std::shared_ptr(this); std::string pkgName = "com.ohos.devicemangagerdemo"; sessionSession_->RegisterSessionCallback(pkgName, data_); @@ -111,7 +114,7 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au authRequestContext_->appIcon = jsonObject[APP_ICON_KEY]; } } - + authRequestContext_->token = "123456"; authRequestState_ = std::shared_ptr(new AuthRequestInitState()); authRequestState_->SetAuthManager(data_); authRequestState_->SetAuthContext(authRequestContext_); @@ -125,6 +128,35 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au 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_ = std::make_shared(); + 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; + hiChainConnector_ = nullptr; return DM_OK; } @@ -145,6 +177,7 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const st authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); return DM_FAILED; } + CancelDisplay(); LOGI("DmAuthManager::VerifyAuthentication complete"); return DM_OK; } @@ -152,7 +185,6 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const st 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); - mPincode_ = GeneratePincode(); if (sessionSide == AUTH_SESSION_SIDE_SERVER) { if (authResponseState_ == nullptr) { authMessageProcessor_ = std::make_shared(data_); @@ -268,8 +300,8 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseShowState())); - int32_t pinCode = 123456; - authResponseContext_->code = pinCode; + // int32_t pinCode = 123456; + // authResponseContext_->code = pinCode; authResponseContext_->groupId = groupId; authResponseContext_->groupName = "1234567890"; authResponseContext_->reply = 0; @@ -281,15 +313,9 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) { -// if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) { -// authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNetworkState())); -// } + CancelDisplay(); - if (!mMemberJoinTimerPtr_) { - std::string mMemberJoinTimerName = "mMemberJoinTimer"; - mMemberJoinTimerPtr_ = std::make_shared(mMemberJoinTimerName); - } - mMemberJoinTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT); + timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); LOGE("DmAuthManager OnMemberJoin start"); if (authRequestState_ != nullptr){ @@ -403,13 +429,13 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) confirmStartTimer->Start(CONFIRM_TIMEOUT, TimeOut, this); } -void DmAuthManager::StartAuthProcess(const int32_t &authType) +void DmAuthManager::StartAuthProcess(const int32_t &action) { //1. 收到请求响应,判断用户响应结果 //2. 用户授权同意 //3. 回调给认证实现模块,启动认证 LOGI("DmAuthManager:: StartAuthProcess"); - authResponseContext_->reply = 0; + authResponseContext_->reply = action; if (authResponseContext_->reply == DM_OK && authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM){ authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseGroupState())); }else { @@ -524,164 +550,6 @@ void DmAuthManager::AuthenticateFinish() LOGI("DmAuthManager::AuthenticateFinish complete"); } - -int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) -{ - std::shared_ptr abilityMgr_ = std::make_shared();; - AbilityRole role = abilityMgr_->GetAbilityRole(); - LOGI("GetAuthenticationParam:: role = %d", (int32_t)role); - if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { - if (authRequestState_ == nullptr) { - LOGE("Get Auth params FAIL : authRequestState_(nullptr)"); - return FAIL; - } - authParam.authType = AUTH_TYPE_PIN; // Currently, only Support PinCode, authType not save. - authParam.direction = (int32_t)abilityMgr_->GetAbilityRole(); - authParam.authToken = authRequestContext_->token; - LOGI("GetAuthenticationParam, role is ABILITY_ROLE_INITIATIVE"); - return SUCCESS; - } - - if (authResponseState_ == nullptr) { - LOGE("Get Auth params FAIL : authResponseState_(nullptr)"); - return FAIL; - } - - BuildAuthenticationInfo(authParam); - return SUCCESS; -} - -void DmAuthManager::OnUserOperate(int32_t action) -{ - if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { - if (authRequestState_ == nullptr) { - LOGE("authRequestState_ not exist"); - return; - } - OnUserReqSessionOperate(action); - return; - } - - if (authResponseState_ == nullptr) { - LOGE("authResponseState_ not exist"); - return; - } - OnUserRespSessionOperate(action); - -} - -void DmAuthManager::OnUserReqSessionOperate(int32_t action) -{ - if (action == FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT) { - ReqSessionRelease(); - return; - } -} - -void DmAuthManager::ReqSessionRelease() -{ - LOGI("close this session"); - sessionSession_->CloseAuthSession(authRequestContext_->sessionId); - LOGI("RequestSession:: close the channel"); -} - -void DmAuthManager::OnUserRespSessionOperate(int32_t action) -{ - switch (action) { - case FaAction::USER_OPERATION_TYPE_ALLOW_AUTH: { - OnUserConfirm(); - break; - } - case FaAction::USER_OPERATION_TYPE_CANCEL_AUTH: { - LOGI("cancle pincode display"); - Release(); - break; - } - case FaAction::USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: { - LOGI("cancle pincode display"); - Release(); - break; - } - case FaAction::USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: { - LOGI("cancle pincode display"); - Release(); - break; - } - default: { - LOGI("action %d not support", action); - break; - } - } -} - - -void DmAuthManager::Release() -{ - LOGI("ResponseSession::Release in"); - mGroupId_ = -1; - mGroupName_ = ""; - mPincode_ = -1; -} - -void DmAuthManager::OnUserConfirm() -{ - LOGI("ResponseSession::OnUserConfirm in"); - mGroupName_ = GenerateGroupName(); - hiChainConnector_->RegisterHiChainCallback(mGroupName_,shared_from_this()); - mGroupId_ = hiChainConnector_->GenRequestId(); - int32_t ret = hiChainConnector_->CreateGroup(mGroupId_, mGroupName_); - if (ret != SUCCESS) { - CancelDisplay(); - return; - } - UpdateDmFaType(DmFaType::FA_TYPE_UNKNOWN); -} - -void DmAuthManager::UpdateDmFaType(DmFaType type) -{ - switch (type) - { - case DmFaType::FA_TYPE_CONWIFI: - LOGE("ConfignetRequest::UpdateDmFaType SetDmFaType : FA_TYPE_CONWIFI"); - break; - case DmFaType::FA_TYPE_UNKNOWN: - LOGE("ConfignetRequest::UpdateDmFaType SetDmFaType : FA_TYPE_UNKNOWN"); - break; - default: - break; - } - std::shared_ptr abilityMgr_ = std::make_shared();; - abilityMgr_->SetDmFaType(type); -} - -std::string DmAuthManager::GenerateGroupName() -{ - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - // GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string sLocalDeviceID = localDeviceId; - std::string groupName = authRequestContext_->targetPkgName + authRequestContext_->hostPkgName + - sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); - return groupName; -} - -void DmAuthManager::BuildAuthenticationInfo(DmAuthParam &authParam) -{ - LOGI("BuildAuthenticationInfo in"); - std::shared_ptr abilityMgr_ = std::make_shared();; - authParam.direction = (int32_t)abilityMgr_->GetAbilityRole(); - if (authRequestState_ == nullptr) { - LOGE("BuildAuthenticationInfo authRequestState_ is nullptr"); - return; - } - - authParam.packageName = authRequestContext_->targetPkgName; - authParam.appName = authRequestContext_->appName; - authParam.appDescription = authRequestContext_->appDesc; - authParam.authType = authRequestContext_->authType; - authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION - authParam.pincode = mPincode_;//获取生成的pincode -} - void DmAuthManager::CancelDisplay() { LOGI("Cancel PinCode Display in"); @@ -697,6 +565,7 @@ void DmAuthManager::CancelDisplay() int32_t DmAuthManager::GeneratePincode() { return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); +} void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) { @@ -735,5 +604,75 @@ int32_t DmAuthManager::GetPinCode() { return authResponseContext_->code; } + +void DmAuthManager::ShowConfigDialog() +{ + LOGI("DmAuthManager::ShowConfigDialog start"); + std::shared_ptr authUi_ = std::make_shared(); + dmAbilityMgr_ = std::make_shared(); + authUi_->ShowConfirmDialog(dmAbilityMgr_); + +} + +void DmAuthManager::ShowAuthInfoDialog() +{ + LOGI("DmAuthManager::ShowAuthInfoDialog start"); + // DmConfigManager& temp = DmConfigManager::GetInstance(); + // std::string soName = "libdevicemanagerext_pin_auth.z.so"; + // std::shared_ptr ptr = temp.GetAuthAdapter(soName); + // if (ptr == nullptr) { + // LOGE("ShowAuthInfoDialog ptr is null"); + // } + + // ptr->ShowAuthInfo(); + return; + +} + +void DmAuthManager::ShowStartAuthDialog() +{ + LOGI("DmAuthManager::ShowStartAuthDialog start"); + DmConfigManager& temp = DmConfigManager::GetInstance(); + std::string soName = "libdevicemanagerext_pin_auth.z.so"; + std::shared_ptr ptr = temp.GetAuthAdapter(soName); + if (ptr == nullptr) { + LOGE("ShowStartAuthDialog ptr is null"); + } + dmAbilityMgr_ = std::make_shared(); + + ptr->StartAuth(dmAbilityMgr_); + +} + +int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) +{ + AbilityRole role = dmAbilityMgr_->GetAbilityRole(); + LOGI("GetAuthenticationParam:: role = %d", (int32_t)role); + authParam.direction = (int32_t)role; + authParam.authType = AUTH_TYPE_PIN; // Currently, only Support PinCode, authType not save. + authParam.authToken = authResponseContext_->token; + LOGI("GetAuthenticationParam:: authToken : %s", authResponseContext_->token.c_str()); + if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { + //生成pincode + authResponseContext_->code = GeneratePincode(); + LOGI("GeneratePincode:: code = %d", authResponseContext_->code); + LOGI("GetAuthenticationParam:: authParam packageName start"); + authParam.packageName = authResponseContext_->targetPkgName; + LOGI("GetAuthenticationParam:: packageName : %s", authResponseContext_->targetPkgName.c_str()); + LOGI("GetAuthenticationParam:: authParam appName start"); + authParam.appName = authResponseContext_->appName; + LOGI("GetAuthenticationParam:: appName : %s", authResponseContext_->appName.c_str()); + LOGI("GetAuthenticationParam:: authParam appDescription start"); + authParam.appDescription = authResponseContext_->appDesc; + LOGI("GetAuthenticationParam:: appDescription : %s", authResponseContext_->appDesc.c_str()); + LOGI("GetAuthenticationParam:: authParam business start"); + authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION + LOGI("GetAuthenticationParam:: business : %d", BUSINESS_FA_MIRGRATION); + LOGI("GetAuthenticationParam:: authParam pincode start"); + authParam.pincode = authResponseContext_->code;//获取生成的pincode + LOGI("GetAuthenticationParam:: pincode : %d", authResponseContext_->code); + } + return SUCCESS; +} } } \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 78f9c2510..5a882dd12 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -104,7 +104,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou } LOGI("HiChainConnector::CreateGroup requestId %lld", requestId); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - // GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; @@ -355,6 +355,24 @@ void HiChainConnector::GetSyncGroupList(std::vector &groupList, std:: } } +int32_t 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 DM_FAILED; + } + } + } + return DM_OK; +} + bool HiChainConnector::IsGroupInfoInvalid(GroupInfo &group) { if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC || diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 7c4da878a..228983edf 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -437,10 +437,15 @@ void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason 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_) { diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 0666e68ea..e98e97ea7 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -188,27 +188,25 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, c return authMgr_->VerifyAuthentication(pkgName, authParam); } -int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam, DmFaType &type) +int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam) { if (pkgName.empty()) { - LOGE("VerifyAuthentication failed, pkgName is empty"); + LOGE("GetFaParam failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - - type = abilityMgr_->GetDmFaType(); - abilityMgr_->StartAbilityDone(); authMgr_->GetAuthenticationParam(authParam); return DM_OK; } + int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action) { if (pkgName.empty()) { - LOGE("VerifyAuthentication failed, pkgName is empty"); + LOGE("SetUserOperation failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - authMgr_->OnUserOperate(action); + authMgr_->StartAuthProcess(action); return DM_OK; } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp index 26745fc2c..c93a8a9bd 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -47,19 +47,21 @@ int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity * int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { + LOGE("OnDeviceFound callback get listener in."); std::string pkgName = req->GetPkgName(); SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { LOGE("OnDeviceFound callback get listener failed."); return DM_FAILED; } - + LOGE("OnDeviceFound callback get listener 1."); 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; } + LOGE("OnDeviceFound callback get listener 2."); if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { LOGD("SendRequest failed cmdCode:%d", cmdCode); } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 1ad45c5fb..3cb6fb98c 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -181,6 +181,30 @@ ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::share return DM_OK; } +ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) +{ + LOGI("OnFaCallBack"); + 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_DEVICEMANAGER_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(); @@ -333,53 +357,44 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) { ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { std::string packName = data.ReadString(); DmAuthParam authParam; - DmFaType type; int32_t ret = DM_OK; - LOGE("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); - DeviceManagerService::GetInstance().GetFaParam(packName, authParam, type); - - if (!reply.WriteRawData(&type, sizeof(DmFaType))) { - LOGE("write appThumbnail failed"); + LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:start"); + ret = DeviceManagerService::GetInstance().GetFaParam(packName, authParam); + LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:direction:%d", authParam.direction); + LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:ret:%d", ret); + LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:pkgName:%s", packName.c_str()); + // if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + // !reply.WriteString(authParam.authToken)) { + // LOGE("DeviceManagerStub::wirte client fail"); + // return DM_IPC_FLATTEN_OBJECT; + // } + 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; } - LOGI("dmfa1 %d", type); - if(type == FA_TYPE_AUTH){ - if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || - !reply.WriteInt32(authParam.pinToken)) { - LOGE("DeviceManagerStub::wirte client fail"); - ret = DM_IPC_FLATTEN_OBJECT; - } - - 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)) { - LOGE("write reply failed"); + if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { + if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { + LOGE("write appIcon 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; - } + 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; } @@ -426,7 +441,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { // // return DM_OK; //} -// + ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParcel &reply) { std::string packageName = data.ReadString(); @@ -439,29 +454,5 @@ ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParc } return result; } - -ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) -{ - LOGI("OnFaCallBack"); - 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_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} } // 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 90c8f1b8b..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() -{ - 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::WiteforTimeout, 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::WiteforTimeout() -{ - 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) { - LOGE("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; -} -} -} -- Gitee From 809a334eb737103f540c77e78fae3ac17b360be1 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Mon, 3 Jan 2022 12:35:13 +0800 Subject: [PATCH 059/110] =?UTF-8?q?=E6=89=93=E5=8D=B0=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/ipc/standard/ipc_cmd_parser.cpp | 3 --- .../kits/js/src/native_devicemanager_js.cpp | 20 ------------------- .../src/authentication/dm_auth_manager.cpp | 18 ----------------- .../src/ipc/standard/ipc_cmd_parser.cpp | 5 ----- 4 files changed, 46 deletions(-) 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 836121d0b..e6c2bb644 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 @@ -458,11 +458,8 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) { - LOGI("OnFaCallBack"); std::string packagename = data.ReadString(); std::string paramJson = data.ReadString(); - LOGI("OnFaCallBack Packagename is %s", packagename.c_str()); - LOGI("OnFaCallBack Json is %s", paramJson.c_str()); DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); if (!reply.WriteInt32(DM_OK)) { diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 6f00537ec..0886c6301 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -346,10 +346,6 @@ void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam, napi_value ¶mResult) { - LOGI("DmAuthParamToJsAuthParam in"); - LOGI("DmAuthParamToJsAuthParam direction1: %d", authParam.direction); - LOGI("DmAuthParamToJsAuthParam authToken: %s", authParam.authToken.c_str()); - napi_value extraInfo = nullptr; napi_create_object(env, &extraInfo); SetValueInt32(env, "direction", authParam.direction, extraInfo); @@ -360,12 +356,6 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; } - LOGI("DmAuthParamToJsAuthParam SetValueUtf8String in"); - LOGI("DmAuthParamToJsAuthParam get packageName : %s", authParam.packageName.c_str()); - LOGI("DmAuthParamToJsAuthParam get appName : %s", authParam.appName.c_str()); - LOGI("DmAuthParamToJsAuthParam get appDescription : %s", authParam.appDescription.c_str()); - LOGI("DmAuthParamToJsAuthParam get business : %d", authParam.business); - LOGI("DmAuthParamToJsAuthParam get pinCode : %d", authParam.pincode); SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); SetValueUtf8String(env, "appName", authParam.appName, extraInfo); SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); @@ -373,9 +363,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); napi_set_named_property(env, paramResult, "extraInfo", extraInfo); - LOGI("DmAuthParamToJsAuthParam get appIconLen in"); size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); - LOGI("DmAuthParamToJsAuthParam get appIconLen : %d", appIconLen); if (appIconLen > 0) { void *appIcon = nullptr; napi_value appIconBuffer = nullptr; @@ -389,9 +377,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, } } - LOGI("DmAuthParamToJsAuthParam get appThumbnailLen in"); size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); - LOGI("DmAuthParamToJsAuthParam get appThumbnailLen : %d", appThumbnailLen); if (appThumbnailLen > 0) { void *appThumbnail = nullptr; napi_value appThumbnailBuffer = nullptr; @@ -784,23 +770,17 @@ napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_call NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); - LOGI("GetAuthenticationParamSync in 1"); DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - LOGI("GetAuthenticationParamSync in 2"); DmAuthParam authParam; - LOGI("GetAuthenticationParamSync in 22"); int32_t ret = DeviceManager::GetInstance().GetFaParam(deviceManagerWrapper->bundleName_, authParam); - LOGI("GetAuthenticationParamSync in 3"); if (ret != 0) { LOGE("GetAuthenticationParam for %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); napi_get_undefined(env, &resultParam); return resultParam; } - LOGI("GetAuthenticationParamSync in 4"); napi_create_object(env, &resultParam); - LOGI("GetAuthenticationParamSync direction: %d", authParam.direction); DmAuthParamToJsAuthParam(env, authParam, resultParam); return resultParam; } diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 8ddd91130..f199382a8 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -552,13 +552,11 @@ void DmAuthManager::AuthenticateFinish() void DmAuthManager::CancelDisplay() { - LOGI("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"; listener_->OnFaCall(pkgName, paramJson); - LOGI("Cancel PinCode Display success"); } @@ -607,7 +605,6 @@ int32_t DmAuthManager::GetPinCode() void DmAuthManager::ShowConfigDialog() { - LOGI("DmAuthManager::ShowConfigDialog start"); std::shared_ptr authUi_ = std::make_shared(); dmAbilityMgr_ = std::make_shared(); authUi_->ShowConfirmDialog(dmAbilityMgr_); @@ -616,7 +613,6 @@ void DmAuthManager::ShowConfigDialog() void DmAuthManager::ShowAuthInfoDialog() { - LOGI("DmAuthManager::ShowAuthInfoDialog start"); // DmConfigManager& temp = DmConfigManager::GetInstance(); // std::string soName = "libdevicemanagerext_pin_auth.z.so"; // std::shared_ptr ptr = temp.GetAuthAdapter(soName); @@ -631,7 +627,6 @@ void DmAuthManager::ShowAuthInfoDialog() void DmAuthManager::ShowStartAuthDialog() { - LOGI("DmAuthManager::ShowStartAuthDialog start"); DmConfigManager& temp = DmConfigManager::GetInstance(); std::string soName = "libdevicemanagerext_pin_auth.z.so"; std::shared_ptr ptr = temp.GetAuthAdapter(soName); @@ -647,30 +642,17 @@ void DmAuthManager::ShowStartAuthDialog() int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) { AbilityRole role = dmAbilityMgr_->GetAbilityRole(); - LOGI("GetAuthenticationParam:: role = %d", (int32_t)role); authParam.direction = (int32_t)role; authParam.authType = AUTH_TYPE_PIN; // Currently, only Support PinCode, authType not save. authParam.authToken = authResponseContext_->token; - LOGI("GetAuthenticationParam:: authToken : %s", authResponseContext_->token.c_str()); if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { //生成pincode authResponseContext_->code = GeneratePincode(); - LOGI("GeneratePincode:: code = %d", authResponseContext_->code); - LOGI("GetAuthenticationParam:: authParam packageName start"); authParam.packageName = authResponseContext_->targetPkgName; - LOGI("GetAuthenticationParam:: packageName : %s", authResponseContext_->targetPkgName.c_str()); - LOGI("GetAuthenticationParam:: authParam appName start"); authParam.appName = authResponseContext_->appName; - LOGI("GetAuthenticationParam:: appName : %s", authResponseContext_->appName.c_str()); - LOGI("GetAuthenticationParam:: authParam appDescription start"); authParam.appDescription = authResponseContext_->appDesc; - LOGI("GetAuthenticationParam:: appDescription : %s", authResponseContext_->appDesc.c_str()); - LOGI("GetAuthenticationParam:: authParam business start"); authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION - LOGI("GetAuthenticationParam:: business : %d", BUSINESS_FA_MIRGRATION); - LOGI("GetAuthenticationParam:: authParam pincode start"); authParam.pincode = authResponseContext_->code;//获取生成的pincode - LOGI("GetAuthenticationParam:: pincode : %d", authResponseContext_->code); } return SUCCESS; } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 3cb6fb98c..7555f253f 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -183,7 +183,6 @@ ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::share ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) { - LOGI("OnFaCallBack"); std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string packagname = pReq->GetPkgName(); std::string paramJson = pReq->GetJsonParam(); @@ -358,11 +357,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { std::string packName = data.ReadString(); DmAuthParam authParam; int32_t ret = DM_OK; - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:start"); ret = DeviceManagerService::GetInstance().GetFaParam(packName, authParam); - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:direction:%d", authParam.direction); - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:ret:%d", ret); - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:pkgName:%s", packName.c_str()); // if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || // !reply.WriteString(authParam.authToken)) { // LOGE("DeviceManagerStub::wirte client fail"); -- Gitee From c2c257dcb54b0ad37045c894f0c40b797b5dac36 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Mon, 3 Jan 2022 15:51:30 +0800 Subject: [PATCH 060/110] =?UTF-8?q?=E7=BC=96=E7=A0=81=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 2 +- common/include/ipc/ipc_def.h | 2 +- .../ability/standard/dm_ability_manager.cpp | 2 - .../native_cpp/include/device_manager_impl.h | 1 - .../include/notify/device_manager_notify.h | 3 +- .../native_cpp/src/device_manager_impl.cpp | 1 - .../src/ipc/lite/ipc_cmd_parser.cpp | 30 ++--- .../src/ipc/standard/ipc_cmd_parser.cpp | 5 +- .../kits/js/src/native_devicemanager_js.cpp | 108 +++++++++--------- .../include/device_manager_service_listener.h | 6 +- .../ability/standard/dm_ability_manager.cpp | 2 - .../src/authentication/auth_ui.cpp | 2 - .../src/device_manager_service.cpp | 1 - .../src/ipc/lite/ipc_cmd_parser.cpp | 16 +-- .../src/ipc/standard/ipc_cmd_parser.cpp | 44 +++---- 15 files changed, 109 insertions(+), 116 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 1dd59532d..e6065c5f9 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -129,7 +129,7 @@ namespace DistributedHardware { 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 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; diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 9f077c32c..9c7d5852c 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -49,7 +49,7 @@ enum IpcCmdID { SERVER_DISCOVER_FINISH, SERVER_AUTH_RESULT, SERVER_VERIFY_AUTH_RESULT, - SERVER_GET_DMFA_INFO, + SERVER_GET_DMFA_INFO, SERVER_USER_AUTHORIZATION_OPERATION, SERVER_DEVICEMANAGER_FA_NOTIFY, }; diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp index 089b4c17f..49d4cd53d 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -25,7 +25,6 @@ #include "single_instance.h" #include "dm_log.h" - namespace OHOS { namespace DistributedHardware { namespace { @@ -92,7 +91,6 @@ void DmAbilityManager::waitForTimeout(uint32_t timeout_s) sem_timedwait(&mSem_, &ts); } - void DmAbilityManager::StartAbilityDone() { mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; 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 0b508787d..bf6fa6d54 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -21,7 +21,6 @@ #include "ipc_client_manager.h" #include "dm_device_info.h" - namespace OHOS { namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { 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 e1986e3ee..4f8c4cf7f 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 @@ -54,7 +54,8 @@ public: 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 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: 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 1a3c85b41..ca10f1161 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -427,7 +427,6 @@ int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &dmFaPar return DM_OK; } - int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action) { LOGI("DeviceManager::SetUserOperation start"); 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 863b0efc5..16c35d1dc 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 @@ -209,20 +209,20 @@ ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo& request, uint8_t *buffer, size_t buffLen) { - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName= pReq->GetPkgName(); - int32_t action = pReq->GetOperation(); - - IpcIoInit(&request, buffer, buffLen, 0); - IpcIoPushString(&request, pkgName.c_str()); - IpcIoPushInt32(&request, action); - return DM_OK; + 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_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) { - pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); - return DM_OK; + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DM_OK; } ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply) @@ -367,11 +367,11 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply) ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply) { - size_t len = 0; - std::string packagename = (const char *)IpcIoPopString(&reply, &len); - size_t jsonLen = 0; - std::string paramJson = (const char *)IpcIoPopString(&reply, &jsonLen); - DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); + size_t len = 0; + std::string packagename = (const char *)IpcIoPopString(&reply, &len); + size_t jsonLen = 0; + std::string paramJson = (const char *)IpcIoPopString(&reply, &jsonLen); + DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); } } // 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 e6c2bb644..3c5062d60 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 @@ -367,8 +367,8 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) { - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; } ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) @@ -455,7 +455,6 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) return DM_OK; } - ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string packagename = data.ReadString(); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 0886c6301..9871a9362 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -356,40 +356,40 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; } - SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); - SetValueUtf8String(env, "appName", authParam.appName, extraInfo); - SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); - SetValueInt32(env, "business", authParam.business, extraInfo); - SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); - napi_set_named_property(env, paramResult, "extraInfo", extraInfo); - - size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); - if (appIconLen > 0) { - void *appIcon = nullptr; - 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) { - napi_value appIconArray = nullptr; - napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); - napi_set_named_property(env, paramResult, "appIcon", appIconArray); - } - } - - size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); - if (appThumbnailLen > 0) { - void *appThumbnail = nullptr; - napi_value appThumbnailBuffer = nullptr; - napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); - if (appThumbnail != nullptr && - memcpy_s(appThumbnail, appThumbnailLen, - 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); - } - } + SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); + SetValueUtf8String(env, "appName", authParam.appName, extraInfo); + SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); + SetValueInt32(env, "business", authParam.business, extraInfo); + SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); + napi_set_named_property(env, paramResult, "extraInfo", extraInfo); + + size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); + if (appIconLen > 0) { + void *appIcon = nullptr; + 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) { + napi_value appIconArray = nullptr; + napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); + napi_set_named_property(env, paramResult, "appIcon", appIconArray); + } + } + + size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); + if (appThumbnailLen > 0) { + void *appThumbnail = nullptr; + napi_value appThumbnailBuffer = nullptr; + napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); + if (appThumbnail != nullptr && + memcpy_s(appThumbnail, appThumbnailLen, + 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); + } + } } void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, @@ -763,26 +763,26 @@ 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; + 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) diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index d54f218cd..52bc1481c 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -30,8 +30,10 @@ public: 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 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_; diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp index fae78740b..e64d2ef32 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -25,7 +25,6 @@ #include "single_instance.h" #include "dm_log.h" - namespace OHOS { namespace DistributedHardware { namespace { @@ -91,7 +90,6 @@ void DmAbilityManager::waitForTimeout(uint32_t timeout_s) sem_timedwait(&mSem_, &ts); } - void DmAbilityManager::StartAbilityDone() { mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp index bdf2a5147..0cdffa33e 100644 --- a/services/devicemanagerservice/src/authentication/auth_ui.cpp +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -43,7 +43,5 @@ int32_t AuthUi::StartFaService() } return SUCCESS; } - - } } diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index e98e97ea7..1b98657bc 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -198,7 +198,6 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth return DM_OK; } - int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action) { if (pkgName.empty()) { diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 3eef5882b..5020c4b5f 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -278,18 +278,18 @@ ON_IPC_SERVER_CMD(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo &req, IpcIo &reply) 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 DM_OK; + 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_DEVICEMANAGER_FA_NOTIFY, IpcIo& request, std::shared_ptr pBaseRsp) { - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 7555f253f..1ed64f300 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -183,25 +183,25 @@ ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::share ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_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)) + 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; + return DM_OK; } ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) { - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; } ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) @@ -362,7 +362,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { // !reply.WriteString(authParam.authToken)) { // LOGE("DeviceManagerStub::wirte client fail"); // return DM_IPC_FLATTEN_OBJECT; - // } + // } int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); @@ -380,7 +380,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { LOGE("write appIcon failed"); return DM_IPC_FLATTEN_OBJECT; - } + } } if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { @@ -439,15 +439,15 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { ON_IPC_CMD(SERVER_USER_AUTHORIZATION_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; + 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 -- Gitee From fe38cfb93804c0fa6dfb63d84f32603203cec27c Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Tue, 4 Jan 2022 20:55:49 +0800 Subject: [PATCH 061/110] =?UTF-8?q?=E8=A7=84=E8=8C=83=E4=BF=AE=E6=94=B9/?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/c_cpp_properties.json | 19 --- common/include/dm_constants.h | 4 +- common/include/ipc/ipc_def.h | 4 +- .../ipc/model/ipc_authenticate_device_req.h | 3 +- .../include/ipc/model/ipc_get_dmfaparam_rsp.h | 7 +- .../ipc/model/ipc_get_local_device_info_rsp.h | 4 +- .../ipc/model/ipc_notify_dmfa_result_req.h | 4 +- .../ipc/model/ipc_set_useroperation_req.h | 4 +- .../ipc/model/ipc_start_discovery_req.h | 4 +- .../ipc/model/ipc_unauthenticate_device_req.h | 4 +- .../ipc/model/ipc_verify_authenticate_req.h | 1 - .../include/ability/dm_ability_manager.h | 16 ++- ext/pin_auth/include/pin_auth.h | 4 +- ext/pin_auth/include/pin_auth_ui.h | 5 +- .../src/ability/lite/dm_ability_manager.cpp | 5 +- .../ability/standard/dm_ability_manager.cpp | 45 ++----- ext/pin_auth/src/pin_auth.cpp | 8 +- ext/pin_auth/src/pin_auth_ui.cpp | 25 ++-- .../native_cpp/include/device_manager.h | 4 +- .../include/device_manager_callback.h | 2 +- .../native_cpp/include/dm_device_info.h | 1 + .../include/notify/device_manager_notify.h | 6 +- .../native_cpp/src/device_manager.cpp | 1 + .../native_cpp/src/device_manager_impl.cpp | 28 ++--- .../src/ipc/lite/ipc_cmd_parser.cpp | 54 +------- .../src/ipc/standard/ipc_client_manager.cpp | 10 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 61 +-------- .../kits/js/include/native_devicemanager_js.h | 9 +- .../kits/js/src/native_devicemanager_js.cpp | 117 +++++++----------- .../include/ability/dm_ability_manager.h | 12 +- .../include/authentication/auth_ui.h | 1 + .../include/authentication/authentication.h | 1 - .../include/authentication/dm_auth_manager.h | 20 +-- .../include/device_manager_service.h | 2 +- .../include/device_manager_service_listener.h | 6 +- .../src/ability/lite/dm_ability_manager.cpp | 4 +- .../ability/standard/dm_ability_manager.cpp | 37 +----- .../src/authentication/auth_request_state.cpp | 3 +- .../src/authentication/auth_ui.cpp | 16 +-- .../src/authentication/dm_auth_manager.cpp | 74 +++++------ .../dependency/hichain/hichain_connector.cpp | 2 +- .../src/device_manager_service.cpp | 11 +- .../src/device_manager_service_listener.cpp | 2 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 44 +------ .../src/ipc/lite/ipc_server_listener.cpp | 5 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 95 ++++---------- 46 files changed, 236 insertions(+), 558 deletions(-) delete mode 100644 .vscode/c_cpp_properties.json diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json deleted file mode 100644 index 46cf7f48c..000000000 --- a/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "configurations": [ - { - "name": "Win32", - "includePath": [ - "${workspaceFolder}/**" - ], - "defines": [ - "_DEBUG", - "UNICODE", - "_UNICODE" - ], - "cStandard": "c17", - "cppStandard": "c++17", - "intelliSenseMode": "windows-msvc-x64" - } - ], - "version": 4 -} \ No newline at end of file diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 1dd59532d..86cd85f9a 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -45,8 +45,6 @@ namespace DistributedHardware { 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 FAIL = -1; - const int32_t SUCCESS = 0; // const int32_t TOKEN_LEN = 9; enum { @@ -133,6 +131,8 @@ namespace DistributedHardware { 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; diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 9f077c32c..5912acd64 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -50,8 +50,8 @@ enum IpcCmdID { SERVER_AUTH_RESULT, SERVER_VERIFY_AUTH_RESULT, SERVER_GET_DMFA_INFO, - SERVER_USER_AUTHORIZATION_OPERATION, - SERVER_DEVICEMANAGER_FA_NOTIFY, + 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 931ec6abe..cc20f75f9 100644 --- a/common/include/ipc/model/ipc_authenticate_device_req.h +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -16,9 +16,10 @@ #ifndef OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H #define OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H -#include "ipc_req.h" #include "dm_device_info.h" +#include "ipc_req.h" + namespace OHOS { namespace DistributedHardware { class IpcAuthenticateDeviceReq : public IpcReq { diff --git a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h index d79008ddd..f8a74ec9b 100644 --- a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h +++ b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h @@ -16,20 +16,21 @@ #ifndef OHOS_DEVICE_MANAGER_IPC_GET_DM_FA_PARAM_RSP_H #define OHOS_DEVICE_MANAGER_IPC_GET_DM_FA_PARAM_RSP_H -#include "ipc_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 + const DmAuthParam GetDmAuthParam() const { return dmFaParam_; } - void SetDmAuthParam(DmAuthParam &dmFaParam) + void SetDmAuthParam(const DmAuthParam &dmFaParam) { dmFaParam_ = dmFaParam; } 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 index 3f9854cbd..b2056ba64 100644 --- a/common/include/ipc/model/ipc_get_local_device_info_rsp.h +++ b/common/include/ipc/model/ipc_get_local_device_info_rsp.h @@ -16,9 +16,10 @@ #ifndef OHOS_DM_IPC_GET_LOCAL_DEVICE_INFO_RSP_H #define OHOS_DM_IPC_GET_LOCAL_DEVICE_INFO_RSP_H -#include "ipc_rsp.h" #include "dm_device_info.h" +#include "ipc_req.h" + namespace OHOS { namespace DistributedHardware { class IpcGetLocalDeviceInfoRsp : public IpcRsp { @@ -38,5 +39,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS - #endif // OHOS_DM_IPC_GET_TRUSTDEVICE_RSP_H \ No newline at end of file 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..a222878e3 100644 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -30,7 +30,7 @@ public: return JsonParam_; } - void SetJsonParam(std::string& JsonParam) + void SetJsonParam(const std::string& JsonParam) { JsonParam_ = JsonParam; } @@ -39,4 +39,4 @@ private: }; } // 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_set_useroperation_req.h b/common/include/ipc/model/ipc_set_useroperation_req.h index e2f51db3f..90a873c51 100644 --- a/common/include/ipc/model/ipc_set_useroperation_req.h +++ b/common/include/ipc/model/ipc_set_useroperation_req.h @@ -15,9 +15,11 @@ #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 { diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h index 5a2918ced..c8b77ac2f 100644 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ b/common/include/ipc/model/ipc_start_discovery_req.h @@ -16,10 +16,10 @@ #ifndef OHOS_DM_IPC_START_DISCOVERY_REQ_H #define OHOS_DM_IPC_START_DISCOVERY_REQ_H -#include "ipc_req.h" - #include "dm_subscribe_info.h" +#include "ipc_req.h" + namespace OHOS { namespace DistributedHardware { class IpcStartDiscoveryReq : public IpcReq { diff --git a/common/include/ipc/model/ipc_unauthenticate_device_req.h b/common/include/ipc/model/ipc_unauthenticate_device_req.h index 1b44b9336..fa6c3dcb7 100644 --- a/common/include/ipc/model/ipc_unauthenticate_device_req.h +++ b/common/include/ipc/model/ipc_unauthenticate_device_req.h @@ -16,9 +16,10 @@ #ifndef OHOS_DM_IPC_UNAUTHENTICATE_DEVICE_REQ_H #define OHOS_DM_IPC_UNAUTHENTICATE_DEVICE_REQ_H -#include "ipc_req.h" #include "dm_device_info.h" +#include "ipc_req.h" + namespace OHOS { namespace DistributedHardware { class IpcUnAuthenticateDeviceReq : public IpcReq { @@ -38,5 +39,4 @@ private: }; } // 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 index da2b5472c..26400c66e 100644 --- a/common/include/ipc/model/ipc_verify_authenticate_req.h +++ b/common/include/ipc/model/ipc_verify_authenticate_req.h @@ -37,5 +37,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS - #endif // OHOS_DEVICE_MANAGER_IPC_VERIFY_AUTHENTICATE_REQ_H diff --git a/ext/pin_auth/include/ability/dm_ability_manager.h b/ext/pin_auth/include/ability/dm_ability_manager.h index dd39026ec..2cb96ec26 100644 --- a/ext/pin_auth/include/ability/dm_ability_manager.h +++ b/ext/pin_auth/include/ability/dm_ability_manager.h @@ -16,34 +16,32 @@ #ifndef OHOS_DM_ABILITY_MANAGER_H #define OHOS_DM_ABILITY_MANAGER_H -#include -#include #include +#include #include - -#include "single_instance.h" +#include namespace OHOS { namespace DistributedHardware { -enum AbilityRole : int32_t { +enum AbilityRole { ABILITY_ROLE_PASSIVE = 0, ABILITY_ROLE_INITIATIVE = 1, ABILITY_ROLE_UNKNOWN = 2 }; -enum AbilityStatus : int32_t { +enum AbilityStatus { ABILITY_STATUS_FAILED = 0, ABILITY_STATUS_SUCCESS = 1, ABILITY_STATUS_START = 2 }; -typedef enum FaAction { +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 { public: @@ -60,4 +58,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif +#endif // OHOS_DM_ABILITY_MANAGER_H diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h index 556663d58..a15e8390e 100644 --- a/ext/pin_auth/include/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.h @@ -18,9 +18,10 @@ #include #include -#include "pin_auth_ui.h" + #include "authentication.h" #include "dm_ability_manager.h" +#include "pin_auth_ui.h" namespace OHOS { namespace DistributedHardware { @@ -34,7 +35,6 @@ public: private: 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 index d98f9763a..018587678 100644 --- a/ext/pin_auth/include/pin_auth_ui.h +++ b/ext/pin_auth/include/pin_auth_ui.h @@ -17,6 +17,7 @@ #define OHOS_DM_PIN_AUTH_UI_H #include + #include "dm_ability_manager.h" namespace OHOS { @@ -28,9 +29,7 @@ public: int32_t InputPinDialog(std::shared_ptr dmAbilityManager); private: - int32_t StartFaService(); -private: - std::shared_ptr dmAbilityMgr_ ; + int32_t StartFaUiService(std::shared_ptr dmAbilityManager); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp index 1570551ba..539b52f96 100644 --- a/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp @@ -15,13 +15,12 @@ #include "dm_ability_manager.h" -#include "semaphore.h" +#include #include "dm_constants.h" namespace OHOS { namespace DistributedHardware { - AbilityRole DmAbilityManager::GetAbilityRole() { return mAbilityStatus_; @@ -37,7 +36,7 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) void DmAbilityManager::waitForTimeout(uint32_t timeout_s) { - struct timespec ts; + struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += timeout_s; sem_timedwait(&mSem_, &ts); diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp index 089b4c17f..82736fc8c 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -18,18 +18,17 @@ #include "ability_manager_client.h" #include "ability_record.h" #include "ability_manager_service.h" -#include "parameter.h" -#include "semaphore.h" - #include "dm_constants.h" -#include "single_instance.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 bundleName = "com.ohos.devicemanagerui"; +const std::string abilityName = "com.ohos.devicemanagerui.MainAbility"; } AbilityRole DmAbilityManager::GetAbilityRole() @@ -39,47 +38,21 @@ AbilityRole DmAbilityManager::GetAbilityRole() AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) { - LOGI("pinauthui StartAbility, role %d", (int32_t)role); - std::string roleStr; - if (role == AbilityRole::ABILITY_ROLE_INITIATIVE) { - roleStr = "initiative"; - } else if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { - roleStr = "passive"; - } else { - LOGE("StartAbility, failed, role unknown"); - return AbilityStatus::ABILITY_STATUS_FAILED; - } - - LOGI("StartAbility, role %s", roleStr.c_str()); mAbilityStatus_ = role; - LOGI("pinauthui StartAbility, mAbilityStatus_ :%d", (int32_t)mAbilityStatus_); - 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) ? - DISPLAY_OWNER_OTHER : DISPLAY_OWNER_SYSTEM; - - mStatus_ = AbilityStatus::ABILITY_STATUS_START; + mStatus_ = ABILITY_STATUS_START; AAFwk::Want want; AppExecFwk::ElementName element(deviceId, bundleName, abilityName); want.SetElement(element); - LOGI("StartAbility, displayOwner %d", displayOwner); - // if (displayOwner == DISPLAY_OWNER_OTHER) { - // LOGI("StartAbility, other display no need to start ability"); - // return AbilityStatus::ABILITY_STATUS_SUCCESS; - // } AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); - if (result == OHOS::ERR_OK) { - LOGI("Start Ability succeed"); - } else { + if (result != DM_OK) { LOGE("Start Ability faild"); - mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; + mStatus_ = ABILITY_STATUS_FAILED; return mStatus_; - } + } waitForTimeout(ABILITY_START_TIMEOUT); return mStatus_; } @@ -95,7 +68,7 @@ void DmAbilityManager::waitForTimeout(uint32_t timeout_s) void DmAbilityManager::StartAbilityDone() { - mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + mStatus_ = ABILITY_STATUS_SUCCESS; sem_post(&mSem_); } } diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 9124181f9..74dc69a54 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -14,17 +14,17 @@ */ #include "pin_auth.h" -#include "dm_constants.h" -#include "dm_log.h" #include +#include "dm_constants.h" +#include "dm_log.h" + namespace OHOS { namespace DistributedHardware { PinAuth::PinAuth() { LOGI("PinAuth constructor"); - } PinAuth::~PinAuth() @@ -34,13 +34,11 @@ PinAuth::~PinAuth() int32_t PinAuth::ShowAuthInfo() { - LOGI("PinAuth::ShowAuthInfo in"); return pinAuthUi_->ShowPinDialog(); } int32_t PinAuth::StartAuth(std::shared_ptr dmAbilityManager) { - LOGI("PinAuth::StartAuth in"); return pinAuthUi_->InputPinDialog(dmAbilityManager); } diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index b3ce28a8c..69ffb0e45 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -14,6 +14,7 @@ */ #include "pin_auth_ui.h" + #include "dm_ability_manager.h" #include "dm_constants.h" #include "dm_log.h" @@ -28,30 +29,26 @@ PinAuthUi::PinAuthUi() int32_t PinAuthUi::ShowPinDialog() { - LOGI("PinAuthUi::ShowPinDialog in"); - return SUCCESS; + return DM_OK; } int32_t PinAuthUi::InputPinDialog(std::shared_ptr dmAbilityManager) { - LOGI("PinAuthUi::InputPinDialog in"); - if (dmAbilityMgr_ == nullptr) { - LOGI("PinAuthUi::dmAbilityMgr_ is null"); - dmAbilityMgr_ = dmAbilityManager; - } - return StartFaService(); + if (dmAbilityManager == nullptr) { + LOGE("PinAuthUi::dmAbilityManager is null"); + return DM_FAILED; + } + return StartFaUiService(dmAbilityManager); } -int32_t PinAuthUi::StartFaService() +int32_t PinAuthUi::StartFaUiService(std::shared_ptr dmAbilityManager) { - LOGI("PinAuthUi::StartFaService in"); - AbilityStatus status = dmAbilityMgr_->StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); + AbilityStatus status = dmAbilityManager->StartAbility(AbilityRole::ABILITY_ROLE_INITIATIVE); if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { LOGE("PinAuthUi::StartFaService timeout"); - return FAIL; + return DM_FAILED; } - return SUCCESS; + return DM_OK; } - } } diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 3b52c8a0b..14152823e 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -46,8 +46,8 @@ public: 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 GetFaParam(std::string &pkgName, DmAuthParam &faParam) = 0; - virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) = 0; + virtual int32_t GetFaParam(const std::string &pkgName, const DmAuthParam &faParam) = 0; + virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index e96c9e582..2a1a079cf 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -60,7 +60,7 @@ public: class DeviceManagerFaCallback { public: virtual ~DeviceManagerFaCallback() {} - virtual void OnCall(std::string ¶mJson) = 0; + virtual void OnCall(const std::string ¶mJson) = 0; }; } // namespace DistributedHardware } // namespace OHOS 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 ff58e67d0..eb2c32523 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -17,6 +17,7 @@ #define OHOS_DM_DEVICE_INFO_H #include + #include "dm_app_image_info.h" #define DM_MAX_DEVICE_ID_LEN (96) 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 e1986e3ee..fc541f55b 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 @@ -54,8 +54,10 @@ public: 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 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_; diff --git a/interfaces/inner_kits/native_cpp/src/device_manager.cpp b/interfaces/inner_kits/native_cpp/src/device_manager.cpp index b3cfbfcd5..4bedc0a57 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager.cpp @@ -14,6 +14,7 @@ */ #include "device_manager.h" + #include "device_manager_impl.h" namespace OHOS { diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 1a3c85b41..13d5ffba2 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,6 +15,10 @@ #include "device_manager_impl.h" +#include "bundle_info.h" +#include "bundle_constants.h" +#include "bundle_mgr_client.h" + #include "dm_log.h" #include "dm_constants.h" #include "device_manager_notify.h" @@ -31,11 +35,7 @@ #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" #include "ipc_set_useroperation_req.h" - -#include "bundle_info.h" #include "ipc_skeleton.h" -#include "bundle_constants.h" -#include "bundle_mgr_client.h" using namespace OHOS::AppExecFwk; using namespace OHOS::AppExecFwk::Constants; @@ -375,12 +375,10 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons 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()) { LOGE("VerifyAuthentication error: Invalid para"); return DM_INVALID_VALUE; @@ -390,12 +388,12 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetAuthPara(authPara); + 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); @@ -403,46 +401,42 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons } DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); - LOGI("DeviceManager::VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); return DM_OK; } -int32_t DeviceManagerImpl::GetFaParam(std::string &pkgName, DmAuthParam &dmFaParam) +int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, const DmAuthParam &dmFaParam) { - LOGI("DeviceManagerImpl::GetFaParam start"); 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); - LOGI("DeviceManagerImpl::GetFaParam start 1"); + if (ipcClientProxy_->SendRequest(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { LOGI("DeviceManagerImpl::GetFaParam start 2"); return DM_IPC_SEND_REQUEST_FAILED; } - LOGI("DeviceManagerImpl::GetFaParam start 3"); dmFaParam = rsp->GetDmAuthParam(); return DM_OK; } -int32_t DeviceManagerImpl::SetUserOperation(std::string &pkgName, int32_t action) +int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action) { - LOGI("DeviceManager::SetUserOperation start"); 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) != DM_OK) { + if (ipcClientProxy_->SendRequest(SERVER_USER_AUTH_OPERATION, req, rsp) != DM_OK) { return DM_IPC_SEND_REQUEST_FAILED; } int32_t ret = rsp->GetErrCode(); 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 863b0efc5..65c0f523a 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 @@ -206,7 +206,7 @@ ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo& request, +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); @@ -219,7 +219,7 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_USER_AUTH_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); return DM_OK; @@ -317,55 +317,7 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply) DeviceManagerNotify::GetInstance().OnVerifyAuthResult(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 DM_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 DM_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 DM_OK; -//} - -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 c071e1508..a2b1815a5 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 @@ -15,17 +15,15 @@ #include "ipc_client_manager.h" +#include "device_manager_notify.h" +#include "dm_constants.h" +#include "dm_log.h" #include "iremote_object.h" #include "iservice_registry.h" -#include "system_ability_definition.h" - #include "ipc_remote_broker.h" #include "ipc_client_stub.h" #include "ipc_register_listener_req.h" - -#include "dm_constants.h" -#include "dm_log.h" -#include "device_manager_notify.h" +#include "system_ability_definition.h" namespace OHOS { namespace DistributedHardware { diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index 836121d0b..6ba603e66 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 @@ -16,11 +16,11 @@ #include "ipc_cmd_register.h" #include "securec.h" + #include "dm_constants.h" #include "dm_log.h" #include "dm_device_info.h" #include "device_manager_notify.h" - #include "ipc_def.h" #include "ipc_rsp.h" #include "ipc_req.h" @@ -288,7 +288,6 @@ ON_IPC_READ_RESPONSE(SERVER_GET_DMFA_INFO, MessageParcel &reply, std::shared_ptr { std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); DmAuthParam authParam; - authParam.direction = reply.ReadInt32(); authParam.authType = reply.ReadInt32(); authParam.authToken = reply.ReadString(); @@ -297,23 +296,11 @@ ON_IPC_READ_RESPONSE(SERVER_GET_DMFA_INFO, MessageParcel &reply, std::shared_ptr 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->SetDmAuthParam(authParam); return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr pBaseReq, MessageParcel &data) +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(); @@ -331,41 +318,7 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr return DM_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 DM_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 DM_OK; -//} - -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_USER_AUTH_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; @@ -438,7 +391,6 @@ ON_IPC_CMD(SERVER_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) std::string token = data.ReadString(); int32_t status = data.ReadInt32(); int32_t reason = data.ReadInt32(); - DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, token, status, reason); reply.WriteInt32(DM_OK); return DM_OK; @@ -455,16 +407,11 @@ ON_IPC_CMD(SERVER_VERIFY_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) return DM_OK; } - -ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(SERVER_DEVICE_FA_NOTIFY, MessageParcel &data, MessageParcel &reply) { - LOGI("OnFaCallBack"); std::string packagename = data.ReadString(); std::string paramJson = data.ReadString(); - LOGI("OnFaCallBack Packagename is %s", packagename.c_str()); - LOGI("OnFaCallBack Json is %s", paramJson.c_str()); DeviceManagerNotify::GetInstance().OnFaCall(packagename, paramJson); - if (!reply.WriteInt32(DM_OK)) { LOGE("write return failed"); return DM_WRITE_FAILED; diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 4fdbc9b77..d8807340c 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -18,15 +18,16 @@ #include #include -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#include "nlohmann/json.hpp" + #include "device_manager_callback.h" #include "dm_native_event.h" #include "dm_device_info.h" #include "dm_subscribe_info.h" #include "dm_device_info.h" #include "dm_app_image_info.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "nlohmann/json.hpp" #define DM_NAPI_BUF_LENGTH (256) struct AsyncCallbackInfo { @@ -116,7 +117,7 @@ class DmNapiDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceMa public: explicit DmNapiDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) {} virtual ~DmNapiDeviceManagerFaCallback() {}; - void OnCall(std::string ¶mJson) override; + void OnCall(const std::string ¶mJson) override; private: std::string bundleName_; diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 6f00537ec..97f91c7dd 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -16,12 +16,12 @@ #include "native_devicemanager_js.h" #include -#include "nlohmann/json.hpp" #include "device_manager.h" #include "dm_log.h" #include "dm_constants.h" #include "dm_device_info.h" +#include "nlohmann/json.hpp" using namespace OHOS::DistributedHardware; @@ -346,64 +346,51 @@ void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam, napi_value ¶mResult) { - LOGI("DmAuthParamToJsAuthParam in"); - LOGI("DmAuthParamToJsAuthParam direction1: %d", authParam.direction); - LOGI("DmAuthParamToJsAuthParam authToken: %s", authParam.authToken.c_str()); - napi_value extraInfo = nullptr; napi_create_object(env, &extraInfo); SetValueInt32(env, "direction", authParam.direction, extraInfo); SetValueInt32(env, "authType", authParam.authType, paramResult); - SetValueInt32(env, "pinToken", atoi(authParam.authToken.c_str()), extraInfo); - LOGI("DmAuthParamToJsAuthParam direction2: %d", authParam.direction); + SetValueInt32(env, "pinToken", stoi(authParam.authToken), extraInfo); + if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); return; } - LOGI("DmAuthParamToJsAuthParam SetValueUtf8String in"); - LOGI("DmAuthParamToJsAuthParam get packageName : %s", authParam.packageName.c_str()); - LOGI("DmAuthParamToJsAuthParam get appName : %s", authParam.appName.c_str()); - LOGI("DmAuthParamToJsAuthParam get appDescription : %s", authParam.appDescription.c_str()); - LOGI("DmAuthParamToJsAuthParam get business : %d", authParam.business); - LOGI("DmAuthParamToJsAuthParam get pinCode : %d", authParam.pincode); - SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); - SetValueUtf8String(env, "appName", authParam.appName, extraInfo); - SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); - SetValueInt32(env, "business", authParam.business, extraInfo); - SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); - napi_set_named_property(env, paramResult, "extraInfo", extraInfo); - - LOGI("DmAuthParamToJsAuthParam get appIconLen in"); - size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); - LOGI("DmAuthParamToJsAuthParam get appIconLen : %d", appIconLen); - if (appIconLen > 0) { - void *appIcon = nullptr; - 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) { - napi_value appIconArray = nullptr; - napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); - napi_set_named_property(env, paramResult, "appIcon", appIconArray); - } - } - LOGI("DmAuthParamToJsAuthParam get appThumbnailLen in"); - size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); - LOGI("DmAuthParamToJsAuthParam get appThumbnailLen : %d", appThumbnailLen); - if (appThumbnailLen > 0) { - void *appThumbnail = nullptr; - napi_value appThumbnailBuffer = nullptr; - napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); - if (appThumbnail != nullptr && - memcpy_s(appThumbnail, appThumbnailLen, - 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); - } - } + SetValueUtf8String(env, "packageName", authParam.packageName, extraInfo); + SetValueUtf8String(env, "appName", authParam.appName, extraInfo); + SetValueUtf8String(env, "appDescription", authParam.appDescription, extraInfo); + SetValueInt32(env, "business", authParam.business, extraInfo); + SetValueInt32(env, "pinCode", authParam.pincode, extraInfo); + napi_set_named_property(env, paramResult, "extraInfo", extraInfo); + + size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); + if (appIconLen > 0) { + void *appIcon = nullptr; + 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) { + napi_value appIconArray = nullptr; + napi_create_typedarray(env, napi_uint8_array, appIconLen, appIconBuffer, 0, &appIconArray); + napi_set_named_property(env, paramResult, "appIcon", appIconArray); + } + } + + size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); + if (appThumbnailLen > 0) { + void *appThumbnail = nullptr; + napi_value appThumbnailBuffer = nullptr; + napi_create_arraybuffer(env, appThumbnailLen, &appThumbnail, &appThumbnailBuffer); + if (appThumbnail != nullptr && + memcpy_s(appThumbnail, appThumbnailLen, + 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); + } + } } void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, @@ -677,25 +664,12 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob nlohmann::json jsonObj; //TODO: -// jsonObj[AUTH_TYPE] = authType; -// if (authType == DM_AUTH_TYPE_PINCODE) { -// jsonObj[PIN_TOKEN] = token; -// } else { -// jsonObj[TOKEN] = token; -// } + jsonObj[AUTH_TYPE] = authType; + jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); extra = jsonObj.dump(); } -// void DeviceManagerNapi::JsToDmFilterOptions(const napi_env &env, const napi_value &object, -// DmFilterOptions &filterOptions) -// { -// JsObjectToString(env, object, "targetPkgName", filterOptions.targetPkgName, sizeof(filterOptions.targetPkgName)); -// int32_t sortType = -1; -// JsObjectToInt(env, object, "sortType", sortType); -// filterOptions.sortType = (DmDeviceSortType)sortType; -// JsObjectToString(env, object, "filter", filterOptions.filter, sizeof(filterOptions.filter)); -// } void DeviceManagerNapi::DmDeviceInfotoJsDeviceInfo(const napi_env &env, const DmDeviceInfo &vecDevInfo, @@ -777,30 +751,24 @@ 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"); - LOGI("GetAuthenticationParamSync in 1"); + DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - LOGI("GetAuthenticationParamSync in 2"); DmAuthParam authParam; - LOGI("GetAuthenticationParamSync in 22"); int32_t ret = DeviceManager::GetInstance().GetFaParam(deviceManagerWrapper->bundleName_, authParam); - LOGI("GetAuthenticationParamSync in 3"); if (ret != 0) { LOGE("GetAuthenticationParam for %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); napi_get_undefined(env, &resultParam); return resultParam; } - LOGI("GetAuthenticationParamSync in 4"); napi_create_object(env, &resultParam); - LOGI("GetAuthenticationParamSync direction: %d", authParam.direction); DmAuthParamToJsAuthParam(env, authParam, resultParam); return resultParam; } @@ -819,8 +787,7 @@ 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) { - LOGE("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); @@ -861,7 +828,7 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_st } } -void DmNapiDeviceManagerFaCallback::OnCall(std::string ¶mJson) +void DmNapiDeviceManagerFaCallback::OnCall(const std::string ¶mJson) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h index dd39026ec..e874851c7 100644 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ b/services/devicemanagerservice/include/ability/dm_ability_manager.h @@ -16,34 +16,34 @@ #ifndef OHOS_DM_ABILITY_MANAGER_H #define OHOS_DM_ABILITY_MANAGER_H -#include -#include #include +#include #include +#include #include "single_instance.h" namespace OHOS { namespace DistributedHardware { -enum AbilityRole : int32_t { +enum AbilityRole { ABILITY_ROLE_PASSIVE = 0, ABILITY_ROLE_INITIATIVE = 1, ABILITY_ROLE_UNKNOWN = 2 }; -enum AbilityStatus : int32_t { +enum AbilityStatus { ABILITY_STATUS_FAILED = 0, ABILITY_STATUS_SUCCESS = 1, ABILITY_STATUS_START = 2 }; -typedef enum FaAction { +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 { public: diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h index 0639bb8f9..20c5ec32c 100644 --- a/services/devicemanagerservice/include/authentication/auth_ui.h +++ b/services/devicemanagerservice/include/authentication/auth_ui.h @@ -17,6 +17,7 @@ #define OHOS_DM_AUTH_UI_H #include + #include "dm_ability_manager.h" namespace OHOS { diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h index d68118306..5ebce1f20 100644 --- a/services/devicemanagerservice/include/authentication/authentication.h +++ b/services/devicemanagerservice/include/authentication/authentication.h @@ -30,5 +30,4 @@ public: 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 index 27d024686..2260f808c 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -20,19 +20,19 @@ #include #include "authentication.h" +#include "auth_ui.h" +#include "auth_message_processor.h" +#include "auth_request_state.h" +#include "auth_response_state.h" #include "dm_ability_manager.h" #include "dm_device_info.h" -#include "softbus_session.h" +#include "dm_timer.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 "auth_ui.h" +#include "softbus_connector.h" +#include "softbus_session.h" namespace OHOS { namespace DistributedHardware { @@ -89,7 +89,7 @@ typedef struct DmAuthRequestContext { std::string token; int32_t reason; std::vector syncGroupList; -} DmAuthRequestContext ; +} DmAuthRequestContext; typedef struct DmAuthResponseContext { int32_t authType; @@ -125,7 +125,7 @@ public: ~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 &pkgName, const std::string &authParam); + 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); @@ -169,7 +169,7 @@ private: std::shared_ptr authMessageProcessor_; std::map> timerMap_; std::shared_ptr data_; - std::shared_ptr dmAbilityMgr_ ; + std::shared_ptr dmAbilityMgr_; bool isCryptoSupport_ = false; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index b7f740156..dca3a4836 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -40,7 +40,7 @@ public: 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 &pkgName, const std::string &authParam); + 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: diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index d54f218cd..bcd1e39f5 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -30,8 +30,10 @@ public: 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 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_; diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp index 1570551ba..d87cd3eed 100644 --- a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp @@ -15,13 +15,11 @@ #include "dm_ability_manager.h" -#include "semaphore.h" - #include "dm_constants.h" +#include "semaphore.h" namespace OHOS { namespace DistributedHardware { - AbilityRole DmAbilityManager::GetAbilityRole() { return mAbilityStatus_; diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp index fae78740b..b0a8f1bf2 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -18,18 +18,18 @@ #include "ability_manager_client.h" #include "ability_record.h" #include "ability_manager_service.h" +#include "dm_constants.h" +#include "dm_log.h" #include "parameter.h" #include "semaphore.h" - -#include "dm_constants.h" #include "single_instance.h" -#include "dm_log.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"; } AbilityRole DmAbilityManager::GetAbilityRole() @@ -39,46 +39,21 @@ AbilityRole DmAbilityManager::GetAbilityRole() 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 { - LOGE("StartAbility, failed, role unknown"); - return AbilityStatus::ABILITY_STATUS_FAILED; - } - - LOGI("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) ? - DISPLAY_OWNER_OTHER : DISPLAY_OWNER_SYSTEM; - mStatus_ = AbilityStatus::ABILITY_STATUS_START; AAFwk::Want want; AppExecFwk::ElementName element(deviceId, bundleName, abilityName); want.SetElement(element); - LOGI("StartAbility, displayOwner %d", displayOwner); - // if (displayOwner == DISPLAY_OWNER_OTHER) { - // LOGI("StartAbility, other display no need to start ability"); - // return AbilityStatus::ABILITY_STATUS_SUCCESS; - // } AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); - LOGI("StartAbility, AAFwk running"); - if (result == OHOS::ERR_OK) { - LOGI("Start Ability succeed"); - } else { + if (result != DM_OK) { LOGE("Start Ability faild"); mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; return mStatus_; - } + } waitForTimeout(ABILITY_START_TIMEOUT); return mStatus_; } diff --git a/services/devicemanagerservice/src/authentication/auth_request_state.cpp b/services/devicemanagerservice/src/authentication/auth_request_state.cpp index d00b65f74..accf29ebb 100644 --- a/services/devicemanagerservice/src/authentication/auth_request_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -17,9 +17,8 @@ #include - -#include "dm_constants.h" #include "dm_auth_manager.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp index bdf2a5147..06287f619 100644 --- a/services/devicemanagerservice/src/authentication/auth_ui.cpp +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -14,13 +14,13 @@ */ #include "auth_ui.h" + #include "dm_ability_manager.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { - AuthUi::AuthUi() { LOGI("AuthUi constructor"); @@ -28,22 +28,22 @@ AuthUi::AuthUi() int32_t AuthUi::ShowConfirmDialog(std::shared_ptr dmAbilityManager) { - LOGI("AuthUi::ShowConfirmDialog in"); + if (dmAbilityManager == nullptr) { + LOGE("AuthUi::dmAbilityManager is null"); + return DM_FAILED; + } dmAbilityMgr_ = dmAbilityManager; return StartFaService(); } int32_t AuthUi::StartFaService() { - LOGI("AuthUi::StartFaService in"); AbilityStatus status = dmAbilityMgr_->StartAbility(AbilityRole::ABILITY_ROLE_PASSIVE); if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) { LOGE("AuthUi::StartFaService timeout"); - return FAIL; + return DM_FAILED; } - return SUCCESS; + return DM_OK; } - - } } diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 8ddd91130..f307e9e11 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -17,13 +17,14 @@ #include "nlohmann/json.hpp" -#include "dm_log.h" -#include "dm_random.h" -#include "dm_constants.h" -#include "config_manager.h" #include "auth_message_processor.h" -#include "dm_ability_manager.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" + namespace OHOS { namespace DistributedHardware { @@ -160,11 +161,20 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st return DM_OK; } -int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) +int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) { LOGI("DmAuthManager::VerifyAuthentication"); timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - int32_t pinCode = 123456; + 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)){ + LOGE("err json string, first time"); + return DM_FAILED; + } + int32_t pinCode = jsonObject[PIN_CODE_KEY]; int32_t times = 0; if (pinCode == authResponseContext_->code && authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT){ authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); @@ -175,9 +185,10 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &pkgName, const st authResponseContext_->reply = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = DM_AUTH_INPUT_FAILED; authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + CancelDisplay(); return DM_FAILED; } - CancelDisplay(); + LOGI("DmAuthManager::VerifyAuthentication complete"); return DM_OK; } @@ -313,7 +324,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) { - + LOGI("DmAuthManager OnMemberJoin start"); CancelDisplay(); timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); @@ -552,13 +563,11 @@ void DmAuthManager::AuthenticateFinish() void DmAuthManager::CancelDisplay() { - LOGI("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"; listener_->OnFaCall(pkgName, paramJson); - LOGI("Cancel PinCode Display success"); } @@ -607,31 +616,18 @@ int32_t DmAuthManager::GetPinCode() void DmAuthManager::ShowConfigDialog() { - LOGI("DmAuthManager::ShowConfigDialog start"); std::shared_ptr authUi_ = std::make_shared(); dmAbilityMgr_ = std::make_shared(); authUi_->ShowConfirmDialog(dmAbilityMgr_); - } void DmAuthManager::ShowAuthInfoDialog() { - LOGI("DmAuthManager::ShowAuthInfoDialog start"); - // DmConfigManager& temp = DmConfigManager::GetInstance(); - // std::string soName = "libdevicemanagerext_pin_auth.z.so"; - // std::shared_ptr ptr = temp.GetAuthAdapter(soName); - // if (ptr == nullptr) { - // LOGE("ShowAuthInfoDialog ptr is null"); - // } - - // ptr->ShowAuthInfo(); return; - } void DmAuthManager::ShowStartAuthDialog() { - LOGI("DmAuthManager::ShowStartAuthDialog start"); DmConfigManager& temp = DmConfigManager::GetInstance(); std::string soName = "libdevicemanagerext_pin_auth.z.so"; std::shared_ptr ptr = temp.GetAuthAdapter(soName); @@ -639,7 +635,6 @@ void DmAuthManager::ShowStartAuthDialog() LOGE("ShowStartAuthDialog ptr is null"); } dmAbilityMgr_ = std::make_shared(); - ptr->StartAuth(dmAbilityMgr_); } @@ -647,32 +642,23 @@ void DmAuthManager::ShowStartAuthDialog() int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) { AbilityRole role = dmAbilityMgr_->GetAbilityRole(); - LOGI("GetAuthenticationParam:: role = %d", (int32_t)role); authParam.direction = (int32_t)role; - authParam.authType = AUTH_TYPE_PIN; // Currently, only Support PinCode, authType not save. + // Currently, only Support PinCode, authType not save. + authParam.authType = AUTH_TYPE_PIN; authParam.authToken = authResponseContext_->token; - LOGI("GetAuthenticationParam:: authToken : %s", authResponseContext_->token.c_str()); + if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { - //生成pincode + // 生成pincode authResponseContext_->code = GeneratePincode(); - LOGI("GeneratePincode:: code = %d", authResponseContext_->code); - LOGI("GetAuthenticationParam:: authParam packageName start"); authParam.packageName = authResponseContext_->targetPkgName; - LOGI("GetAuthenticationParam:: packageName : %s", authResponseContext_->targetPkgName.c_str()); - LOGI("GetAuthenticationParam:: authParam appName start"); authParam.appName = authResponseContext_->appName; - LOGI("GetAuthenticationParam:: appName : %s", authResponseContext_->appName.c_str()); - LOGI("GetAuthenticationParam:: authParam appDescription start"); authParam.appDescription = authResponseContext_->appDesc; - LOGI("GetAuthenticationParam:: appDescription : %s", authResponseContext_->appDesc.c_str()); - LOGI("GetAuthenticationParam:: authParam business start"); - authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION - LOGI("GetAuthenticationParam:: business : %d", BUSINESS_FA_MIRGRATION); - LOGI("GetAuthenticationParam:: authParam pincode start"); - authParam.pincode = authResponseContext_->code;//获取生成的pincode - LOGI("GetAuthenticationParam:: pincode : %d", authResponseContext_->code); - } - return SUCCESS; + // currently, only support BUSINESS_FA_MIRGRATION + authParam.business = BUSINESS_FA_MIRGRATION; + // 获取生成的pincode + authParam.pincode = authResponseContext_->code; + } + return DM_OK; } } } diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 5a882dd12..270ee7363 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -270,7 +270,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, cons pinCode = iter.second->GetPinCode(); } nlohmann::json jsonObj; - if (pinCode == FAIL) { + if (pinCode == DM_FAILED) { jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index e98e97ea7..b6649590b 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -14,10 +14,11 @@ */ #include "device_manager_service.h" + #include "device_manager_service_listener.h" -#include "dm_log.h" #include "dm_constants.h" #include "dm_device_info_manager.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { @@ -173,19 +174,15 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c return authMgr_->UnAuthenticateDevice(pkgName, deviceId); } -int32_t DeviceManagerService::VerifyAuthentication(const std::string &pkgName, const std::string &authParam) +int32_t DeviceManagerService::VerifyAuthentication(const std::string &authParam) { if (!intFlag_) { LOGE("VerifyAuthentication failed, singleton not init or init fail"); return DM_NOT_INIT; } - if (pkgName.empty()) { - LOGE("VerifyAuthentication failed, pkgName is empty"); - return DM_INPUT_PARA_EMPTY; - } - return authMgr_->VerifyAuthentication(pkgName, authParam); + return authMgr_->VerifyAuthentication(authParam); } int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam) diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 09735e653..6d9df3433 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -114,7 +114,7 @@ void DeviceManagerServiceListener::OnFaCall(std::string &pkgName, std::string &p pReq->SetPkgName(pkgName); pReq->SetJsonParam(paramJson); - ipcServerListener_.SendRequest(SERVER_DEVICEMANAGER_FA_NOTIFY, pReq, pRsp); + ipcServerListener_.SendRequest(SERVER_DEVICE_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 index 3eef5882b..d5436b5fe 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -18,7 +18,6 @@ #include "dm_constants.h" #include "dm_log.h" #include "device_manager_service.h" - #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_verify_auth_result_req.h" @@ -228,7 +227,7 @@ ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATION, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, ret); } -ON_IPC_SERVER_CMD(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo &req, IpcIo &reply) +ON_IPC_SERVER_CMD(SERVER_USER_AUTH_OPERATION, IpcIo &req, IpcIo &reply) { size_t len = 0; std::string packName = (const char *)IpcIoPopString(&req, &len); @@ -238,44 +237,7 @@ ON_IPC_SERVER_CMD(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, action); } -//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}; -// LOGE("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); -// DeviceManagerService::GetInstance().GetAuthenticationParam(packName, authParam); -// if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { -// IpcIoPushInt32(&reply, authParam.direction); -// IpcIoPushInt32(&reply, authParam.authType); -// IpcIoPushInt32(&reply, authParam.pinToken); -// LOGD("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_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, IpcIo& request, +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); @@ -286,7 +248,7 @@ ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBase return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo& request, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, IpcIo& request, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp index c93a8a9bd..02a41e89f 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -47,21 +47,20 @@ int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity * int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - LOGE("OnDeviceFound callback get listener in."); std::string pkgName = req->GetPkgName(); SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { LOGE("OnDeviceFound callback get listener failed."); return DM_FAILED; } - LOGE("OnDeviceFound callback get listener 1."); + 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; } - LOGE("OnDeviceFound callback get listener 2."); + if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) { LOGD("SendRequest failed cmdCode:%d", cmdCode); } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 3cb6fb98c..4ecea8170 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -13,22 +13,23 @@ * limitations under the License. */ +#include "ipc_cmd_register.h" + #include + +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_subscribe_info.h" +#include "dm_device_info.h" +#include "device_manager_service.h" #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_verify_auth_result_req.h" -#include "ipc_cmd_register.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_stub.h" -#include "dm_constants.h" -#include "dm_log.h" -#include "dm_subscribe_info.h" -#include "dm_device_info.h" -#include "device_manager_service.h" - namespace OHOS { namespace DistributedHardware { ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) @@ -181,7 +182,7 @@ ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::share return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) +ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) { LOGI("OnFaCallBack"); std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); @@ -199,7 +200,7 @@ ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBase return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; @@ -328,12 +329,13 @@ ON_IPC_CMD(UNAUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) { 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; -// } + int32_t result = DeviceManagerService::GetInstance().VerifyAuthentication(authPara); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } return DM_OK; } @@ -358,25 +360,16 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { std::string packName = data.ReadString(); DmAuthParam authParam; int32_t ret = DM_OK; - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:start"); ret = DeviceManagerService::GetInstance().GetFaParam(packName, authParam); - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:direction:%d", authParam.direction); - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:ret:%d", ret); - LOGI("service ON_IPC_CMD:: SERVER_GET_DMFA_INFO:pkgName:%s", packName.c_str()); - // if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || - // !reply.WriteString(authParam.authToken)) { - // LOGE("DeviceManagerStub::wirte client fail"); - // return DM_IPC_FLATTEN_OBJECT; - // } + 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)) { + !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; } @@ -398,51 +391,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { return DM_OK; } -//ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) -//{ -// std::string packName = data.ReadString(); -// DmAuthParam authParam; -// int32_t ret = DM_OK; -// LOGE("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); -// DeviceManagerService::GetInstance().GetAuthenticationParam(packName, authParam); -// if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { -// if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || -// !reply.WriteInt32(authParam.pinToken)) { -// LOGE("DeviceManagerStub::wirte client fail"); -// ret = DM_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)) { -// LOGE("write reply failed"); -// return DM_WRITE_FAILED; -// } -// -// if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { -// if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { -// LOGE("write appIcon failed"); -// return DM_WRITE_FAILED; -// } -// } -// -// if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { -// if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { -// LOGE("write appThumbnail failed"); -// return DM_WRITE_FAILED; -// } -// } -// -// return DM_OK; -//} - -ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(SERVER_USER_AUTH_OPERATION, MessageParcel &data, MessageParcel &reply) { std::string packageName = data.ReadString(); int32_t action = data.ReadInt32(); -- Gitee From 65949950c47e5e85988feeb868cf7d4cc29b414a Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Tue, 4 Jan 2022 21:37:08 +0800 Subject: [PATCH 062/110] =?UTF-8?q?=E7=BC=96=E8=AF=91=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- interfaces/inner_kits/native_cpp/include/device_manager.h | 2 +- .../inner_kits/native_cpp/include/device_manager_impl.h | 6 +++--- .../inner_kits/native_cpp/src/device_manager_impl.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 14152823e..279b0d581 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -46,7 +46,7 @@ public: 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 GetFaParam(const std::string &pkgName, const DmAuthParam &faParam) = 0; + virtual int32_t GetFaParam(const std::string &pkgName, DmAuthParam &faParam) = 0; virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) = 0; }; } // namespace DistributedHardware 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 bf6fa6d54..733c87da3 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -17,9 +17,9 @@ #define OHOS_DEVICE_MANAGER_IMPL_H #include "device_manager.h" + #include "ipc_client_proxy.h" #include "ipc_client_manager.h" -#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -44,8 +44,8 @@ public: 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 GetFaParam(std::string &pkgName, DmAuthParam &faParam) override; - virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) override; + virtual int32_t GetFaParam(const std::string &pkgName, DmAuthParam &faParam) override; + virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) override; private: DeviceManagerImpl() = default; ~DeviceManagerImpl() = default; 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 fff72e1b8..b77413725 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -404,7 +404,7 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons return DM_OK; } -int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, const DmAuthParam &dmFaParam) +int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &dmFaParam) { if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); -- Gitee From e532ae6f603c3fff5c61deb1989e2e650eb5b856 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Tue, 4 Jan 2022 21:39:22 +0800 Subject: [PATCH 063/110] =?UTF-8?q?=E5=90=88=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index f527b9212..f307e9e11 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -646,29 +646,19 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) // Currently, only Support PinCode, authType not save. authParam.authType = AUTH_TYPE_PIN; authParam.authToken = authResponseContext_->token; -<<<<<<< HEAD -======= ->>>>>>> c2c257dcb54b0ad37045c894f0c40b797b5dac36 if (role == AbilityRole::ABILITY_ROLE_PASSIVE) { // 生成pincode authResponseContext_->code = GeneratePincode(); authParam.packageName = authResponseContext_->targetPkgName; authParam.appName = authResponseContext_->appName; authParam.appDescription = authResponseContext_->appDesc; -<<<<<<< HEAD // currently, only support BUSINESS_FA_MIRGRATION authParam.business = BUSINESS_FA_MIRGRATION; // 获取生成的pincode authParam.pincode = authResponseContext_->code; } return DM_OK; -======= - authParam.business = BUSINESS_FA_MIRGRATION; // currently, only support BUSINESS_FA_MIRGRATION - authParam.pincode = authResponseContext_->code;//获取生成的pincode - } - return SUCCESS; ->>>>>>> c2c257dcb54b0ad37045c894f0c40b797b5dac36 } } } -- Gitee From 3ee69538776fbea5908f7d296f3be1c1ec8718d0 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Tue, 4 Jan 2022 22:50:28 +0800 Subject: [PATCH 064/110] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=AF=B9=E9=BD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/ipc/ipc_def.h | 2 +- .../ipc/model/ipc_get_local_device_info_rsp.h | 2 +- .../model/ipc_notify_discover_result_req.h | 2 -- .../ipc/model/ipc_notify_dmfa_result_req.h | 2 -- .../src/ipc/standard/ipc_cmd_parser.cpp | 22 +++++++++---------- 5 files changed, 13 insertions(+), 17 deletions(-) diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 5912acd64..1a5ab0055 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -49,7 +49,7 @@ enum IpcCmdID { SERVER_DISCOVER_FINISH, SERVER_AUTH_RESULT, SERVER_VERIFY_AUTH_RESULT, - SERVER_GET_DMFA_INFO, + SERVER_GET_DMFA_INFO, SERVER_USER_AUTH_OPERATION, SERVER_DEVICE_FA_NOTIFY, }; 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 index b2056ba64..2e86038e8 100644 --- a/common/include/ipc/model/ipc_get_local_device_info_rsp.h +++ b/common/include/ipc/model/ipc_get_local_device_info_rsp.h @@ -39,4 +39,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IPC_GET_TRUSTDEVICE_RSP_H \ No newline at end of file +#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_discover_result_req.h b/common/include/ipc/model/ipc_notify_discover_result_req.h index 708f4dddd..e1a3f7474 100644 --- a/common/include/ipc/model/ipc_notify_discover_result_req.h +++ b/common/include/ipc/model/ipc_notify_discover_result_req.h @@ -16,8 +16,6 @@ #ifndef OHOS_DM_IPC_NOTIFY_DISCOVER_RESULT_REQ_H #define OHOS_DM_IPC_NOTIFY_DISCOVER_RESULT_REQ_H -#include - #include "ipc_req.h" namespace OHOS { 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 a222878e3..a517d2f98 100644 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -16,8 +16,6 @@ #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 { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 6a260915f..d479ff1fc 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -356,9 +356,9 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) { } ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { - std::string packName = data.ReadString(); - DmAuthParam authParam; - int32_t ret = DM_OK; + 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(); @@ -368,21 +368,21 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { !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; + 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 (!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; + if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { + LOGE("write appThumbnail failed"); + return DM_IPC_FLATTEN_OBJECT; } } -- Gitee From 2a4edf7c9e979353f7b1d2900b8bb4afc03b8946 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Tue, 4 Jan 2022 22:55:20 +0800 Subject: [PATCH 065/110] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=AF=B9=E9=BD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/ipc/standard/ipc_cmd_parser.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index d479ff1fc..b01d7907a 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -361,32 +361,32 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { int32_t ret = DM_OK; ret = DeviceManagerService::GetInstance().GetFaParam(packName, authParam); int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); - int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); + int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); - if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + 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 (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 (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; + return DM_OK; } ON_IPC_CMD(SERVER_USER_AUTH_OPERATION, MessageParcel &data, MessageParcel &reply) -- Gitee From 76e68f11cebf9ca78d1098e5f7589a7811c38c93 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Wed, 5 Jan 2022 16:28:06 +0800 Subject: [PATCH 066/110] =?UTF-8?q?=E6=B5=81=E7=A8=8B=E4=BF=AE=E6=94=B9/?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E8=A7=84=E8=8C=83=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 2 + ext/pin_auth/include/pin_auth.h | 3 +- .../ability/standard/dm_ability_manager.cpp | 8 +- ext/pin_auth/src/pin_auth.cpp | 27 ++++ .../native_cpp/include/device_manager.h | 7 +- .../native_cpp/include/device_manager_impl.h | 3 + .../include/notify/device_manager_notify.h | 2 + .../native_cpp/src/device_manager_impl.cpp | 30 ++++ .../src/notify/device_manager_notify.cpp | 12 ++ .../kits/js/src/native_devicemanager_js.cpp | 31 ++++ .../include/authentication/authentication.h | 1 + .../include/authentication/dm_auth_manager.h | 6 +- .../dependency/hichain/hichain_connector.h | 2 +- .../devicestate/dm_device_state_manager.h | 1 + .../ability/standard/dm_ability_manager.cpp | 2 +- .../authentication/auth_response_state.cpp | 3 +- .../src/authentication/dm_auth_manager.cpp | 134 +++++++++++------- .../dependency/hichain/hichain_connector.cpp | 6 +- .../devicestate/dm_device_state_manager.cpp | 20 ++- .../src/discovery/dm_discovery_manager.cpp | 12 +- 20 files changed, 234 insertions(+), 78 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index abdefb7d8..6a476e14d 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -144,6 +144,8 @@ namespace DistributedHardware { 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 diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h index a15e8390e..a60ac833e 100644 --- a/ext/pin_auth/include/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.h @@ -31,8 +31,9 @@ public: ~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 diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp index 40633518d..231fb21c6 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -28,8 +28,8 @@ 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"; +const std::string bundleUiName = "com.ohos.devicemanagerui"; +const std::string abilityUiName = "com.ohos.devicemanagerui.MainAbility"; } AbilityRole DmAbilityManager::GetAbilityRole() @@ -45,11 +45,11 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) std::string deviceId = localDeviceId; mStatus_ = ABILITY_STATUS_START; AAFwk::Want want; - AppExecFwk::ElementName element(deviceId, bundleName, abilityName); + AppExecFwk::ElementName element(deviceId, bundleUiName, abilityUiName); want.SetElement(element); AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); - if (result != DM_OK) { + if (result != OHOS::ERR_OK) { LOGE("Start Ability faild"); mStatus_ = ABILITY_STATUS_FAILED; return mStatus_; diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 74dc69a54..41f676fb7 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -19,6 +19,7 @@ #include "dm_constants.h" #include "dm_log.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { @@ -39,9 +40,35 @@ int32_t PinAuth::ShowAuthInfo() 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(TAG_TOKEN)){ + LOGE("err json string, first time"); + return DM_FAILED; + } + + int32_t inputPinCode = jsonObject[PIN_CODE_KEY]; + std::string inputPinToken = jsonObject[TAG_TOKEN]; + if (code == inputPinCode && 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; } diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 279b0d581..afaccffe4 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -46,8 +46,11 @@ public: 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 GetFaParam(const std::string &pkgName, DmAuthParam &faParam) = 0; - virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) = 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(std::string &pkgName, DmAuthParam &faParam) = 0; + virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) = 0; }; } // namespace DistributedHardware } // namespace OHOS 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 733c87da3..6c8d7b354 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -44,6 +44,9 @@ public: 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; private: 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 fc541f55b..05ef75b32 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 @@ -46,6 +46,8 @@ public: 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(const std::string &pkgName, const DmDeviceInfo &deviceInfo); 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 b77413725..931a14048 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -372,9 +372,34 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons 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; @@ -401,11 +426,13 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons } DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); + LOGI("VerifyAuthentication completed , pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &dmFaParam) { + LOGI("DeviceManager::GetFaParam start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INVALID_VALUE; @@ -420,11 +447,13 @@ int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &d return DM_IPC_SEND_REQUEST_FAILED; } dmFaParam = rsp->GetDmAuthParam(); + LOGI("GetFaParam completed , pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action) { + LOGI("DeviceManager::SetUserOperation start , pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INVALID_VALUE; @@ -443,6 +472,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t LOGE("CheckAuthentication Failed with ret %d", ret); return ret; } + LOGI("SetUserOperation completed , pkgName: %s", pkgName.c_str()); return DM_OK; } } // namespace DistributedHardware 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 cc07e51a4..bb10ad302 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 @@ -114,6 +114,18 @@ void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::stri verifyAuthCallback_.erase(pkgName); } +void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName,std::shared_ptr callback) +{ + std::lock_guard autoLock(lock_); + dmFaCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + dmFaCallback_.erase(pkgName); +} + void DeviceManagerNotify::OnRemoteDied() { LOGW("DeviceManager : OnRemoteDied"); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 18f5edc25..f9d41b9e6 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -38,6 +38,7 @@ const std::string DM_NAPI_EVENT_DEVICE_FOUND = "deviceFound"; const std::string DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL = "discoveryFail"; const std::string DM_NAPI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; 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; @@ -55,6 +56,7 @@ std::map> g_deviceStateC std::map> g_DiscoveryCallbackMap; std::map> g_authCallbackMap; std::map> g_verifyAuthCallbackMap; +std::map> g_dmfaCallbackMap; } napi_ref DeviceManagerNapi::sConstructor_ = nullptr; @@ -714,6 +716,20 @@ void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &e DiscoveryCallback->IncreaseRefCount(); return; } + + if (eventType == DM_NAPI_EVENT_DMFA_CALLBACK) { + auto iter = g_dmfaCallbackMap.find(bundleName); + if (iter == g_dmfaCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName, callback); + if (ret != 0) { + LOGE("RegisterDeviceManagerFaCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_dmfaCallbackMap[bundleName] = callback; + } + return; + } } void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string &eventType) @@ -747,6 +763,21 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & } return; } + + if (eventType == DM_NAPI_EVENT_DMFA_CALLBACK) { + auto iter = g_dmfaCallbackMap.find(bundleName); + if (iter == g_dmfaCallbackMap.end()) { + LOGE("cannot find dmFaCallback for bunderName %s", bundleName.c_str()); + return; + } + int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_dmfaCallbackMap.erase(bundleName); + return; + } } napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_callback_info info) diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h index 5ebce1f20..992eb4111 100644 --- a/services/devicemanagerservice/include/authentication/authentication.h +++ b/services/devicemanagerservice/include/authentication/authentication.h @@ -25,6 +25,7 @@ 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); diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 2260f808c..fce1e81e8 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -139,7 +139,7 @@ public: void SendAuthRequest(const int32_t &sessionId); void StartAuthProcess(const int32_t &authType); void StartRespAuthProcess(); - void CreateGroup(int64_t requestId, const std::string &groupName); + void CreateGroup(); void AddMember(const std::string &deviceId); std::string GetConnectAddr(std::string deviceId); void JoinNetwork(); @@ -148,6 +148,7 @@ public: 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(); @@ -168,8 +169,7 @@ private: std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; std::map> timerMap_; - std::shared_ptr data_; - std::shared_ptr dmAbilityMgr_; + std::shared_ptr dmAbilityMgr_ ; bool isCryptoSupport_ = false; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index a2f05503b..319887edc 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -56,7 +56,7 @@ public: int32_t AddMember(std::string deviceId, std::string &connectInfo); int32_t DelMemberFromGroup(std::string groupId, std::string deviceId); void DeleteGroup(std::string &groupId); - int32_t IsDevicesInGroup(std::string hostDevice, std::string peerDevice); + bool IsDevicesInGroup(std::string hostDevice, std::string peerDevice); void GetRelatedGroups(std::string DeviceId, std::vector &groupList); private: int64_t GenRequestId(); diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 7b6ab6f8c..670b5036c 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -36,6 +36,7 @@ private: std::shared_ptr softbusConnector_; std::shared_ptr adapterMgr_; std::shared_ptr listener_; + std::map deviceStateMap_; }; } // 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 index 991ab1346..30ea81aa0 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -49,7 +49,7 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) want.SetElement(element); AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); - if (result != DM_OK) { + if (result != OHOS::ERR_OK) { LOGE("Start Ability faild"); mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; return mStatus_; diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp index e3c22de6c..ffc3f7dd0 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -120,13 +120,12 @@ void AuthResponseGroupState::Enter() // //1.创建群组, // authManagerPtr_->GetHiChainConnector()->CreateGroup(); LOGI("AuthResponse:: AuthResponseGroupState Enter"); - std::string groupName = "1234567890"; std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } - stateAuthManager->CreateGroup(context_->requestId, groupName); + stateAuthManager->CreateGroup(); } int32_t AuthResponseShowState::GetStateType() diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index f307e9e11..dd10b976c 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -24,6 +24,7 @@ #include "dm_constants.h" #include "dm_log.h" #include "dm_random.h" +#include "parameter.h" namespace OHOS { namespace DistributedHardware { @@ -43,6 +44,7 @@ namespace{ int32_t INPUT_TIMEOUT = 60; int32_t ADD_TIMEOUT = 10; int32_t CANCEL_PICODE_DISPLAY = 1; + int32_t DEVICE_ID_HALF = 2; } static void TimeOut(void *data){ @@ -60,10 +62,8 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, { LOGI("DmAuthManager constructor"); //TODO: load library so for different auth type - data_ = std::shared_ptr(this); - std::string pkgName = "com.ohos.devicemangagerdemo"; - sessionSession_->RegisterSessionCallback(pkgName, data_); - // hiChainConnector_ = std::make_shared(); + hiChainConnector_ = std::make_shared(); + sessionSession_->RegisterSessionCallback(DM_PKG_NAME, shared_from_this()); } DmAuthManager::~DmAuthManager() @@ -89,11 +89,18 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au LOGE("DmAuthManager::AuthenticateDevice is response authentication."); return DM_AUTH_BUSINESS_BUSY; } + if (extra.empty()){ + LOGE("AuthenticateDevice failed, extra is empty"); + 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"); + return DM_INPUT_PARA_EMPTY; + } sessionSession_->UnRegisterSessionCallback(pkgName); - sessionSession_->RegisterSessionCallback(pkgName, data_); - // hiChainConnector_->RegisterHiChainCallback(pkgName, std::shared_ptr(this)); + sessionSession_->RegisterSessionCallback(pkgName, shared_from_this()); - authMessageProcessor_ = std::make_shared(data_); + authMessageProcessor_ = std::make_shared(shared_from_this()); authRequestContext_ = std::make_shared(); authRequestContext_->authType = authType; authRequestContext_->deviceId = deviceId; @@ -115,9 +122,9 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au authRequestContext_->appIcon = jsonObject[APP_ICON_KEY]; } } - authRequestContext_->token = "123456"; + authRequestContext_->token = GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN); authRequestState_ = std::shared_ptr(new AuthRequestInitState()); - authRequestState_->SetAuthManager(data_); + authRequestState_->SetAuthManager(shared_from_this()); authRequestState_->SetAuthContext(authRequestContext_); authRequestState_->Enter(); std::shared_ptr authenticateStartTimer = std::make_shared(AUTHENTICATE_TIMEOUT_TASK); @@ -165,28 +172,30 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) { LOGI("DmAuthManager::VerifyAuthentication"); timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - 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)){ - LOGE("err json string, first time"); - return DM_FAILED; + + DmConfigManager& temp = DmConfigManager::GetInstance(); + std::string soName = "libdevicemanagerext_pin_auth.z.so"; + std::shared_ptr ptr = temp.GetAuthAdapter(soName); + if (ptr == nullptr) { + LOGE("VerifyAuthentication ptr is null"); } - int32_t pinCode = jsonObject[PIN_CODE_KEY]; - int32_t times = 0; - if (pinCode == authResponseContext_->code && authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT){ + + int32_t ret = ptr->VerifyAuthentication(authRequestContext_->token, authResponseContext_->code, authParam); + + switch (ret) + { + case DM_OK: authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); - }else if (pinCode != authResponseContext_->code && times < 3) { - times++; - //TODO input again - }else { + break; + case DM_AUTH_INPUT_FAILED: + //todo Prompt for input pin code error + //break; + default: + CancelDisplay(); authResponseContext_->reply = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = DM_AUTH_INPUT_FAILED; authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); - CancelDisplay(); - return DM_FAILED; + break; } LOGI("DmAuthManager::VerifyAuthentication complete"); @@ -198,20 +207,24 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI LOGI("DmAuthManager::OnSessionOpened sessionId=%d result=%d", sessionId, result); if (sessionSide == AUTH_SESSION_SIDE_SERVER) { if (authResponseState_ == nullptr) { - authMessageProcessor_ = std::make_shared(data_); + authMessageProcessor_ = std::make_shared(shared_from_this()); authResponseState_ = std::shared_ptr(new AuthResponseInitState()); - authResponseState_->SetAuthManager(data_); + authResponseState_->SetAuthManager(shared_from_this()); authResponseState_->Enter(); - hiChainConnector_ = std::make_shared(); - hiChainConnector_->RegisterHiChainCallback(pkgName, data_); + hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this()); authResponseContext_ = std::make_shared(); } else { - return; + 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_ = std::make_shared(); - hiChainConnector_->RegisterHiChainCallback(pkgName, data_); + hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this()); authRequestContext_ ->sessionId = sessionId; authRequestState_->SetAuthContext(authRequestContext_); authMessageProcessor_->SetRequestContext(authRequestContext_); @@ -221,7 +234,6 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType()); authResponseContext_ = std::make_shared(); authResponseContext_->reply = AuthState::AUTH_REQUEST_INIT; - authRequestContext_->reason = DM_AUTH_STATE_FAILED; authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } } @@ -255,6 +267,11 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); } else { LOGE("Device manager auth state error"); + 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); + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); } break; case MSG_TYPE_REQ_AUTH: @@ -263,6 +280,11 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseConfirmState())); } else { LOGE("Device manager auth state error"); + authResponseContext_->reply = AuthState::AUTH_RESPONSE_NEGOTIATE; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); } break; case MSG_TYPE_RESP_AUTH: @@ -284,9 +306,11 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId } break; case MSG_TYPE_REQ_AUTH_TERMINATE: - if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { + if (authResponseState_ == nullptr && + authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); - } else { + } else if (authRequestState_ == nullptr && + authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { LOGE("Device manager auth state error"); } break; @@ -311,11 +335,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseShowState())); - // int32_t pinCode = 123456; - // authResponseContext_->code = pinCode; authResponseContext_->groupId = groupId; - authResponseContext_->groupName = "1234567890"; - authResponseContext_->reply = 0; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); @@ -379,8 +399,8 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) DmDeviceInfo localDevice; softbusConnector_->GetLocalDeviceInfo(localDevice); authRequestContext_->localDeviceId = localDevice.deviceId; - int32_t ret = hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); - if (ret != DM_OK){ + bool ret = hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); + if (ret != true){ LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE; authRequestContext_->reason = DM_AUTH_DEVICE_AUTHED; @@ -397,8 +417,8 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) void DmAuthManager::RespNegotiate(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); - int32_t ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); - if (ret != DM_OK){ + bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); + if (ret != true){ LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = DM_AUTH_PEER_REJECT; return; @@ -473,10 +493,12 @@ void DmAuthManager::StartRespAuthProcess() } } -void DmAuthManager::CreateGroup(int64_t requestId, const std::string &groupName) +void DmAuthManager::CreateGroup() { LOGI("DmAuthManager:: CreateGroup"); - hiChainConnector_->CreateGroup(requestId, groupName); + 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) @@ -521,16 +543,18 @@ void DmAuthManager::AuthenticateFinish() LOGI("DmAuthManager::AuthenticateFinish start"); if (authRequestState_ == nullptr){ if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW){ - //todo close show pin dialog + CancelDisplay(); } authResponseContext_ = nullptr; authResponseState_ = nullptr; authMessageProcessor_ = nullptr; }else if(authRequestState_ != nullptr){ std::string flag = ""; - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + 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 (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN){ listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, DM_AUTH_INPUT_FAILED, flag); @@ -576,6 +600,16 @@ 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 = authRequestContext_->targetPkgName + authRequestContext_->hostPkgName + + sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); + return groupName; +} + void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) { LOGI("DmAuthManager::GetIsCryptoSupport start"); diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 270ee7363..610d82495 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -355,7 +355,7 @@ void HiChainConnector::GetSyncGroupList(std::vector &groupList, std:: } } -int32_t HiChainConnector::IsDevicesInGroup(std::string hostDevice, std::string peerDevice) +bool HiChainConnector::IsDevicesInGroup(std::string hostDevice, std::string peerDevice) { LOGE("HiChainConnector::IsDevicesInGroup"); std::vector hostGroupInfoList; @@ -366,11 +366,11 @@ int32_t HiChainConnector::IsDevicesInGroup(std::string hostDevice, std::string p for (auto &peerGroupInfo : peerGroupInfoList) { if (hostGroupInfo.groupId == peerGroupInfo.groupId && hostGroupInfo.groupName == peerGroupInfo.groupName){ LOGE("these are authenticated"); - return DM_FAILED; + return false; } } } - return DM_OK; + return true; } bool HiChainConnector::IsGroupInfoInvalid(GroupInfo &group) diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 54f97dc11..00e89e74a 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -24,7 +24,7 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof std::shared_ptr listener) : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmDeviceStateManager constructor"); - softbusConnector_->RegisterSoftbusStateCallback("", std::shared_ptr(this)); + softbusConnector_->RegisterSoftbusStateCallback(DM_PKG_NAME, std::shared_ptr(this)); } DmDeviceStateManager::~DmDeviceStateManager() @@ -33,7 +33,8 @@ DmDeviceStateManager::~DmDeviceStateManager() softbusConnector_->UnRegisterSoftbusStateCallback(""); } -void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) { +void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) +{ DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); if (profileAdapter == nullptr){ @@ -42,10 +43,12 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe } DmDeviceState state = DEVICE_STATE_ONLINE; // profileAdapter->RegisterProfileListener(); + deviceStateMap_[info.deviceId] = DEVICE_STATE_ONLINE; listener_->OnDeviceStateChange(pkgName, state, info); } -void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) { +void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) +{ DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); if (profileAdapter == nullptr){ @@ -54,15 +57,18 @@ void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmD } DmDeviceState state = DEVICE_STATE_OFFLINE; // profileAdapter->UnRegisterProfileListener(); + deviceStateMap_[info.deviceId] = DEVICE_STATE_OFFLINE; listener_->OnDeviceStateChange(pkgName, state, info); } -void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &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) { - +void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info) +{ + deviceStateMap_[info.deviceId] = DEVICE_INFO_READY; } } } diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 6dfa1f368..9f9c10c4a 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -74,7 +74,8 @@ int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint return softbusConnector_->StopDiscovery(subscribeId); } -void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) { +void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) +{ LOGI("DmDiscoveryManager::OnDeviceFound deviceId=%s", GetAnonyString(info.deviceId).c_str()); // std::string pkgName = discoveryQueue_.front(); auto iter = discoveryContextMap_.find(pkgName); @@ -86,7 +87,8 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDevic listener_->OnDeviceFound(pkgName, iter->second.subscribeId, info); } -void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) { +void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) +{ LOGI("DmDiscoveryManager::OnDiscoveryFailed subscribeId=%d reason=%d", subscribeId, failedReason); // std::string pkgName = discoveryQueue_.front(); // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); @@ -94,14 +96,16 @@ void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t s listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); } -void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) { +void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +{ LOGI("DmDiscoveryManager::OnDiscoverySuccess subscribeId=%d", subscribeId); // std::string pkgName = discoveryQueue_.front(); discoveryContextMap_[pkgName].subscribeId = subscribeId; listener_->OnDiscoverySuccess(pkgName, subscribeId); } -void DmDiscoveryManager::HandleDiscoveryTimeout() { +void DmDiscoveryManager::HandleDiscoveryTimeout() +{ LOGI("DmDiscoveryManager::HandleDiscoveryTimeout"); StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); -- Gitee From eab2f3f55e031f91fcb04b5c41d842d41e44b023 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Wed, 5 Jan 2022 21:29:41 +0800 Subject: [PATCH 067/110] =?UTF-8?q?uuid/=E4=BB=A3=E7=A0=81=E8=A7=84?= =?UTF-8?q?=E8=8C=83=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/ipc/ipc_def.h | 2 + .../ipc/model/ipc_get_info_by_network_req.h | 40 ++++++++++++ .../ipc/model/ipc_get_info_by_network_rsp.h | 52 +++++++++++++++ ext/pin_auth/src/pin_auth.cpp | 3 +- .../native_cpp/include/device_manager.h | 6 +- .../native_cpp/include/device_manager_impl.h | 4 ++ .../native_cpp/src/device_manager_impl.cpp | 64 +++++++++++++++++-- .../src/ipc/standard/ipc_cmd_parser.cpp | 46 +++++++++++++ .../src/notify/device_manager_notify.cpp | 8 +++ .../dependency/softbus/softbus_connector.h | 2 + .../include/device_manager_service.h | 2 + .../dependency/softbus/softbus_connector.cpp | 28 ++++++++ .../src/device_manager_service.cpp | 32 ++++++++++ .../src/discovery/dm_discovery_manager.cpp | 14 ++-- .../src/ipc/standard/ipc_cmd_parser.cpp | 34 ++++++++++ 15 files changed, 324 insertions(+), 13 deletions(-) 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 diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index 1a5ab0055..6aa095ec0 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -39,6 +39,8 @@ enum IpcCmdID { 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, 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..eaa0969b7 --- /dev/null +++ b/common/include/ipc/model/ipc_get_info_by_network_req.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_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..8557e371b --- /dev/null +++ b/common/include/ipc/model/ipc_get_info_by_network_rsp.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_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/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 41f676fb7..c5898712c 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -17,9 +17,10 @@ #include +#include "nlohmann/json.hpp" + #include "dm_constants.h" #include "dm_log.h" -#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index afaccffe4..5456cd5d2 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -49,8 +49,10 @@ public: 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(std::string &pkgName, DmAuthParam &faParam) = 0; - virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) = 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 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 6c8d7b354..07d646745 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -49,6 +49,10 @@ public: 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; 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 931a14048..38a99772d 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -36,6 +36,8 @@ #include "ipc_verify_authenticate_req.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" +#include "ipc_get_info_by_network_req.h" +#include "ipc_get_info_by_network_rsp.h" using namespace OHOS::AppExecFwk; using namespace OHOS::AppExecFwk::Constants; @@ -399,7 +401,7 @@ int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string & 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()); + LOGI("DeviceManager::VerifyAuthentication start, pkgName: %s", pkgName.c_str()); if (!isSystemAppCalling()) { LOGI("the caller is not a system app"); return DM_NOT_SYSTEM_APP; @@ -426,13 +428,13 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons } DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); - LOGI("VerifyAuthentication completed , pkgName: %s", pkgName.c_str()); + LOGI("VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &dmFaParam) { - LOGI("DeviceManager::GetFaParam start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::GetFaParam start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INVALID_VALUE; @@ -447,13 +449,13 @@ int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &d return DM_IPC_SEND_REQUEST_FAILED; } dmFaParam = rsp->GetDmAuthParam(); - LOGI("GetFaParam completed , pkgName: %s", pkgName.c_str()); + LOGI("GetFaParam completed, pkgName: %s", pkgName.c_str()); return DM_OK; } int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action) { - LOGI("DeviceManager::SetUserOperation start , pkgName: %s", pkgName.c_str()); + LOGI("DeviceManager::SetUserOperation start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); return DM_INVALID_VALUE; @@ -472,7 +474,57 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t LOGE("CheckAuthentication Failed with ret %d", ret); return ret; } - LOGI("SetUserOperation completed , pkgName: %s", pkgName.c_str()); + LOGI("SetUserOperation completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) +{ + if (pkgName.empty()) { + LOGE("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::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) +{ + 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_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 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 c9c1ba20a..2be1f866f 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 @@ -35,6 +35,8 @@ #include "ipc_get_local_device_info_rsp.h" #include "ipc_get_dmfaparam_rsp.h" #include "ipc_set_useroperation_req.h" +#include "ipc_get_info_by_network_req.h" +#include "ipc_get_info_by_network_rsp.h" namespace OHOS { namespace DistributedHardware { @@ -137,6 +139,50 @@ ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, MessageParcel &reply, std::shared_pt 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) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); 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 bb10ad302..8f7a0d08e 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 @@ -117,12 +117,20 @@ void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::stri void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName,std::shared_ptr callback) { std::lock_guard autoLock(lock_); + if (dmFaCallback_.count(pkgName) == 0) { + LOGE("DeviceManager RegisterDeviceManagerFaCallback not register"); + return; + } dmFaCallback_[pkgName] = callback; } 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); } diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index 0a27b0bcd..2b53cfb8f 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -46,6 +46,8 @@ public: static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); static bool IsDeviceOnLine(const std::string &deviceId); static int32_t GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info, int32_t infoLen); + static int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); + static int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); public: SoftbusConnector(); ~SoftbusConnector(); diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index dca3a4836..ce138c593 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -36,6 +36,8 @@ 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); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 228983edf..b8f2909dd 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -268,6 +268,34 @@ int32_t SoftbusConnector::GetNodeKeyInfoByNetworkId(const char *networkId, NodeD 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; diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 9085d5579..cf6127041 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -109,6 +109,38 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) 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_) { diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 9f9c10c4a..093611952 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -23,6 +23,7 @@ namespace DistributedHardware { namespace{ std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout"; int32_t DISCOVERY_TIMEOUT = 120; + int32_t SESSION_CANCEL_TIMEOUT = 0; } static void TimeOut(void *data){ LOGE("time out "); @@ -61,16 +62,21 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId}; discoveryContextMap_.emplace(pkgName, context); softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(this)); - std::shared_ptr discoveryTimer_ = std::make_shared(DISCOVERY_TIMEOUT_TASK); + 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) { - discoveryQueue_.pop(); - discoveryContextMap_.erase(pkgName); - softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); + if (!discoveryQueue_.empty()) { + discoveryQueue_.pop(); + } + if (!discoveryContextMap_.empty()) { + discoveryContextMap_.erase(pkgName); + softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); + } + discoveryTimer_->Stop(SESSION_CANCEL_TIMEOUT); return softbusConnector_->StopDiscovery(subscribeId); } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index b01d7907a..ddb859ee1 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -355,6 +355,40 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) { 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; -- Gitee From 452ac7676a8d8cbb8e9535bd58a6c0fd5e9f24e5 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Wed, 5 Jan 2022 23:18:53 +0800 Subject: [PATCH 068/110] =?UTF-8?q?so=E6=8E=A5=E5=8F=A3=E7=9A=84=E9=80=82?= =?UTF-8?q?=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/devicemanagerservice/BUILD.gn | 4 +- .../include/adapter/dm_adapter_manager.h | 23 +- .../include/adapter/profile_adapter.h | 2 + .../include/config_manager.h | 85 ----- .../deviceinfo/dm_device_info_manager.h | 1 - .../adapter/standard/dm_adapter_manager.cpp | 28 +- .../src/authentication/dm_auth_manager.cpp | 7 +- .../src/config_manager.cpp | 332 ------------------ .../src/deviceinfo/dm_device_info_manager.cpp | 3 +- .../devicestate/dm_device_state_manager.cpp | 6 +- 10 files changed, 32 insertions(+), 459 deletions(-) delete mode 100644 services/devicemanagerservice/include/config_manager.h delete mode 100644 services/devicemanagerservice/src/config_manager.cpp diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 8430f2d7b..ffd61a01c 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -110,6 +110,7 @@ if (defined(ohos_lite)) { ohos_shared_library("devicemanagerservice") { include_dirs = [ "include", + "include/config", "include/adapter", "include/authentication", "include/ability", @@ -132,7 +133,6 @@ if (defined(ohos_lite)) { "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/ipc", "${innerkits_path}/native_cpp/include/ipc/standard", - "${ext_path}/config", "//utils/native/base/include", "//utils/system/safwk/native/include", "//base/notification/ces_standard/frameworks/core/include", @@ -144,7 +144,7 @@ if (defined(ohos_lite)) { ] sources = [ - "src/config_manager.cpp", + "src/config/config_manager.cpp", "src/device_manager_service.cpp", "src/ability/standard/dm_ability_manager.cpp", "src/device_manager_service_listener.cpp", diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index 8c0813ddc..071c73fbd 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -18,30 +18,19 @@ #include +#include "crypto_adapter.h" #include "decision_adapter.h" #include "profile_adapter.h" -#include "crypto_adapter.h" +#include "single_instance.h" namespace OHOS { namespace DistributedHardware { class DmAdapterManager { +DECLARE_SINGLE_INSTANCE(DmAdapterManager); public: - static DmAdapterManager& GetInstance(); -public: - std::shared_ptr GetDecisionAdapter(); - std::shared_ptr GetProfileAdapter(); - std::shared_ptr GetCryptoAdapter(); -private: - DmAdapterManager(); - ~DmAdapterManager(); - DmAdapterManager(const DmAdapterManager&) = delete; - DmAdapterManager& operator= (const DmAdapterManager&) = delete; - DmAdapterManager(DmAdapterManager&&) = delete; - DmAdapterManager& operator= (DmAdapterManager&&) = delete; -private: - std::shared_ptr decisionAdapterPtr_; - std::shared_ptr profileAdapterPtr_; - std::shared_ptr cryptoAdapterPtr_; + 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 diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index d53d3c504..25800f63a 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -16,6 +16,8 @@ #ifndef OHOS_DM_PROFILE_ADAPTER_H #define OHOS_DM_PROFILE_ADAPTER_H +#include + namespace OHOS { namespace DistributedHardware { class IProfileAdapter { diff --git a/services/devicemanagerservice/include/config_manager.h b/services/devicemanagerservice/include/config_manager.h deleted file mode 100644 index 17288aa3b..000000000 --- a/services/devicemanagerservice/include/config_manager.h +++ /dev/null @@ -1,85 +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_OHOS_DM_CONFIG_MANAGER_H -#define OHOS_OHOS_DM_CONFIG_MANAGER_H - -#include -#include -#include -#include -#include -#include - -#include "decision_adapter.h" -#include "profile_adapter.h" -#include "crypto_adapter.h" -#include "authentication.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 { - std::string name; - std::string type; - std::string version; - std::string authType; - std::string funcName; - std::string soName; - std::string soPath; -} AuthSoLoadInfo; - -class DmConfigManager final { -public: - static DmConfigManager& GetInstance(); -public: - ~DmConfigManager(); - void GetAllAuthType (std::vector& allAuthType); - const AdapterSoLoadInfo* GetAdapterSoLoadInfo(const std::string& soName); - const AuthSoLoadInfo* GetAuthSoLoadInfo(const std::string& soName); - std::shared_ptr GetDecisionAdapter(const std::string& soName); - std::shared_ptr GetProfileAdapter(const std::string& soName); - std::shared_ptr GetCryptoAdapter(const std::string& soName); - std::shared_ptr GetAuthAdapter(const std::string& soName); -private: - DmConfigManager(); - DmConfigManager(const DmConfigManager&) = delete; - DmConfigManager& operator= (const DmConfigManager&) = delete; - DmConfigManager(DmConfigManager&&) = delete; - DmConfigManager& operator= (DmConfigManager&&) = delete; -private: - std::mutex authAdapterMutex_; - std::mutex cryptoAdpaterMutex_; - std::mutex decisionAdpaterMutex_; - std::mutex profileAdpaterMutex_; - std::map soAdapterLoadInfo_; - std::map soAuthLoadInfo_; - std::map> decisionAdapterPtr_; - std::map> profileAdapterPtr_; - std::map> cryptoAdapterPtr_; - std::map> authAdapterPtr_; -}; -} // namespace DistributedHardware -} // namespace OHOS - -#endif // OHOS_OHOS_DM_CONFIG_MANAGER_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h index 4a111f350..9a55f83a7 100644 --- a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h @@ -32,7 +32,6 @@ public: int32_t GetLocalDeviceInfo(DmDeviceInfo &info); private: std::shared_ptr softbusConnector_; - std::shared_ptr adapterMgr_; }; } // 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 index 83381debe..112f34410 100644 --- a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp @@ -15,9 +15,10 @@ #include +#include "config_manager.h" #include "dm_adapter_manager.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { @@ -27,29 +28,22 @@ DmAdapterManager& DmAdapterManager::GetInstance() return instance; } -DmAdapterManager::DmAdapterManager() -{ - LOGI("DmAdapterManager constructor"); -} - -DmAdapterManager::~DmAdapterManager() -{ - LOGI("DmAdapterManager destructor"); -} - -std::shared_ptr DmAdapterManager::GetDecisionAdapter() +std::shared_ptr DmAdapterManager::GetDecisionAdapter(const std::string& soName) { - return nullptr; + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + return dmConfigManager.GetDecisionAdapter(soName); } -std::shared_ptr DmAdapterManager::GetProfileAdapter() +std::shared_ptr DmAdapterManager::GetProfileAdapter(const std::string& soName) { - return nullptr; + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + return dmConfigManager.GetProfileAdapter(soName); } -std::shared_ptr DmAdapterManager::GetCryptoAdapter() +std::shared_ptr DmAdapterManager::GetCryptoAdapter(const std::string& soName) { - return nullptr; + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + return dmConfigManager.GetCryptoAdapter(soName); } } } diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index f307e9e11..a10eda9bf 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -60,6 +60,9 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, { LOGI("DmAuthManager constructor"); //TODO: load library so for different auth type + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + dmConfigManager.GetAuthAdapter(authenticationMap_); + data_ = std::shared_ptr(this); std::string pkgName = "com.ohos.devicemangagerdemo"; sessionSession_->RegisterSessionCallback(pkgName, data_); @@ -628,14 +631,14 @@ void DmAuthManager::ShowAuthInfoDialog() void DmAuthManager::ShowStartAuthDialog() { - DmConfigManager& temp = DmConfigManager::GetInstance(); + /*DmConfigManager& temp = DmConfigManager::GetInstance(); std::string soName = "libdevicemanagerext_pin_auth.z.so"; std::shared_ptr ptr = temp.GetAuthAdapter(soName); if (ptr == nullptr) { LOGE("ShowStartAuthDialog ptr is null"); } dmAbilityMgr_ = std::make_shared(); - ptr->StartAuth(dmAbilityMgr_); + ptr->StartAuth(dmAbilityMgr_);*/ } diff --git a/services/devicemanagerservice/src/config_manager.cpp b/services/devicemanagerservice/src/config_manager.cpp deleted file mode 100644 index a84bdc748..000000000 --- a/services/devicemanagerservice/src/config_manager.cpp +++ /dev/null @@ -1,332 +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 "config_manager.h" - -#include - -#include "dm_log.h" -#include "json_config.h" -#include "dm_constants.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 || - soLoadInfo[i].authType.size() == 0) { - LOGE("adapter json config string exist invalid members"); - continue; - } - soAuthLoadInfo_[soLoadInfo[i].soName] = 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: %s", soLoadInfo[i].authType.c_str()); - } - } 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"); -} - -void DmConfigManager::GetAllAuthType (std::vector& allAuthType) -{ - std::set authType; - for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) { - if ((iter->second).authType == AUTH_LOAD_JSON_KEY) { - authType.insert((iter->second).authType); - } - } - - allAuthType.clear(); - for (auto iter = authType.begin(); iter != authType.end(); iter++) { - allAuthType.push_back(*iter); - } -} - -const AdapterSoLoadInfo* DmConfigManager::GetAdapterSoLoadInfo(const std::string& soName) -{ - if (soAdapterLoadInfo_.find(soName) != soAdapterLoadInfo_.end()) { - return &soAdapterLoadInfo_[soName]; - } - return nullptr; -} - -const AuthSoLoadInfo* DmConfigManager::GetAuthSoLoadInfo(const std::string& soName) -{ - if (soAuthLoadInfo_.find(soName) != soAuthLoadInfo_.end()) { - return &soAuthLoadInfo_[soName]; - } - return nullptr; -} - -std::shared_ptr DmConfigManager::GetDecisionAdapter(const std::string& soName) -{ - auto soInfoIter = soAdapterLoadInfo_.find(soName); - if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != DECISION_JSON_TYPE_KEY) { - LOGE("not find so info or type not match"); - return nullptr; - } - - std::unique_lock locker(decisionAdpaterMutex_); - 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) -{ - auto soInfoIter = soAdapterLoadInfo_.find(soName); - if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != PROFILE_JSON_TYPE_KEY) { - LOGE("not find so info or type not match"); - return nullptr; - } - - std::unique_lock locker(profileAdpaterMutex_); - 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) -{ - auto soInfoIter = soAdapterLoadInfo_.find(soName); - if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != CPYPTO_JSON_TYPE_KEY) { - LOGE("not find so info or type not match"); - return nullptr; - } - - std::unique_lock locker(cryptoAdpaterMutex_); - 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]; -} - -std::shared_ptr DmConfigManager::GetAuthAdapter(const std::string& soName) -{ - auto soInfoIter = soAuthLoadInfo_.find(soName); - if (soInfoIter == soAuthLoadInfo_.end() || (soInfoIter->second).type != AUTH_JSON_TYPE_KEY) { - LOGE("not find so info or type not match"); - return nullptr; - } - - std::unique_lock locker(authAdapterMutex_); - auto ptrIter = authAdapterPtr_.find(soName); - if (ptrIter != authAdapterPtr_.end()) { - return authAdapterPtr_[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 auth so %s failed", soName.c_str()); - return nullptr; - } - } - - dlerror(); - auto func = (CreateIAuthAdapterFuncPtr)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 iAuthentication(func()); - authAdapterPtr_[soName] = iAuthentication; - return authAdapterPtr_[soName]; -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 0ff41f793..9a28fddba 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -34,8 +34,9 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co } if (!extra.empty() && !deviceList.empty()) { + std::string soName; DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); - std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(); + std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(soName); if (decisionAdapter != nullptr) { //decisionAdapter->FilterDeviceList(deviceList, extra); } else { diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 54f97dc11..1a0ab70f0 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -34,8 +34,9 @@ DmDeviceStateManager::~DmDeviceStateManager() } void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) { + std::string soName; DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); - std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); if (profileAdapter == nullptr){ LOGE("OnDeviceOnline profile adapter is null"); // return; @@ -46,8 +47,9 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe } void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) { + std::string soName; DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); - std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); if (profileAdapter == nullptr){ LOGE("OnDeviceOnline profile adapter is null"); // return; -- Gitee From a35927e728f3c092470f829af0fa1ee29dbb8eaa Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Thu, 6 Jan 2022 09:57:12 +0800 Subject: [PATCH 069/110] =?UTF-8?q?=E4=BE=9D=E8=B5=96=E6=80=A7=E5=88=A0?= =?UTF-8?q?=E9=99=A4/=E6=A0=BC=E5=BC=8F=E5=AF=B9=E9=BD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ext/pin_auth/BUILD.gn | 6 ------ .../native_cpp/src/device_manager_impl.cpp | 8 +++----- .../src/device_manager_service.cpp | 6 ++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 14 +++++++------- 4 files changed, 12 insertions(+), 22 deletions(-) diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index 6ab4f8db5..5669910ef 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -39,22 +39,16 @@ if (defined(ohos_lite)) { ] 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", ] external_deps = [ - "ces_standard:cesfwk_core", - "ces_standard:cesfwk_innerkits", "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", 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 38a99772d..c2cfb4d6b 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -399,7 +399,7 @@ int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string & } int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, const std::string &authPara, - std::shared_ptr callback) + std::shared_ptr callback) { LOGI("DeviceManager::VerifyAuthentication start, pkgName: %s", pkgName.c_str()); if (!isSystemAppCalling()) { @@ -478,8 +478,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t return DM_OK; } -int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, - std::string &udid) +int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid) { if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); @@ -503,8 +502,7 @@ int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const return DM_OK; } -int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, - std::string &uuid) +int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) { if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index cf6127041..61852592b 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -109,8 +109,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) return deviceInfoMgr_->GetLocalDeviceInfo(info); } -int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, - std::string &udid) +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"); @@ -125,8 +124,7 @@ int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, con return DM_OK; } -int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, - std::string &uuid) +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"); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index ddb859ee1..aebe3fe79 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -373,20 +373,20 @@ ON_IPC_CMD(GET_UDID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) { } ON_IPC_CMD(GET_UUID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) { - std::string pkgName = data.ReadString(); + std::string pkgName = data.ReadString(); std::string netWorkId = data.ReadString(); std::string uuid; - int32_t result = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, 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; + 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) { -- Gitee From b9b2e2c3522127f5310b8c648e127d27185c6597 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Thu, 6 Jan 2022 10:24:33 +0800 Subject: [PATCH 070/110] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=A2=E5=A4=B1?= =?UTF-8?q?=E7=9A=84config=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/config/config_manager.h | 78 +++++ .../include/config/json_config.h | 80 +++++ .../src/config/config_manager.cpp | 311 ++++++++++++++++++ 3 files changed, 469 insertions(+) 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/src/config/config_manager.cpp diff --git a/services/devicemanagerservice/include/config/config_manager.h b/services/devicemanagerservice/include/config/config_manager.h new file mode 100644 index 000000000..031e4aeb4 --- /dev/null +++ b/services/devicemanagerservice/include/config/config_manager.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "decision_adapter.h" +#include "profile_adapter.h" +#include "crypto_adapter.h" +#include "authentication.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..bb14e4f14 --- /dev/null +++ b/services/devicemanagerservice/include/config/json_config.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 \ No newline at end of file diff --git a/services/devicemanagerservice/src/config/config_manager.cpp b/services/devicemanagerservice/src/config/config_manager.cpp new file mode 100644 index 000000000..6d92b2d34 --- /dev/null +++ b/services/devicemanagerservice/src/config/config_manager.cpp @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_log.h" +#include "json_config.h" +#include "dm_constants.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 -- Gitee From 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 Mon Sep 17 00:00:00 2001 From: puhui Date: Thu, 6 Jan 2022 12:10:06 +0800 Subject: [PATCH 071/110] =?UTF-8?q?=E7=BC=96=E7=A8=8B=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- common/include/dm_constants.h | 298 ++++++++------- common/include/ipc/ipc_def.h | 24 +- .../ipc/model/ipc_authenticate_device_req.h | 8 +- .../include/ipc/model/ipc_get_dmfaparam_rsp.h | 4 +- .../ipc/model/ipc_get_local_device_info_rsp.h | 8 +- .../ipc/model/ipc_get_trustdevice_req.h | 6 +- .../ipc/model/ipc_get_trustdevice_rsp.h | 6 +- .../ipc/model/ipc_notify_auth_result_req.h | 10 +- .../ipc/model/ipc_notify_device_found_req.h | 10 +- .../ipc/model/ipc_notify_device_state_req.h | 10 +- .../model/ipc_notify_discover_result_req.h | 8 +- .../ipc/model/ipc_notify_dmfa_result_req.h | 6 +- .../model/ipc_notify_verify_auth_result_req.h | 10 +- .../ipc/model/ipc_register_listener_req.h | 3 +- common/include/ipc/model/ipc_req.h | 6 +- common/include/ipc/model/ipc_rsp.h | 4 +- .../ipc/model/ipc_set_useroperation_req.h | 5 +- .../ipc/model/ipc_start_discovery_req.h | 8 +- .../ipc/model/ipc_stop_discovery_req.h | 6 +- .../ipc/model/ipc_unauthenticate_device_req.h | 6 +- .../ipc/model/ipc_verify_authenticate_req.h | 6 +- common/include/single_instance.h | 30 +- ext/config/json_config.h | 80 ---- .../include/ability/dm_ability_manager.h | 15 +- ext/pin_auth/include/pin_auth.h | 2 +- ext/pin_auth/include/pin_auth_ui.h | 2 +- .../src/ability/lite/dm_ability_manager.cpp | 6 +- .../ability/standard/dm_ability_manager.cpp | 10 +- ext/pin_auth/src/pin_auth.cpp | 12 +- ext/pin_auth/src/pin_auth_ui.cpp | 6 +- ext/profile/include/device_profile_adapter.h | 5 +- ext/profile/src/device_profile_adapter.cpp | 5 +- .../native_cpp/include/device_manager.h | 6 +- .../include/device_manager_callback.h | 31 +- .../native_cpp/include/device_manager_impl.h | 23 +- .../native_cpp/include/dm_app_image_info.h | 26 +- .../native_cpp/include/dm_device_info.h | 2 +- .../native_cpp/include/dm_subscribe_info.h | 4 +- .../native_cpp/include/ipc/ipc_client.h | 3 +- .../native_cpp/include/ipc/ipc_client_proxy.h | 9 +- .../include/ipc/lite/ipc_client_manager.h | 5 +- .../ipc/lite/ipc_client_server_proxy.h | 6 +- .../include/ipc/lite/ipc_client_stub.h | 6 +- .../include/ipc/standard/ipc_client_manager.h | 13 +- .../ipc/standard/ipc_client_server_proxy.h | 7 +- .../include/ipc/standard/ipc_client_stub.h | 6 +- .../include/ipc/standard/ipc_remote_broker.h | 7 +- .../include/notify/device_manager_notify.h | 12 +- .../native_cpp/src/device_manager.cpp | 2 +- .../native_cpp/src/device_manager_impl.cpp | 24 +- .../native_cpp/src/ipc/ipc_client_proxy.cpp | 2 +- .../src/ipc/lite/ipc_client_manager.cpp | 2 +- .../src/ipc/lite/ipc_client_server_proxy.cpp | 4 +- .../src/ipc/lite/ipc_client_stub.cpp | 2 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 48 +-- .../src/ipc/standard/ipc_client_manager.cpp | 2 +- .../ipc/standard/ipc_client_server_proxy.cpp | 2 +- .../src/ipc/standard/ipc_client_stub.cpp | 5 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 26 +- .../src/notify/device_manager_notify.cpp | 42 +- interfaces/kits/js/include/dm_native_event.h | 2 +- .../kits/js/include/native_devicemanager_js.h | 100 ++--- interfaces/kits/js/src/dm_native_event.cpp | 2 +- .../kits/js/src/native_devicemanager_js.cpp | 359 ++++++++---------- services/devicemanagerservice/BUILD.gn | 4 - .../include/ability/dm_ability_manager.h | 15 +- .../include/adapter/crypto_adapter.h | 8 +- .../include/adapter/decision_adapter.h | 4 +- .../include/adapter/dm_adapter_manager.h | 9 +- .../include/adapter/profile_adapter.h | 4 +- .../authentication/auth_message_processor.h | 4 +- .../authentication/auth_request_state.h | 12 +- .../authentication/auth_response_state.h | 10 +- .../include/authentication/auth_ui.h | 6 +- .../include/authentication/authentication.h | 4 +- .../include/authentication/dm_auth_manager.h | 12 +- .../include/config/config_manager.h | 17 +- .../include/config/json_config.h | 9 +- .../commonevent/event_manager_adapt.h | 29 +- .../include/dependency/eventbus/event.h | 48 --- .../include/dependency/eventbus/event_bus.h | 151 -------- .../dependency/eventbus/event_registration.h | 49 --- .../dependency/eventbus/event_sender.h | 28 -- .../dependency/eventbus/eventbus_handler.h | 37 -- .../dependency/hichain/hichain_connector.h | 13 +- .../hichain/hichain_connector_callback.h | 3 +- .../dependency/softbus/softbus_connector.h | 14 +- .../softbus/softbus_discovery_callback.h | 3 +- .../dependency/softbus/softbus_session.h | 4 +- .../softbus/softbus_session_callback.h | 6 +- .../softbus/softbus_state_callback.h | 3 +- .../include/dependency/timer/dm_timer.h | 10 +- .../include/device_manager_service.h | 19 +- .../include/device_manager_service_listener.h | 9 +- .../deviceinfo/dm_device_info_manager.h | 8 +- .../devicestate/dm_device_state_manager.h | 9 +- .../include/discovery/dm_discovery_manager.h | 13 +- .../include/ipc/lite/ipc_server_listener.h | 2 +- .../include/ipc/lite/ipc_server_listenermgr.h | 6 +- .../include/ipc/lite/ipc_server_stub.h | 2 +- .../ipc/standard/ipc_server_client_proxy.h | 8 +- .../ipc/standard/ipc_server_listener.h | 3 +- .../include/ipc/standard/ipc_server_stub.h | 17 +- .../src/ability/lite/dm_ability_manager.cpp | 8 +- .../ability/standard/dm_ability_manager.cpp | 10 +- .../src/adapter/lite/dm_adapter_manager.cpp | 10 +- .../adapter/standard/dm_adapter_manager.cpp | 14 +- .../authentication/auth_message_processor.cpp | 43 ++- .../src/authentication/auth_request_state.cpp | 122 +++--- .../authentication/auth_response_state.cpp | 37 +- .../src/authentication/auth_ui.cpp | 2 +- .../src/authentication/dm_auth_manager.cpp | 200 +++++----- .../src/config/config_manager.cpp | 84 ++-- .../commonevent/event_manager_adapt.cpp | 34 +- .../src/dependency/eventbus/event_bus.cpp | 24 -- .../dependency/hichain/hichain_connector.cpp | 68 ++-- .../dependency/softbus/softbus_connector.cpp | 107 ++---- .../dependency/softbus/softbus_session.cpp | 59 +-- .../src/dependency/timer/dm_timer.cpp | 10 +- .../src/device_manager_service.cpp | 32 +- .../src/device_manager_service_listener.cpp | 29 +- .../src/deviceinfo/dm_device_info_manager.cpp | 17 +- .../devicestate/dm_device_state_manager.cpp | 35 +- .../src/discovery/dm_discovery_manager.cpp | 49 +-- .../src/ipc/lite/ipc_cmd_parser.cpp | 34 +- .../src/ipc/lite/ipc_server_listener.cpp | 2 +- .../src/ipc/lite/ipc_server_listenermgr.cpp | 2 +- .../src/ipc/lite/ipc_server_main.cpp | 3 +- .../src/ipc/lite/ipc_server_stub.cpp | 13 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 69 ++-- .../ipc/standard/ipc_server_client_proxy.cpp | 3 +- .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 18 +- utils/include/dm_anonymous.h | 4 +- utils/include/dm_log.h | 18 +- utils/include/dm_random.h | 2 +- utils/include/ipc/lite/ipc_cmd_register.h | 86 +++-- utils/include/ipc/standard/ipc_cmd_register.h | 58 +-- utils/src/dm_anonymous.cpp | 8 +- utils/src/dm_log.cpp | 2 +- utils/src/dm_random.cpp | 4 +- utils/src/ipc/lite/ipc_cmd_register.cpp | 6 +- utils/src/ipc/standard/ipc_cmd_register.cpp | 2 +- 143 files changed, 1437 insertions(+), 1920 deletions(-) delete mode 100644 ext/config/json_config.h delete mode 100644 services/devicemanagerservice/include/dependency/eventbus/event.h delete mode 100644 services/devicemanagerservice/include/dependency/eventbus/event_bus.h delete mode 100644 services/devicemanagerservice/include/dependency/eventbus/event_registration.h delete mode 100644 services/devicemanagerservice/include/dependency/eventbus/event_sender.h delete mode 100644 services/devicemanagerservice/include/dependency/eventbus/eventbus_handler.h delete mode 100644 services/devicemanagerservice/src/dependency/eventbus/event_bus.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index abdefb7d8..198b60c21 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.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,157 +21,155 @@ 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 DM_PKG_NAME = "com.huawei.devicemanager"; - // const std::string DM_SESSION_NAME = "com.huawei.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; +const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; +const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; - 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_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; +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"; - // 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; +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; - //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 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"; +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_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; - //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"; -} -} +// 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 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/ipc_def.h b/common/include/ipc/ipc_def.h index 1a5ab0055..c19e13a46 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,18 +21,18 @@ 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, diff --git a/common/include/ipc/model/ipc_authenticate_device_req.h b/common/include/ipc/model/ipc_authenticate_device_req.h index cc20f75f9..3d700ba6a 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, @@ -24,8 +24,9 @@ namespace OHOS { namespace DistributedHardware { class IpcAuthenticateDeviceReq : public IpcReq { DECLARE_IPC_MODEL(IpcAuthenticateDeviceReq); + public: - const DmDeviceInfo& GetDeviceInfo() const + const DmDeviceInfo &GetDeviceInfo() const { return deviceInfo_; } @@ -45,7 +46,7 @@ public: authType_ = authType; } - const std::string& GetExtra() const + const std::string &GetExtra() const { return extra_; } @@ -54,6 +55,7 @@ public: { extra_ = extra; } + private: DmDeviceInfo deviceInfo_; int32_t authType_; diff --git a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h index f8a74ec9b..e9d1f2639 100644 --- a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h +++ b/common/include/ipc/model/ipc_get_dmfaparam_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, @@ -24,6 +24,7 @@ namespace OHOS { namespace DistributedHardware { class IpcGetDmFaParamRsp : public IpcRsp { DECLARE_IPC_MODEL(IpcGetDmFaParamRsp); + public: const DmAuthParam GetDmAuthParam() const { @@ -34,6 +35,7 @@ public: { dmFaParam_ = dmFaParam; } + private: DmAuthParam dmFaParam_; }; 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 index 2e86038e8..a70facc86 100644 --- a/common/include/ipc/model/ipc_get_local_device_info_rsp.h +++ b/common/include/ipc/model/ipc_get_local_device_info_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, @@ -24,16 +24,18 @@ namespace OHOS { namespace DistributedHardware { class IpcGetLocalDeviceInfoRsp : public IpcRsp { DECLARE_IPC_MODEL(IpcGetLocalDeviceInfoRsp); + public: - const DmDeviceInfo& GetLocalDeviceInfo() const + const DmDeviceInfo &GetLocalDeviceInfo() const { return localDeviceInfo_; } - void SetLocalDeviceInfo(const DmDeviceInfo& localDeviceInfo) + void SetLocalDeviceInfo(const DmDeviceInfo &localDeviceInfo) { localDeviceInfo_ = localDeviceInfo; } + private: DmDeviceInfo localDeviceInfo_; }; diff --git a/common/include/ipc/model/ipc_get_trustdevice_req.h b/common/include/ipc/model/ipc_get_trustdevice_req.h index 7ac969c7c..56f31dadb 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, @@ -22,8 +22,9 @@ namespace OHOS { namespace DistributedHardware { class IpcGetTrustDeviceReq : public IpcReq { DECLARE_IPC_MODEL(IpcGetTrustDeviceReq); + public: - const std::string& GetExtra() const + const std::string &GetExtra() const { return extra_; } @@ -32,6 +33,7 @@ public: { extra_ = extra; } + private: std::string extra_; }; diff --git a/common/include/ipc/model/ipc_get_trustdevice_rsp.h b/common/include/ipc/model/ipc_get_trustdevice_rsp.h index 3ba8832de..ea26906c5 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, @@ -26,16 +26,18 @@ namespace OHOS { namespace DistributedHardware { 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_; }; 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 8dfb3ce83..a4e0badd7 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, @@ -24,13 +24,14 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyAuthResultReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyAuthResultReq); + public: std::string GetDeviceId() const { return deviceId_; } - void SetDeviceId(const std::string& deviceId) + void SetDeviceId(const std::string &deviceId) { deviceId_ = deviceId; } @@ -64,11 +65,12 @@ public: { reason_ = reason; } + private: std::string deviceId_; std::string token_; - int32_t status_ {0}; - int32_t reason_ {0}; + int32_t status_{0}; + int32_t reason_{0}; }; } // namespace DistributedHardware } // namespace OHOS 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 cb51464c9..954b70c6a 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, @@ -24,13 +24,14 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyDeviceFoundReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyDeviceFoundReq); + public: - const DmDeviceInfo& GetDeviceInfo() const + const DmDeviceInfo &GetDeviceInfo() const { return dmDeviceInfo_; } - void SetDeviceInfo(const DmDeviceInfo& dmDeviceInfo) + void SetDeviceInfo(const DmDeviceInfo &dmDeviceInfo) { dmDeviceInfo_ = dmDeviceInfo; } @@ -44,8 +45,9 @@ public: { subscribeId_ = subscribeId; } + private: - uint16_t subscribeId_ {0}; + uint16_t subscribeId_{0}; DmDeviceInfo dmDeviceInfo_; }; } // namespace DistributedHardware 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 0cb6cb5bf..4703b8247 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, @@ -24,6 +24,7 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyDeviceStateReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyDeviceStateReq); + public: int32_t GetDeviceState() const { @@ -35,17 +36,18 @@ public: deviceState_ = deviceState; } - const DmDeviceInfo& GetDeviceInfo() const + const DmDeviceInfo &GetDeviceInfo() const { return dmDeviceInfo_; } - void SetDeviceInfo(const DmDeviceInfo& dmDeviceInfo) + void SetDeviceInfo(const DmDeviceInfo &dmDeviceInfo) { dmDeviceInfo_ = dmDeviceInfo; } + private: - int32_t deviceState_ {0}; + int32_t deviceState_{0}; DmDeviceInfo dmDeviceInfo_; }; } // namespace DistributedHardware 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 e1a3f7474..c48d12d2d 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, @@ -22,6 +22,7 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyDiscoverResultReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyDiscoverResultReq); + public: uint16_t GetSubscribeId() const { @@ -42,9 +43,10 @@ public: { result_ = result; } + private: - uint16_t subscribeId_ {0}; - int32_t result_ {0}; + uint16_t subscribeId_{0}; + int32_t result_{0}; }; } // namespace DistributedHardware } // namespace OHOS 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 a517d2f98..14744e692 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, @@ -22,16 +22,18 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyDMFAResultReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyDMFAResultReq); + public: std::string GetJsonParam() const { return JsonParam_; } - void SetJsonParam(const std::string& JsonParam) + void SetJsonParam(const std::string &JsonParam) { JsonParam_ = JsonParam; } + private: std::string JsonParam_; }; 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 index 233babfc6..0e6a4104c 100644 --- a/common/include/ipc/model/ipc_notify_verify_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_verify_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, @@ -24,13 +24,14 @@ 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) + void SetDeviceId(const std::string &deviceId) { deviceId_ = deviceId; } @@ -54,10 +55,11 @@ public: { flag_ = flag; } + private: std::string deviceId_; - int32_t result_ {0}; - int32_t flag_ {0}; + int32_t result_{0}; + int32_t flag_{0}; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_register_listener_req.h b/common/include/ipc/model/ipc_register_listener_req.h index 5b82a2fcc..e7dc5a83d 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, @@ -28,6 +28,7 @@ namespace OHOS { namespace DistributedHardware { class IpcRegisterListenerReq : public IpcReq { DECLARE_IPC_MODEL(IpcRegisterListenerReq); + public: #ifdef LITE_DEVICE SvcIdentity GetSvcIdentity() const diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index 4f2d1bc24..1583738ca 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, @@ -24,8 +24,9 @@ namespace OHOS { namespace DistributedHardware { class IpcReq { DECLARE_IPC_MODEL(IpcReq); + public: - const std::string& GetPkgName() const + const std::string &GetPkgName() const { return pkgName_; } @@ -34,6 +35,7 @@ public: { pkgName_ = pkgName; } + private: std::string pkgName_; }; diff --git a/common/include/ipc/model/ipc_rsp.h b/common/include/ipc/model/ipc_rsp.h index 1af507684..30a2bfd94 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, @@ -24,6 +24,7 @@ namespace OHOS { namespace DistributedHardware { class IpcRsp { DECLARE_IPC_MODEL(IpcRsp); + public: int32_t GetErrCode() const { @@ -34,6 +35,7 @@ public: { errCode_ = errCode; } + private: int32_t errCode_; }; diff --git a/common/include/ipc/model/ipc_set_useroperation_req.h b/common/include/ipc/model/ipc_set_useroperation_req.h index 90a873c51..ec46f6896 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, @@ -24,6 +24,7 @@ namespace OHOS { namespace DistributedHardware { class IpcGetOperationReq : public IpcReq { DECLARE_IPC_MODEL(IpcGetOperationReq); + public: int32_t GetOperation() const { @@ -36,7 +37,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 c8b77ac2f..c110f55d7 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, @@ -24,8 +24,9 @@ namespace OHOS { namespace DistributedHardware { class IpcStartDiscoveryReq : public IpcReq { DECLARE_IPC_MODEL(IpcStartDiscoveryReq); + public: - const DmSubscribeInfo& GetSubscribeInfo() const + const DmSubscribeInfo &GetSubscribeInfo() const { return subscribeInfo_; } @@ -35,7 +36,7 @@ public: subscribeInfo_ = subscribeInfo; } - const std::string& GetExtra() const + const std::string &GetExtra() const { return extra_; } @@ -44,6 +45,7 @@ public: { extra_ = extra; } + private: std::string extra_; DmSubscribeInfo subscribeInfo_; diff --git a/common/include/ipc/model/ipc_stop_discovery_req.h b/common/include/ipc/model/ipc_stop_discovery_req.h index 2d53adc2b..fba136527 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, @@ -24,6 +24,7 @@ namespace OHOS { namespace DistributedHardware { class IpcStopDiscoveryReq : public IpcReq { DECLARE_IPC_MODEL(IpcStopDiscoveryReq); + public: uint16_t GetSubscribeId() const { @@ -34,8 +35,9 @@ public: { subscribeId_ = subscribeId; } + private: - uint16_t subscribeId_ {0}; + uint16_t subscribeId_{0}; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_unauthenticate_device_req.h b/common/include/ipc/model/ipc_unauthenticate_device_req.h index fa6c3dcb7..c142d4a30 100644 --- a/common/include/ipc/model/ipc_unauthenticate_device_req.h +++ b/common/include/ipc/model/ipc_unauthenticate_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, @@ -24,8 +24,9 @@ namespace OHOS { namespace DistributedHardware { class IpcUnAuthenticateDeviceReq : public IpcReq { DECLARE_IPC_MODEL(IpcUnAuthenticateDeviceReq); + public: - const DmDeviceInfo& GetDeviceInfo() const + const DmDeviceInfo &GetDeviceInfo() const { return deviceInfo_; } @@ -34,6 +35,7 @@ public: { deviceInfo_ = deviceInfo; } + private: DmDeviceInfo deviceInfo_; }; diff --git a/common/include/ipc/model/ipc_verify_authenticate_req.h b/common/include/ipc/model/ipc_verify_authenticate_req.h index 26400c66e..5c973498b 100644 --- a/common/include/ipc/model/ipc_verify_authenticate_req.h +++ b/common/include/ipc/model/ipc_verify_authenticate_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, @@ -22,8 +22,9 @@ namespace OHOS { namespace DistributedHardware { class IpcVerifyAuthenticateReq : public IpcReq { DECLARE_IPC_MODEL(IpcVerifyAuthenticateReq); + public: - const std::string& GetAuthPara() const + const std::string &GetAuthPara() const { return authPara_; } @@ -32,6 +33,7 @@ public: { authPara_ = authPara; } + private: std::string authPara_; }; diff --git a/common/include/single_instance.h b/common/include/single_instance.h index e2601b876..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, @@ -19,27 +19,27 @@ 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 diff --git a/ext/config/json_config.h b/ext/config/json_config.h deleted file mode 100644 index f048ce162..000000000 --- a/ext/config/json_config.h +++ /dev/null @@ -1,80 +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_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.so", - "soPath": "/system/lib/" - }, - { - "name": "device_profile", - "type": "PROFILE", - "version": "1.0", - "funcName": "CreateDeviceProfileObject", - "soName": "libdevicemanager_dp_adapter.so", - "soPath": "/system/lib/" - } - ] -})"; - -const std::string authJsonConfigString = -R"({ - "devicemanager_auth_components": [ - { - "name": "pin_auth", - "type": "AUTHENTICATE", - "version": "1.0", - "authType": "pin", - "funcName": "CreatePinAuthObject", - "soName": "libdevicemanagerext_pin_auth.z.so", - "soPath": "/system/lib/" - }, - { - "name": "QRcode_auth", - "type": "AUTHENTICATE", - "version": "1.0", - "authType": "QRcode", - "funcName": "CreateQRcodeAuthObject", - "soName": "libdevicemanager_qrcodeauth.z.so", - "soPath": "/system/lib/" - }, - { - "name": "nfc_auth", - "type": "AUTHENTICATE", - "version": "1.0", - "authType": "nfc", - "funcName": "CreateNfcAuthObject", - "soName": "libdevicemanager_nfcauth.z.so", - "soPath": "/system/lib/" - } - ] -})"; - -} // namespace DistributedHardware -} // namespace OHOS -#endif \ 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 index 2cb96ec26..d4f2c4863 100644 --- a/ext/pin_auth/include/ability/dm_ability_manager.h +++ b/ext/pin_auth/include/ability/dm_ability_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, @@ -23,17 +23,9 @@ namespace OHOS { namespace DistributedHardware { -enum AbilityRole { - ABILITY_ROLE_PASSIVE = 0, - ABILITY_ROLE_INITIATIVE = 1, - ABILITY_ROLE_UNKNOWN = 2 -}; +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 AbilityStatus { ABILITY_STATUS_FAILED = 0, ABILITY_STATUS_SUCCESS = 1, ABILITY_STATUS_START = 2 }; enum FaAction { USER_OPERATION_TYPE_ALLOW_AUTH = 0, @@ -48,6 +40,7 @@ public: AbilityRole GetAbilityRole(); AbilityStatus StartAbility(AbilityRole role); void StartAbilityDone(); + private: void waitForTimeout(uint32_t timeout_s); diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h index a15e8390e..2f6232876 100644 --- a/ext/pin_auth/include/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.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, diff --git a/ext/pin_auth/include/pin_auth_ui.h b/ext/pin_auth/include/pin_auth_ui.h index 018587678..f8910cba2 100644 --- a/ext/pin_auth/include/pin_auth_ui.h +++ b/ext/pin_auth/include/pin_auth_ui.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, diff --git a/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp index 539b52f96..31870a284 100644 --- a/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/lite/dm_ability_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, @@ -47,5 +47,5 @@ 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 index 40633518d..87bca5753 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_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, @@ -30,7 +30,7 @@ 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() { @@ -53,7 +53,7 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) LOGE("Start Ability faild"); mStatus_ = ABILITY_STATUS_FAILED; return mStatus_; - } + } waitForTimeout(ABILITY_START_TIMEOUT); return mStatus_; } @@ -71,5 +71,5 @@ 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 index 74dc69a54..c582d45e5 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.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, @@ -29,9 +29,8 @@ PinAuth::PinAuth() PinAuth::~PinAuth() { - } - + int32_t PinAuth::ShowAuthInfo() { return pinAuthUi_->ShowPinDialog(); @@ -42,8 +41,9 @@ int32_t PinAuth::StartAuth(std::shared_ptr dmAbilityManager) return pinAuthUi_->InputPinDialog(dmAbilityManager); } -extern "C" IAuthentication* CreatePinAuthObject (void) { +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 index 69ffb0e45..15dd767ab 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.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, @@ -50,5 +50,5 @@ int32_t PinAuthUi::StartFaUiService(std::shared_ptr dmAbilityM } return DM_OK; } -} -} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/ext/profile/include/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h index 1e58ce5a2..fb27cbdd5 100644 --- a/ext/profile/include/device_profile_adapter.h +++ b/ext/profile/include/device_profile_adapter.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, @@ -23,9 +23,8 @@ namespace DistributedHardware { class DeviceProfileAdapter : public IProfileAdapter { public: DeviceProfileAdapter(); - -private: +private: }; } // namespace DistributedHardware } // namespace OHOS diff --git a/ext/profile/src/device_profile_adapter.cpp b/ext/profile/src/device_profile_adapter.cpp index 94a86ea59..2fe6d6f51 100644 --- a/ext/profile/src/device_profile_adapter.cpp +++ b/ext/profile/src/device_profile_adapter.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, @@ -19,6 +19,5 @@ namespace OHOS { namespace DistributedHardware { - -} } +} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 279b0d581..c996814de 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_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, @@ -29,6 +29,7 @@ namespace DistributedHardware { class DeviceManager { public: static DeviceManager &GetInstance(); + public: virtual int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) = 0; virtual int32_t UnInitDeviceManager(const std::string &pkgName) = 0; @@ -36,7 +37,7 @@ public: 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; + 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; @@ -51,5 +52,4 @@ public: }; } // namespace DistributedHardware } // namespace OHOS - #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 2a1a079cf..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, @@ -25,13 +25,17 @@ 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 OnDeviceOffline(const DmDeviceInfo &deviceInfo) = 0; virtual void OnDeviceChanged(const DmDeviceInfo &deviceInfo) = 0; @@ -40,26 +44,35 @@ public: class DiscoveryCallback { public: - virtual ~DiscoveryCallback() {} - virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; + virtual ~DiscoveryCallback() + { + } + virtual void OnDiscoverySuccess(uint16_t subscribeId) = 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(const std::string &deviceId, const std::string &token, 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 VerifyAuthCallback { public: - virtual ~VerifyAuthCallback() {} + virtual ~VerifyAuthCallback() + { + } virtual void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) = 0; }; class DeviceManagerFaCallback { public: - virtual ~DeviceManagerFaCallback() {} + virtual ~DeviceManagerFaCallback() + { + } virtual void OnCall(const std::string ¶mJson) = 0; }; } // namespace DistributedHardware 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 733c87da3..49c3917bd 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, @@ -25,7 +25,8 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { public: - static DeviceManagerImpl& GetInstance(); + static DeviceManagerImpl &GetInstance(); + public: virtual int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) override; @@ -37,29 +38,33 @@ public: 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; + 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; + 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 GetFaParam(const std::string &pkgName, DmAuthParam &faParam) override; virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) override; + private: DeviceManagerImpl() = default; ~DeviceManagerImpl() = default; - DeviceManagerImpl(const DeviceManagerImpl&) = delete; - DeviceManagerImpl& operator = (const DeviceManagerImpl&) = delete; - DeviceManagerImpl(DeviceManagerImpl&&) = delete; - DeviceManagerImpl& operator = (DeviceManagerImpl&&) = delete; + 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()); }; } // namespace DistributedHardware } // namespace OHOS - #endif // OHOS_DEVICE_MANAGER_IMPL_H 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 1a3e7256c..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, @@ -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,11 +171,12 @@ 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; }; 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 eb2c32523..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, 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 57eccdb88..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, @@ -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 { 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 8db238f87..b95fabadb 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, @@ -27,6 +27,7 @@ namespace OHOS { namespace DistributedHardware { class IpcClient { DECLARE_IPC_INTERFACE(IpcClient); + public: virtual int32_t Init(const std::string &pkgName) = 0; virtual int32_t UnInit(const std::string &pkgName) = 0; 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 95866c599..22e3fd4dc 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, @@ -27,14 +27,17 @@ namespace OHOS { namespace DistributedHardware { class IpcClientProxy : public IpcClient { DECLARE_IPC_INTERFACE(IpcClientProxy); + public: - IpcClientProxy(std::shared_ptr ipcClientManager) : ipcClientManager_(ipcClientManager) {}; + IpcClientProxy(std::shared_ptr ipcClientManager) : ipcClientManager_(ipcClientManager){}; + public: 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 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 efe32e78c..0e4746b97 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, @@ -27,12 +27,15 @@ namespace OHOS { namespace DistributedHardware { class IpcClientManager : public IpcClient { DECLARE_IPC_INTERFACE(IpcClientManager); + public: 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(const std::string &pkgName); + private: IpcClientServerProxy serverProxy_; std::set packageInitSet_; 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 1389af5ff..23b369397 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, @@ -33,12 +33,14 @@ 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 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 5c019d6d5..76fb7167a 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, @@ -27,15 +27,17 @@ namespace OHOS { namespace DistributedHardware { class 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 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 fee6ac52a..22c61ab44 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, @@ -38,20 +38,23 @@ public: }; class IpcClientManager : public IpcClient { -friend class DmDeathRecipient; -DECLARE_IPC_INTERFACE(IpcClientManager); + friend class DmDeathRecipient; + DECLARE_IPC_INTERFACE(IpcClientManager); + public: 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(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 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 154994b83..bb27d1479 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, @@ -28,9 +28,10 @@ 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_; }; 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 f1d1e7407..f654f0db1 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, @@ -30,8 +30,8 @@ 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; }; 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 1d2eda69f..9d88094cf 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, @@ -28,8 +28,11 @@ 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"); }; 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 fc541f55b..bef7c3077 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, @@ -31,13 +31,14 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerNotify { DECLARE_SINGLE_INSTANCE(DeviceManagerNotify); + public: 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); + 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); @@ -46,6 +47,7 @@ public: void RegisterVerifyAuthenticationCallback(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback); void UnRegisterVerifyAuthenticationCallback(const std::string &pkgName); + public: void OnRemoteDied(); void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); @@ -54,11 +56,11 @@ public: 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, + 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 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_; 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 b77413725..f0d756512 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, @@ -50,7 +50,7 @@ bool DeviceManagerImpl::isSystemAppCalling(void) LOGE("check permission true for system uid %d", uid); return true; } - + std::string bundleName; BundleMgrClient bundleMgrClient; bool ret = bundleMgrClient.GetBundleNameForUid(uid, bundleName); @@ -70,7 +70,7 @@ bool DeviceManagerImpl::isSystemAppCalling(void) return bundleInfo.applicationInfo.isSystemApp; } -DeviceManagerImpl & DeviceManagerImpl::GetInstance() +DeviceManagerImpl &DeviceManagerImpl::GetInstance() { static DeviceManagerImpl instance; return instance; @@ -147,10 +147,10 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons 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); + LOGI("GetTrustedDeviceList error: failed ret: %d", ret); return DM_IPC_RESPOND_ERROR; } @@ -178,17 +178,17 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDevi ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGI("GetLocalDeviceInfo error: failed ret: %d",ret); + LOGI("GetLocalDeviceInfo error: failed ret: %d", ret); return DM_IPC_RESPOND_ERROR; } info = rsp->GetLocalDeviceInfo(); - LOGI("GetLocalDeviceInfo completed,pkgname%s",req->GetPkgName().c_str()); + LOGI("GetLocalDeviceInfo completed,pkgname%s", req->GetPkgName().c_str()); return DM_OK; } int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, - std::shared_ptr callback) + std::shared_ptr callback) { LOGI("DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); if (!isSystemAppCalling()) { @@ -297,8 +297,9 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint1 return DM_OK; } -int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, const DmDeviceInfo &deviceInfo, - const std::string &extra, std::shared_ptr callback) +int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const DmDeviceInfo &deviceInfo, const std::string &extra, + std::shared_ptr callback) { LOGI("DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); if (!isSystemAppCalling()) { @@ -335,7 +336,6 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ return DM_OK; } - int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s, deviceId: %s", pkgName.c_str(), deviceId.c_str()); @@ -373,7 +373,7 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons } int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, const std::string &authPara, - std::shared_ptr callback) + std::shared_ptr callback) { if (!isSystemAppCalling()) { LOGI("the caller is not a system app"); 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 248812296..af32e1f65 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, 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 93f693737..0fa638f85 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, 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 91d3ae92f..e492e5069 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, @@ -25,7 +25,7 @@ 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; 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 e1b90089a..65865047c 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, 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 0bbedd437..3e58881a1 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, @@ -35,8 +35,8 @@ 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(); @@ -55,7 +55,7 @@ ON_IPC_READ_RESPONSE(REGISTER_DEVICE_MANAGER_LISTENER, IpcIo &reply, std::shared } 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(); @@ -70,8 +70,8 @@ ON_IPC_READ_RESPONSE(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &reply, std::shar 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::string pkgName = pReq->GetPkgName(); @@ -107,8 +107,8 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +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; @@ -119,7 +119,7 @@ ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, IpcIo &reply, std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); uint32_t size = 0; - DmDeviceInfo* dmDeviceInfo = (DmDeviceInfo *)IpcIoPopFlatObj(&reply, &size); + DmDeviceInfo *dmDeviceInfo = (DmDeviceInfo *)IpcIoPopFlatObj(&reply, &size); if (dmDeviceInfo != nullptr) { pRsp->SetLocalDeviceInfo(*dmDeviceInfo); } @@ -127,8 +127,8 @@ ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, IpcIo &reply, 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(); @@ -148,8 +148,8 @@ ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, IpcIo &reply, 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(); @@ -167,12 +167,12 @@ ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr 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); @@ -189,8 +189,8 @@ ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, IpcIo &reply, std::shared_ptr return DM_OK; } -ON_IPC_SET_REQUEST(VERIFY_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::string authPara = pReq->GetAuthPara(); @@ -206,8 +206,8 @@ ON_IPC_READ_RESPONSE(VERIFY_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo& request, - uint8_t *buffer, size_t buffLen) +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(); @@ -219,7 +219,7 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTH_OPERATION, std::shared_ptr pBaseReq, return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_USER_AUTH_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_USER_AUTH_OPERATION, IpcIo &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); return DM_OK; @@ -231,7 +231,7 @@ 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) { LOGE("OnDeviceOnline, get para failed"); return; @@ -258,7 +258,7 @@ 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) { LOGE("OnDeviceChanged, get para failed"); return; @@ -290,7 +290,7 @@ 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); 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 a2b1815a5..648f68388 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, 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 23ffa8bd5..dc0862783 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, 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 53bd6e82b..2d0558e28 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, @@ -25,8 +25,7 @@ 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) { LOGI("code = %d, flags= %d.", code, option.GetFlags()); if (IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply) == DM_OK) { 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 c9c1ba20a..b75719bf3 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, @@ -129,7 +129,7 @@ ON_IPC_READ_RESPONSE(GET_LOCAL_DEVICE_INFO, MessageParcel &reply, std::shared_pt { std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); DmDeviceInfo *localDeviceInfo = (DmDeviceInfo *)reply.ReadRawData(sizeof(DmDeviceInfo)); - if (localDeviceInfo == nullptr){ + if (localDeviceInfo == nullptr) { LOGE("write subscribe info failed"); } pRsp->SetLocalDeviceInfo(*localDeviceInfo); @@ -185,11 +185,11 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag { 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(); std::string deviceId = deviceInfo.deviceId; -// DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); + // DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); if (!data.WriteString(pkgName)) { LOGE("write pkgName failed"); @@ -207,24 +207,6 @@ ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, Messag LOGE("write pkgName failed"); return DM_IPC_FLATTEN_OBJECT; } -// int32_t appIconLen = imageInfo.GetAppIconLen(); -// int32_t appThumbnailLen = imageInfo.GetAppThumbnailLen(); -// if (!data.WriteInt32(appIconLen)) { -// LOGE("write imageinfo appicon len failed"); -// return DM_IPC_FLATTEN_OBJECT; -// } -// if (!data.WriteInt32(appThumbnailLen)) { -// LOGE("write imageinfo appThumbnailLen failed"); -// return DM_IPC_FLATTEN_OBJECT; -// } -// if (appIconLen > 0 && !data.WriteRawData(imageInfo.GetAppIcon(), appIconLen)) { -// LOGE("write imageinfo appIcon failed"); -// return DM_IPC_FLATTEN_OBJECT; -// } -// if (appThumbnailLen > 0 && !data.WriteRawData(imageInfo.GetAppThumbnail(), appThumbnailLen)) { -// LOGE("write imageinfo appThumbnail failed"); -// return DM_IPC_FLATTEN_OBJECT; -// } return DM_OK; } 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 cc07e51a4..c89972184 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, @@ -25,7 +25,7 @@ namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, - std::shared_ptr dmInitCallback) + std::shared_ptr dmInitCallback) { std::lock_guard autoLock(lock_); dmInitCallback_[pkgName] = dmInitCallback; @@ -38,7 +38,7 @@ void DeviceManagerNotify::UnRegisterDeathRecipientCallback(const std::string &pk } void DeviceManagerNotify::RegisterDeviceStateCallback(const std::string &pkgName, - std::shared_ptr callback) + std::shared_ptr callback) { std::lock_guard autoLock(lock_); deviceStateCallback_[pkgName] = callback; @@ -51,7 +51,7 @@ void DeviceManagerNotify::UnRegisterDeviceStateCallback(const std::string &pkgNa } void DeviceManagerNotify::RegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId, - std::shared_ptr callback) + std::shared_ptr callback) { std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { @@ -72,7 +72,7 @@ void DeviceManagerNotify::UnRegisterDiscoveryCallback(const std::string &pkgName } void DeviceManagerNotify::RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, - std::shared_ptr callback) + std::shared_ptr callback) { std::lock_guard autoLock(lock_); if (authenticateCallback_.count(pkgName) == 0) { @@ -156,10 +156,9 @@ void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDe } void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, - const DmDeviceInfo &deviceInfo) + const DmDeviceInfo &deviceInfo) { - LOGI("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 (deviceDiscoveryCallbacks_.count(pkgName) == 0) { LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for this package"); @@ -168,8 +167,7 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for subscribeId %d", - subscribeId); + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } iter->second->OnDeviceFound(subscribeId, deviceInfo); @@ -177,8 +175,8 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) { - LOGI("DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", - pkgName.c_str(), subscribeId, failedReason); + LOGI("DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", pkgName.c_str(), subscribeId, + failedReason); std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for this package"); @@ -187,8 +185,7 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for subscribeId %d", - subscribeId); + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } iter->second->OnDiscoveryFailed(subscribeId, failedReason); @@ -196,8 +193,7 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId) { - LOGI("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 (deviceDiscoveryCallbacks_.count(pkgName) == 0) { LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for this package"); @@ -206,18 +202,16 @@ void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_ std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { - LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for subscribeId %d", - subscribeId); + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for subscribeId %d", subscribeId); return; } iter->second->OnDiscoverySuccess(subscribeId); } -void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, - uint32_t status, uint32_t reason) +void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::string &deviceId, + const std::string &token, uint32_t status, uint32_t reason) { - LOGI("DeviceManagerNotify::OnAuthResult pkgName:%s, status:%d, reason:%d", - pkgName.c_str(), status, reason); + LOGI("DeviceManagerNotify::OnAuthResult pkgName:%s, status:%d, reason:%d", pkgName.c_str(), status, reason); std::lock_guard autoLock(lock_); if (authenticateCallback_.count(pkgName) == 0) { LOGE("DeviceManager OnAuthResult: no register authCallback for this package"); @@ -239,8 +233,8 @@ void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::st void DeviceManagerNotify::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode, int32_t flag) { - LOGI("DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", - pkgName.c_str(), resultCode, flag); + LOGI("DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", pkgName.c_str(), resultCode, + flag); std::lock_guard autoLock(lock_); if (verifyAuthCallback_.count(pkgName) == 0) { LOGE("DeviceManager OnCheckAuthResult: no register authCallback for this package"); diff --git a/interfaces/kits/js/include/dm_native_event.h b/interfaces/kits/js/include/dm_native_event.h index d551fbac8..6d21ffb68 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, diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index d8807340c..cef7739a9 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, @@ -67,17 +67,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: @@ -86,8 +85,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; @@ -99,8 +100,10 @@ private: class DmNapiDiscoveryCallback : public OHOS::DistributedHardware::DiscoveryCallback { public: - explicit DmNapiDiscoveryCallback(std::string &bundleName) : refCount_(0), bundleName_(bundleName) {} - virtual ~DmNapiDiscoveryCallback() {}; + explicit DmNapiDiscoveryCallback(std::string &bundleName) : refCount_(0), bundleName_(bundleName) + { + } + virtual ~DmNapiDiscoveryCallback(){}; void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; void OnDiscoverySuccess(uint16_t subscribeId) override; @@ -115,8 +118,10 @@ private: class DmNapiDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceManagerFaCallback { public: - explicit DmNapiDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiDeviceManagerFaCallback() {}; + explicit DmNapiDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + virtual ~DmNapiDeviceManagerFaCallback(){}; void OnCall(const std::string ¶mJson) override; private: @@ -125,8 +130,10 @@ private: class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { public: - explicit DmNapiAuthenticateCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiAuthenticateCallback() {}; + 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: @@ -135,8 +142,10 @@ private: class DmNapiVerifyAuthCallback : public OHOS::DistributedHardware::VerifyAuthCallback { public: - explicit DmNapiVerifyAuthCallback(std::string &bundleName) : bundleName_(bundleName) {} - virtual ~DmNapiVerifyAuthCallback() {}; + explicit DmNapiVerifyAuthCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + virtual ~DmNapiVerifyAuthCallback(){}; void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) override; private: @@ -169,60 +178,63 @@ public: 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); + 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); + 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 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); + 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); + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static void CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static napi_value CallDeviceList(napi_env env, napi_callback_info info, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static void CallGetLocalDeviceInfoSync(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static void CallGetLocalDeviceInfo(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + private: napi_env env_; napi_ref wrapper_; diff --git a/interfaces/kits/js/src/dm_native_event.cpp b/interfaces/kits/js/src/dm_native_event.cpp index c0e627c89..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, diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 18f5edc25..4e46ed1b6 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, @@ -26,11 +26,11 @@ 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"; @@ -46,16 +46,13 @@ const int32_t DM_NAPI_SUB_ID_MAX = 65535; 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_DiscoveryCallbackMap; std::map> g_authCallbackMap; std::map> g_verifyAuthCallbackMap; -} +} // namespace napi_ref DeviceManagerNapi::sConstructor_ = nullptr; AuthAsyncCallbackInfo DeviceManagerNapi::authAsyncCallbackInfo_; @@ -111,7 +108,7 @@ void DmNapiDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::CHANGE, deviceInfo); } -void DmNapiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +void DmNapiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { @@ -159,7 +156,8 @@ int32_t DmNapiDiscoveryCallback::GetRefCount() return refCount_; } -void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, 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) { @@ -202,7 +200,7 @@ DeviceManagerNapi *DeviceManagerNapi::GetDeviceManagerNapi(std::string &buldleNa } void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action, - const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) + const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) { napi_value result = nullptr; napi_create_object(env_, &result); @@ -245,22 +243,19 @@ void DeviceManagerNapi::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedRe OnEvent("discoverFail", DM_NAPI_ARGS_ONE, &result); } -void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) +void DeviceManagerNapi::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t 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) { LOGI("OnAuthResult success"); napi_get_undefined(env_, &result[0]); napi_create_object(env_, &result[1]); SetValueUtf8String(env_, "deviceId", deviceId, result[1]); - //TODO: - //if (authAsyncCallbackInfo_.authType == DM_AUTH_TYPE_PINCODE) { - // SetValueInt32(env_, "pinTone", token, result[1]); - //} } else { LOGI("OnAuthResult failed"); napi_create_object(env_, &result[0]); @@ -286,7 +281,7 @@ void DeviceManagerNapi::OnVerifyResult(const std::string &deviceId, int32_t resu 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]); @@ -311,7 +306,7 @@ void DeviceManagerNapi::OnVerifyResult(const std::string &deviceId, int32_t resu } 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); @@ -319,16 +314,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); @@ -343,8 +337,8 @@ void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, } } -void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, - const DmAuthParam &authParam, napi_value ¶mResult) +void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAuthParam &authParam, + napi_value ¶mResult) { napi_value extraInfo = nullptr; napi_create_object(env, &extraInfo); @@ -370,7 +364,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(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()), + 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); @@ -385,7 +379,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(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); @@ -393,8 +387,8 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(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)); @@ -440,8 +434,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)); @@ -458,8 +452,8 @@ void DeviceManagerNapi::JsObjectToInt(const napi_env &env, const napi_value &obj } } -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)); @@ -476,8 +470,7 @@ void DeviceManagerNapi::JsObjectToBool(const napi_env &env, const napi_value &ob } } -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); @@ -511,8 +504,7 @@ 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)); @@ -521,9 +513,10 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & info.deviceTypeId = (DmDeviceType)deviceType; } -void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &object, std::string &extra, int32_t &authType) +void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &object, std::string &extra, + int32_t &authType) { - LOGI("JsToDmExtra in."); + LOGI("JsToDmExtra in."); int32_t authTypeTemp = -1; JsObjectToInt(env, object, "authType", authTypeTemp); authType = authTypeTemp; @@ -535,9 +528,7 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec uint8_t *appThumbnailBufferPtr = nullptr; int32_t appThumbnailBufferLen = 0; JsToDmBuffer(env, object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); - // appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); - if (appIconBufferPtr != nullptr) { free(appIconBufferPtr); appIconBufferPtr = nullptr; @@ -556,8 +547,8 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec 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) { LOGI("JsToDmBuffer in."); bool hasProperty = false; @@ -574,13 +565,12 @@ 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) { LOGE("Invaild AppIconInfo"); return; } - *bufferPtr = (uint8_t*)calloc(sizeof(uint8_t), length); + *bufferPtr = (uint8_t *)calloc(sizeof(uint8_t), length); if (*bufferPtr == nullptr) { LOGE("low memory, calloc return nullptr, length is %d, filed %s", length, fieldStr.c_str()); return; @@ -594,8 +584,8 @@ 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) { LOGI("JsToJsonObject in."); bool hasProperty = false; @@ -661,19 +651,15 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob JsObjectToInt(env, object, "authType", authType); JsObjectToInt(env, object, "token", token); - nlohmann::json jsonObj; - //TODO: jsonObj[AUTH_TYPE] = authType; 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_value &result) { napi_create_object(env, &result); @@ -763,8 +749,7 @@ napi_value DeviceManagerNapi::GetAuthenticationParamSync(napi_env env, napi_call 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); + LOGE("GetAuthenticationParam for %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); napi_get_undefined(env, &resultParam); return resultParam; } @@ -795,15 +780,15 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i } void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) + 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); + deviceInfoAsyncCallbackInfo->devList[i].deviceId, deviceInfoAsyncCallbackInfo->devList[i].deviceName, + deviceInfoAsyncCallbackInfo->devList[i].deviceTypeId); } - napi_value array[DM_NAPI_ARGS_TWO] = { 0 }; + napi_value array[DM_NAPI_ARGS_TWO] = {0}; if (deviceInfoAsyncCallbackInfo->status == 0) { if (deviceInfoAsyncCallbackInfo->devList.size() > 0) { bool isArray = false; @@ -812,7 +797,6 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_st 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]); } @@ -848,16 +832,16 @@ void DeviceManagerNapi::OnDmfaCall(const std::string ¶mJson) } void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) + 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); + 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 }; + napi_value array[DM_NAPI_ARGS_TWO] = {0}; if (deviceInfoAsyncCallbackInfo->status == 0) { if (deviceInfoAsyncCallbackInfo->devList.size() > 0) { @@ -868,7 +852,7 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status LOGE("napi_create_array fail"); } - for (size_t i= 0; i != deviceInfoAsyncCallbackInfo->devList.size(); ++i) { + for (size_t i = 0; i != deviceInfoAsyncCallbackInfo->devList.size(); ++i) { DeviceInfoToJsArray(env, deviceInfoAsyncCallbackInfo->devList, i, array[1]); } LOGE("devList is OK"); @@ -890,13 +874,13 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status } void DeviceManagerNapi::CallGetLocalDeviceInfoSync(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) { - napi_value result[DM_NAPI_ARGS_TWO] = { 0 }; + 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); + deviceInfoAsyncCallbackInfo->deviceInfo.deviceId, deviceInfoAsyncCallbackInfo->deviceInfo.deviceName, + deviceInfoAsyncCallbackInfo->deviceInfo.deviceTypeId); if (deviceInfoAsyncCallbackInfo->status == 0) { DmDeviceInfotoJsDeviceInfo(env, deviceInfoAsyncCallbackInfo->deviceInfo, result[1]); @@ -908,12 +892,12 @@ void DeviceManagerNapi::CallGetLocalDeviceInfoSync(napi_env env, napi_status &st } void DeviceManagerNapi::CallGetLocalDeviceInfo(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) { - napi_value result[DM_NAPI_ARGS_TWO] = { 0 }; + 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); + deviceInfoAsyncCallbackInfo->deviceInfo.deviceId, deviceInfoAsyncCallbackInfo->deviceInfo.deviceName, + deviceInfoAsyncCallbackInfo->deviceInfo.deviceTypeId); napi_value callResult = nullptr; napi_value handler = nullptr; @@ -943,16 +927,17 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI (void)env; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; int32_t ret = 0; - if(deviceInfoAsyncCallbackInfo->isList == 1){ + if (deviceInfoAsyncCallbackInfo->isList == 1) { ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->extra, deviceInfoAsyncCallbackInfo->devList); + deviceInfoAsyncCallbackInfo->extra, + deviceInfoAsyncCallbackInfo->devList); } else { ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->deviceInfo); + deviceInfoAsyncCallbackInfo->deviceInfo); } if (ret != 0) { LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", - deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); + deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); deviceInfoAsyncCallbackInfo->status = -1; return; } @@ -962,14 +947,15 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI [](napi_env env, napi_status status, void *data) { (void)status; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - if(deviceInfoAsyncCallbackInfo->isList == 1){ + 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); + }, + (void *)deviceInfoAsyncCallbackInfo, &deviceInfoAsyncCallbackInfo->asyncWork); napi_queue_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); } @@ -978,50 +964,46 @@ void DeviceManagerNapi::CallAsyncWork(napi_env env, 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); + 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) + DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) { napi_value result = nullptr; - // DmFilterOptions filterOptions; - // memset_s(filterOptions.targetPkgName, sizeof(filterOptions.targetPkgName), 0, sizeof(filterOptions.targetPkgName)); - // int32_t sortType = -1; - // filterOptions.sortType = (DmDeviceSortType)sortType; - // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); - // deviceInfoAsyncCallbackInfo->filter = filterOptions; std::string extra = ""; deviceInfoAsyncCallbackInfo->extra = extra; GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); @@ -1040,8 +1022,6 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in napi_value promise = 0; napi_create_promise(env, &deferred, &promise); deviceInfoAsyncCallbackInfo->deferred = deferred; - // JsToDmFilterOptions(env, argv[0], filterOptions); - // deviceInfoAsyncCallbackInfo->filter = filterOptions; char extraString[20]; JsObjectToString(env, argv[0], "extra", extraString, sizeof(extraString)); deviceInfoAsyncCallbackInfo->extra = extraString; @@ -1056,8 +1036,8 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba napi_value result = nullptr; napi_value thisVar = nullptr; DmDeviceInfo deviceInfo; - LOGI("DeviceManager::GetTrustedDeviceListSync deviceId:%s deviceName:%s deviceTypeId:%d ", - deviceInfo.deviceId, deviceInfo.deviceName, deviceInfo.deviceTypeId); + LOGI("DeviceManager::GetTrustedDeviceListSync 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)); @@ -1069,13 +1049,11 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceManagerWrapper->bundleName_, extra, devList); if (ret != 0) { LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); - return result; + return result; } LOGI("DeviceManager::GetTrustedDeviceListSync"); - if (devList.size() > 0) - { - for (size_t i= 0; i != devList.size(); ++i) - { + if (devList.size() > 0) { + for (size_t i = 0; i != devList.size(); ++i) { DeviceInfoToJsArray(env, devList, i, result); } } @@ -1099,14 +1077,7 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i deviceInfoAsyncCallbackInfo->isList = 1; deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; LOGE("GetTrustedDeviceList for argc %d", argc); - if(argc == 0) { - // DmFilterOptions filterOptions; - // memset_s(filterOptions.targetPkgName, sizeof(filterOptions.targetPkgName), 0, - // sizeof(filterOptions.targetPkgName)); - // int32_t sortType = -1; - // filterOptions.sortType = (DmDeviceSortType)sortType; - // memset_s(filterOptions.filter, sizeof(filterOptions.filter), 0, sizeof(filterOptions.filter)); - // deviceInfoAsyncCallbackInfo->filter = filterOptions; + if (argc == 0) { std::string extra = ""; deviceInfoAsyncCallbackInfo->extra = extra; napi_deferred deferred; @@ -1129,9 +1100,6 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i 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."); - - // JsToDmFilterOptions(env, argv[0], filterOptions); - // deviceInfoAsyncCallbackInfo->filter = filterOptions; char extra[20]; JsObjectToString(env, argv[0], "extra", extra, sizeof(extra)); deviceInfoAsyncCallbackInfo->extra = extra; @@ -1149,8 +1117,8 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback 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); + 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)); @@ -1159,11 +1127,11 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback 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; + LOGE("GetLocalDeviceInfoSync for failed, ret %d", ret); + return result; } - LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ", - deviceInfo.deviceId, deviceInfo.deviceName, deviceInfo.deviceTypeId); + LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ", deviceInfo.deviceId, + deviceInfo.deviceName, deviceInfo.deviceTypeId); DmDeviceInfotoJsDeviceInfo(env, deviceInfo, result); return result; } @@ -1185,7 +1153,7 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfo(napi_env env, napi_callback_inf deviceInfoAsyncCallbackInfo->isList = 0; deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; LOGE("GetLocalDeviceInfo for argc %d", argc); - if(argc == 0) { + if (argc == 0) { std::string extra = ""; deviceInfoAsyncCallbackInfo->extra = extra; napi_deferred deferred; @@ -1221,8 +1189,7 @@ napi_value DeviceManagerNapi::UnAuthenticateDevice(napi_env env, napi_callback_i 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); + LOGE("UnAuthenticateDevice for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } napi_create_int32(env, ret, &result); @@ -1254,12 +1221,10 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac NAPI_ASSERT(env, res == 0, "Wrong subscribeId "); std::string extra = ""; - //TODO: - int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, - subInfo, extra, DiscoveryCallback); + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, subInfo, extra, + DiscoveryCallback); if (ret != 0) { - LOGE("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); return result; } @@ -1275,18 +1240,15 @@ napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback 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) { - LOGE("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; } @@ -1329,19 +1291,12 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf } DmDeviceInfo deviceInfo; JsToDmDeviceInfo(env, argv[0], deviceInfo); - -// DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); - // char extra[20]; - // JsObjectToString(env, argv[PARAM_INDEX_ONE], "extra", extra, sizeof(extra)); std::string extraString; JsToDmExtra(env, argv[PARAM_INDEX_ONE], extraString, authAsyncCallbackInfo_.authType); - - //TODO:get real authType int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, - extraString, authCallback); + extraString, authCallback); if (ret != 0) { - LOGE("AuthenticateDevice for bundleName %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; @@ -1377,11 +1332,10 @@ napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info in std::string authParam; JsToDmAuthInfo(env, argv[0], authParam); - int32_t ret = DeviceManager::GetInstance().VerifyAuthentication(deviceManagerWrapper->bundleName_, - authParam, verifyCallback); + int32_t ret = + DeviceManager::GetInstance().VerifyAuthentication(deviceManagerWrapper->bundleName_, authParam, verifyCallback); if (ret != 0) { - LOGE("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); @@ -1397,7 +1351,7 @@ napi_value DeviceManagerNapi::JsOnFrench(napi_env env, int32_t num, napi_value t 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){ + if (num) { // DmFilterOptions filterOptions; // JsToDmFilterOptions(env, argv[1], filterOptions); } @@ -1406,9 +1360,8 @@ napi_value DeviceManagerNapi::JsOnFrench(napi_env env, int32_t num, napi_value t DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - LOGI("JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), - eventType.c_str()); - deviceManagerWrapper->On(eventType, argv[num+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); @@ -1430,7 +1383,7 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) 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"); @@ -1455,17 +1408,12 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) return JsOnFrench(env, 0, thisVar, argv); } - } napi_value DeviceManagerNapi::JsOffFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]) -{ - // DmFilterOptions filterOptions; +{ size_t typeLen = 0; napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen); - // if(num){ - // JsToDmFilterOptions(env, argv[1], filterOptions); - // } NAPI_ASSERT(env, typeLen > 0, "typeLen == 0"); NAPI_ASSERT(env, typeLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN"); char type[DM_NAPI_BUF_LENGTH] = {0}; @@ -1475,8 +1423,7 @@ napi_value DeviceManagerNapi::JsOffFrench(napi_env env, int32_t num, napi_value DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - LOGI("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); @@ -1499,7 +1446,7 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) 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"); @@ -1527,7 +1474,6 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) } return JsOffFrench(env, 0, thisVar, argv); } - } napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_info info) { @@ -1544,8 +1490,7 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i LOGI("ReleaseDeviceManager for bunderName %s", deviceManagerWrapper->bundleName_.c_str()); int32_t ret = DeviceManager::GetInstance().UnInitDeviceManager(deviceManagerWrapper->bundleName_); if (ret != 0) { - LOGE("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; } @@ -1581,7 +1526,7 @@ 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); @@ -1609,7 +1554,8 @@ 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); } @@ -1630,7 +1576,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); @@ -1650,7 +1596,7 @@ 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); @@ -1658,7 +1604,8 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) 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; @@ -1687,17 +1634,15 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) 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), }; 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_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)); @@ -1718,15 +1663,13 @@ 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 diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index ffd61a01c..15d59a3d6 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -31,7 +31,6 @@ if (defined(ohos_lite)) { "include/discovery", "include/dependency/hichain", "include/dependency/softbus", -# "include/dependency/eventbus", "include/dependency/timer", "include/ipc", "include/ipc/lite", @@ -75,7 +74,6 @@ if (defined(ohos_lite)) { "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", -# "src/dependency/eventbus/event_bus.cpp", "src/dependency/timer/dm_timer.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", @@ -120,7 +118,6 @@ if (defined(ohos_lite)) { "include/dependency/commonevent", "include/dependency/hichain", "include/dependency/softbus", - "include/dependency/eventbus", "include/dependency/timer", "include/ipc", "include/ipc/standard", @@ -157,7 +154,6 @@ if (defined(ohos_lite)) { "src/deviceinfo/dm_device_info_manager.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/discovery/dm_discovery_manager.cpp", - "src/dependency/eventbus/event_bus.cpp", "src/dependency/commonevent/event_manager_adapt.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h index e874851c7..0b7e6604d 100644 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ b/services/devicemanagerservice/include/ability/dm_ability_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, @@ -25,17 +25,9 @@ namespace OHOS { namespace DistributedHardware { -enum AbilityRole { - ABILITY_ROLE_PASSIVE = 0, - ABILITY_ROLE_INITIATIVE = 1, - ABILITY_ROLE_UNKNOWN = 2 -}; +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 AbilityStatus { ABILITY_STATUS_FAILED = 0, ABILITY_STATUS_SUCCESS = 1, ABILITY_STATUS_START = 2 }; enum FaAction { USER_OPERATION_TYPE_ALLOW_AUTH = 0, @@ -50,6 +42,7 @@ public: AbilityRole GetAbilityRole(); AbilityStatus StartAbility(AbilityRole role); void StartAbilityDone(); + private: void waitForTimeout(uint32_t timeout_s); diff --git a/services/devicemanagerservice/include/adapter/crypto_adapter.h b/services/devicemanagerservice/include/adapter/crypto_adapter.h index cd1e2e0f1..099107ed1 100644 --- a/services/devicemanagerservice/include/adapter/crypto_adapter.h +++ b/services/devicemanagerservice/include/adapter/crypto_adapter.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, @@ -26,12 +26,12 @@ public: 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; + 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; + int32_t plainTextLen, int32_t *outLen) = 0; }; -using CreateICryptoAdapterFuncPtr = ICryptoAdapter* (*)(void); +using CreateICryptoAdapterFuncPtr = ICryptoAdapter *(*)(void); } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/adapter/decision_adapter.h b/services/devicemanagerservice/include/adapter/decision_adapter.h index c46d115f3..7e96a823d 100644 --- a/services/devicemanagerservice/include/adapter/decision_adapter.h +++ b/services/devicemanagerservice/include/adapter/decision_adapter.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, @@ -32,7 +32,7 @@ public: virtual int32_t SortDeviceList(std::vector &infoList, const std::string &sortOptions) = 0; }; -using CreateIDecisionAdapterFuncPtr = IDecisionAdapter* (*)(void); +using CreateIDecisionAdapterFuncPtr = IDecisionAdapter *(*)(void); } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index 071c73fbd..0dbc8fee0 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_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, @@ -27,10 +27,11 @@ namespace OHOS { namespace DistributedHardware { 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); + 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 diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index 25800f63a..c18d1e5ac 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.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, @@ -27,7 +27,7 @@ public: virtual int32_t UnRegisterProfileListener() = 0; }; -using CreateIProfileAdapterFuncPtr = IProfileAdapter* (*)(void); +using CreateIProfileAdapterFuncPtr = IProfileAdapter *(*)(void); } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/auth_message_processor.h b/services/devicemanagerservice/include/authentication/auth_message_processor.h index 29b79081c..3e985d499 100644 --- a/services/devicemanagerservice/include/authentication/auth_message_processor.h +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.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, @@ -39,6 +39,7 @@ public: 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); @@ -49,6 +50,7 @@ private: 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_; diff --git a/services/devicemanagerservice/include/authentication/auth_request_state.h b/services/devicemanagerservice/include/authentication/auth_request_state.h index 95e6aa173..d0cdc0635 100644 --- a/services/devicemanagerservice/include/authentication/auth_request_state.h +++ b/services/devicemanagerservice/include/authentication/auth_request_state.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, @@ -23,9 +23,10 @@ namespace OHOS { namespace DistributedHardware { class DmAuthManager; struct DmAuthRequestContext; -class AuthRequestState : public std::enable_shared_from_this{ +class AuthRequestState : public std::enable_shared_from_this { public: - virtual ~AuthRequestState(){ + virtual ~AuthRequestState() + { authManager_.reset(); LOGE("~AuthRequestState"); }; @@ -33,13 +34,12 @@ public: virtual void Enter() = 0; void Leave(); void TransitionTo(std::shared_ptr state); - // void SetLastState(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 lastState_; std::shared_ptr context_; }; @@ -91,4 +91,4 @@ public: }; } // namespace DistributedHardware } // namespace OHOS -#endif //OHOS_DM_AUTH_REQUEST_STATE_H +#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 index e8f50d0ab..f84e54ba9 100644 --- a/services/devicemanagerservice/include/authentication/auth_response_state.h +++ b/services/devicemanagerservice/include/authentication/auth_response_state.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, @@ -25,20 +25,20 @@ class DmAuthManager; struct DmAuthResponseContext; class AuthResponseState : public std::enable_shared_from_this { public: - virtual ~AuthResponseState(){ + virtual ~AuthResponseState() + { authManager_.reset(); }; virtual int32_t GetStateType() = 0; virtual void Enter() = 0; void Leave(); void TransitionTo(std::shared_ptr state); - // void SetLastState(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 lastState_; std::shared_ptr context_; }; @@ -79,4 +79,4 @@ public: }; } // namespace DistributedHardware } // namespace OHOS -#endif //OHOS_DM_AUTH_RESPONSE_STATE_H +#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 index 20c5ec32c..4ba96cb50 100644 --- a/services/devicemanagerservice/include/authentication/auth_ui.h +++ b/services/devicemanagerservice/include/authentication/auth_ui.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, @@ -26,10 +26,12 @@ class AuthUi { public: AuthUi(); int32_t ShowConfirmDialog(std::shared_ptr dmAbilityManager); + private: int32_t StartFaService(); + private: - std::shared_ptr dmAbilityMgr_ ; + std::shared_ptr dmAbilityMgr_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h index 5ebce1f20..7c3c76a3a 100644 --- a/services/devicemanagerservice/include/authentication/authentication.h +++ b/services/devicemanagerservice/include/authentication/authentication.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, @@ -27,7 +27,7 @@ public: virtual int32_t StartAuth(std::shared_ptr dmAbilityManager) = 0; }; -using CreateIAuthAdapterFuncPtr = IAuthentication* (*)(void); +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 index 2260f808c..0ad5b73c6 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_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, @@ -118,12 +118,15 @@ typedef struct DmAuthResponseContext { class AuthMessageProcessor; -class DmAuthManager final : public ISoftbusSessionCallback, public IHiChainConnectorCallback, public std::enable_shared_from_this { +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 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); @@ -132,7 +135,7 @@ public: void OnGroupCreated(int64_t requestId, const std::string &groupId); void OnMemberJoin(int64_t requestId, int32_t status); - //auth state machine + // auth state machine void EstablishAuthChannel(const std::string &deviceId); void StartNegotiate(const int32_t &sessionId); void RespNegotiate(const int32_t &sessionId); @@ -155,6 +158,7 @@ public: void ShowAuthInfoDialog(); void ShowStartAuthDialog(); int32_t GetAuthenticationParam(DmAuthParam &authParam); + private: std::shared_ptr softbusConnector_; std::shared_ptr sessionSession_; diff --git a/services/devicemanagerservice/include/config/config_manager.h b/services/devicemanagerservice/include/config/config_manager.h index 031e4aeb4..6395ad71d 100644 --- a/services/devicemanagerservice/include/config/config_manager.h +++ b/services/devicemanagerservice/include/config/config_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, @@ -52,16 +52,19 @@ typedef struct { } AuthSoLoadInfo; class DmConfigManager final { -DECLARE_SINGLE_INSTANCE_BASE(DmConfigManager); + 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); + 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_; diff --git a/services/devicemanagerservice/include/config/json_config.h b/services/devicemanagerservice/include/config/json_config.h index bb14e4f14..42d7153eb 100644 --- a/services/devicemanagerservice/include/config/json_config.h +++ b/services/devicemanagerservice/include/config/json_config.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, @@ -20,7 +20,7 @@ namespace OHOS { namespace DistributedHardware { -const std::string adapterJsonConfigString = +const std::string adapterJsonConfigString = R"({ "devicemanager_adapter_components": [ { @@ -42,7 +42,7 @@ R"({ ] })"; -const std::string authJsonConfigString = +const std::string authJsonConfigString = R"({ "devicemanager_auth_components": [ { @@ -74,7 +74,6 @@ R"({ } ] })"; - } // namespace DistributedHardware } // namespace OHOS -#endif \ No newline at end of file +#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 index f472380be..047eadd72 100644 --- a/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h +++ b/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.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, @@ -34,19 +34,23 @@ using CommomEventCallback = void (*)(void); class DmCommonEventManager { public: - static DmCommonEventManager& GetInstance(); + static DmCommonEventManager &GetInstance(); + public: - bool SubscribeServiceEvent(const std::string& event, CommomEventCallback callback); - bool UnsubscribeServiceEvent(const std::string& event); + 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) {} + : EventFwk::CommonEventSubscriber(subscribeInfo) + { + } void OnReceiveEvent(const EventFwk::CommonEventData &data); - void addEventCallback(const std::string& event, CommomEventCallback callback); - void deleteEventCallback(const std::string& event); + void addEventCallback(const std::string &event, CommomEventCallback callback); + void deleteEventCallback(const std::string &event); + private: std::mutex callbackLock_; std::map dmEventCallback_; @@ -54,11 +58,12 @@ public: private: DmCommonEventManager() = default; - virtual ~DmCommonEventManager(); - DmCommonEventManager(const DmCommonEventManager&) = delete; - DmCommonEventManager& operator= (const DmCommonEventManager&) = delete; - DmCommonEventManager(DmCommonEventManager&&) = delete; - DmCommonEventManager& operator= (DmCommonEventManager&&) = delete; + 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); diff --git a/services/devicemanagerservice/include/dependency/eventbus/event.h b/services/devicemanagerservice/include/dependency/eventbus/event.h deleted file mode 100644 index 8db338218..000000000 --- a/services/devicemanagerservice/include/dependency/eventbus/event.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_DM_EVENTBUS_EVENT_H -#define OHOS_DM_EVENTBUS_EVENT_H - -#include - -#include "event_sender.h" - -namespace OHOS { -namespace DistributedHardware { -#define TYPEINDENT(className) public: \ - virtual std::string GetType() const \ - { \ - return #className; \ - } - -class Event { -TYPEINDENT(Event) - -public: - Event(EventSender &sender) :sender_(sender) {} - - virtual ~Event() = default; - - const EventSender &GetSender() const - { - return sender_; - } -private: - EventSender &sender_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_EVENTBUS_EVENT_H diff --git a/services/devicemanagerservice/include/dependency/eventbus/event_bus.h b/services/devicemanagerservice/include/dependency/eventbus/event_bus.h deleted file mode 100644 index 683bd96bb..000000000 --- a/services/devicemanagerservice/include/dependency/eventbus/event_bus.h +++ /dev/null @@ -1,151 +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_EVENTBUS_H -#define OHOS_DM_EVENTBUS_H - -#include -#include -#include - -#include "event_handler.h" -#include "event.h" -#include "eventbus_handler.h" -#include "event_registration.h" -#include "dm_log.h" -#include "dm_anonymous.h" - -namespace OHOS { -namespace DistributedHardware { -class EventBus final { -public: - EventBus() = default; - ~EventBus() = default; - - static EventBus *GetInstance() - { - if (instance_ == nullptr) { - instance_ = new EventBus(); - } - if (!eventBusHandler_) { - auto eventBusRunner = AppExecFwk::EventRunner::Create("EventbusHandler"); - eventBusHandler_ = std::make_shared(eventBusRunner); - } - return instance_; - } - - template - static std::shared_ptr AddHandler(const std::string &typeId, EventBusHandler &handler, EventSender &sender) - { - EventBus *instance = GetInstance(); - Registrations *registrations = instance->handlers_[typeId]; - if (registrations == nullptr) { - registrations = new EventRegistration::Registrations(); - instance->handlers_[typeId] = registrations; - } - for (auto ® : *registrations) { - if (reg->GetHandler() == static_cast(&handler) && reg->GetSender() == &sender) { - return reg; - } - } - std::shared_ptr registration = std::make_shared(static_cast(&handler), - &sender); - registrations->insert(registration); - return registration; - } - - template - static std::shared_ptr AddHandler(const std::string &typeId, DistributedHardware::EventBusHandler &handler) - { - return AddHandler(typeId, handler, nullptr); - } - - template - static bool RemoveHandler(const std::string &typeId, std::shared_ptr &eventReg) - { - EventBus *instance = GetInstance(); - Registrations *registrations = instance->handlers_[typeId]; - if (registrations == nullptr) { - return false; - } - auto regIter = registrations->find(eventReg); - if (regIter != registrations->end()) { - registrations->erase(regIter); - return true; - } - return false; - } - - template - static void PostEvent(T &e, int64_t delayTime) - { - auto eventFunc = [e]() mutable { - PostEventInner(e); - }; - if (!eventBusHandler_ && eventBusHandler_->PostTask(eventFunc, e->GetType(), delayTime)) { - LOGE("Eventbus:PostEvent PostTask failed"); - } - } - - template - static void RemoveEvent(T &e) - { - if (!eventBusHandler_ && eventBusHandler_->RemoveTask(e->GetType())) { - LOGE("Eventbus:PostEvent RemoveTask failed"); - } - } - - static void PostTask(const AppExecFwk::InnerEvent::Callback &callback, const std::string &name, int64_t delayTimeInMs) - { - LOGI("Eventbus:PostTask Async, taskName:%s.", GetAnonyString(name).c_str()); - if (eventBusHandler_ != nullptr) { - eventBusHandler_->PostTask(callback, name, delayTimeInMs); - } - } - - static void RemoveTask(const std::string &name) - { - LOGI("Eventbus:RemoveTask Async, taskName:%s.", GetAnonyString(name).c_str()); - if (eventBusHandler_ != nullptr) { - eventBusHandler_->RemoveTask(name); - } - } - -private: - template - static void PostEventInner(T &e) - { - EventBus *instance = GetInstance(); - Registrations *registrations = instance->handlers_[e.GetType()]; - if (registrations == nullptr) { - return; - } - for (auto ® : *registrations) { - if ((reg->GetSender() == nullptr) || (reg->GetSender() == &e.GetSender())) { - static_cast *>(const_cast(reg->GetHandler()))->Dispatch(e); - } - } - } - -private: - static EventBus *instance_; - static std::shared_ptr eventBusHandler_; - using Registrations = std::set>; - using TypeMap = std::unordered_map> *>; - TypeMap handlers_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_EVENTBUS_H diff --git a/services/devicemanagerservice/include/dependency/eventbus/event_registration.h b/services/devicemanagerservice/include/dependency/eventbus/event_registration.h deleted file mode 100644 index 882607866..000000000 --- a/services/devicemanagerservice/include/dependency/eventbus/event_registration.h +++ /dev/null @@ -1,49 +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_EVENTBUS_EVENT_REGISTRATION_H -#define OHOS_DM_EVENTBUS_EVENT_REGISTRATION_H - -#include -#include - -#include "event_sender.h" - -namespace OHOS { -namespace DistributedHardware { -class EventRegistration { -public: - using Registrations = std::set>; - EventRegistration(void * const handler, EventSender * const sender) : handler_(handler), sender_(sender) {} - virtual ~EventRegistration() {} - - const void *GetHandler() - { - return handler_; - } - - const EventSender *GetSender() - { - return sender_; - } - -private: - void * const handler_; - EventSender * const sender_; - -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_EVENTBUS_EVENT_REGISTRATION_H diff --git a/services/devicemanagerservice/include/dependency/eventbus/event_sender.h b/services/devicemanagerservice/include/dependency/eventbus/event_sender.h deleted file mode 100644 index 840607e24..000000000 --- a/services/devicemanagerservice/include/dependency/eventbus/event_sender.h +++ /dev/null @@ -1,28 +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_EVENTBUS_EVENT_SENDER_H -#define OHOS_DM_EVENTBUS_EVENT_SENDER_H - -namespace OHOS { -namespace DistributedHardware { -class EventSender { -public: - virtual ~EventSender() = default; - -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_EVENTBUS_EVENT_SENDER_H diff --git a/services/devicemanagerservice/include/dependency/eventbus/eventbus_handler.h b/services/devicemanagerservice/include/dependency/eventbus/eventbus_handler.h deleted file mode 100644 index 902f112b5..000000000 --- a/services/devicemanagerservice/include/dependency/eventbus/eventbus_handler.h +++ /dev/null @@ -1,37 +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_EVENTBUS_EVENT_HANDLE_H -#define OHOS_DM_EVENTBUS_EVENT_HANDLE_H - -namespace OHOS { -namespace DistributedHardware { -template -class EventBusHandler { -public: - EventBusHandler() {} - - virtual ~EventBusHandler() = default; - - virtual void OnEvent(T &e) = 0; - - void Dispatch(T &e) - { - OnEvent(e); - } -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_EVENTBUS_EVENT_HANDLE_H diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index a2f05503b..938246d9d 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.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, @@ -36,10 +36,12 @@ struct GroupInfo { int32_t groupType; int32_t groupVisibility; - GroupInfo() : groupName(""), groupId(""), groupOwner(""), groupType(0), groupVisibility(0) {} + GroupInfo() : groupName(""), groupId(""), groupOwner(""), groupType(0), groupVisibility(0) + { + } }; -void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo); +void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo); class HiChainConnector { public: @@ -47,6 +49,7 @@ public: 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(); @@ -58,6 +61,7 @@ public: void DeleteGroup(std::string &groupId); int32_t 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); @@ -66,9 +70,10 @@ private: 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_ ; + DeviceAuthCallback deviceAuthCallback_; static std::map> hiChainConnectorCallbackMap_; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h index 1e0bac7aa..f6504949a 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector_callback.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector_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, @@ -16,7 +16,6 @@ #ifndef OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H #define OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H - namespace OHOS { namespace DistributedHardware { class IHiChainConnectorCallback { diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index 0a27b0bcd..cedfd158f 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.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, @@ -45,24 +45,30 @@ public: 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 GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info, int32_t infoLen); + 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 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 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(); + 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, diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h index a862b49ee..c8b1f57cd 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_discovery_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, @@ -16,7 +16,6 @@ #ifndef OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H #define OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H - namespace OHOS { namespace DistributedHardware { class ISoftbusDiscoveryCallback { diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 2da087841..4862c7d0c 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.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, @@ -32,6 +32,7 @@ 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(); @@ -41,6 +42,7 @@ public: 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_; }; diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h index 0b1a48c41..9569a3313 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_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, @@ -16,12 +16,12 @@ #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 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; diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h index 9335ac060..15a08a2e3 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_state_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_state_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, @@ -16,7 +16,6 @@ #ifndef OHOS_DM_SOFTBUS_STATE_CALLBACK_H #define OHOS_DM_SOFTBUS_STATE_CALLBACK_H - namespace OHOS { namespace DistributedHardware { class ISoftbusStateCallback { diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h index ea52ce137..788b0b5e9 100644 --- a/services/devicemanagerservice/include/dependency/timer/dm_timer.h +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.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, @@ -26,7 +26,6 @@ #include "dm_log.h" - namespace OHOS { namespace DistributedHardware { @@ -48,7 +47,7 @@ public: ~DmTimer(); DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data); void Stop(int32_t code); - void WiteforTimeout(); + void WaitForTimeout(); private: int32_t CreateTimeFd(); @@ -66,7 +65,6 @@ private: 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 index dca3a4836..fe9be358c 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.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, @@ -31,20 +31,25 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerService { -DECLARE_SINGLE_INSTANCE(DeviceManagerService); -public: + DECLARE_SINGLE_INSTANCE(DeviceManagerService); + +public: int32_t Init(); - int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList); int32_t GetLocalDeviceInfo(DmDeviceInfo &info); - int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra); + 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 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; + bool intFlag_ = false; std::shared_ptr authMgr_; std::shared_ptr deviceInfoMgr_; std::shared_ptr deviceStateMgr_; diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index bcd1e39f5..071f723f7 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.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, @@ -30,11 +30,12 @@ public: 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, + 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_; }; diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h index 9a55f83a7..8d67069bb 100644 --- a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_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, @@ -27,9 +27,11 @@ 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); + 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_; }; diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 7b6ab6f8c..f298685ea 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_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, @@ -16,16 +16,17 @@ #ifndef OHOS_DM_DEVICE_STATE_MANAGER_H #define OHOS_DM_DEVICE_STATE_MANAGER_H - #include "softbus_connector.h" #include "dm_adapter_manager.h" #include "device_manager_service_listener.h" namespace OHOS { namespace DistributedHardware { -class DmDeviceStateManager final : public ISoftbusStateCallback, public std::enable_shared_from_this { +class DmDeviceStateManager final : public ISoftbusStateCallback, + public std::enable_shared_from_this { public: - DmDeviceStateManager(std::shared_ptr softbusConnector, std::shared_ptr listener); + 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); diff --git a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h index 06fb6549d..b775453ba 100644 --- a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h +++ b/services/devicemanagerservice/include/discovery/dm_discovery_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, @@ -16,7 +16,6 @@ #ifndef OHOS_DM_DISCOVERY_MANAGER_H #define OHOS_DM_DISCOVERY_MANAGER_H - #include #include "softbus_connector.h" #include "device_manager_service_listener.h" @@ -30,16 +29,20 @@ typedef struct DmDiscoveryContext { uint16_t subscribeId; } DmDiscoveryContext; -class DmDiscoveryManager final : public ISoftbusDiscoveryCallback, public std::enable_shared_from_this { +class DmDiscoveryManager final : public ISoftbusDiscoveryCallback, + public std::enable_shared_from_this { public: - DmDiscoveryManager(std::shared_ptr softbusConnector, std::shared_ptr listener); + 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 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_; diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h index 840a4c0f6..a11a79137 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.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, diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h index 0dfc26074..19b8e4838 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.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, @@ -32,15 +32,17 @@ typedef struct CommonSvcId { uint32_t cookie; IpcContext *ipcCtx; uint32_t cbId; -}CommonSvcId; +} 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_; diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h index d6ac9d1e7..fc22d9471 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_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, diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h index 5349c7739..f1fbd2405 100644 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_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, @@ -23,10 +23,10 @@ namespace OHOS { namespace DistributedHardware { class IpcServerClientProxy : public IRemoteProxy { public: - explicit IpcServerClientProxy(const sptr &impl) - : IRemoteProxy(impl) {}; - ~IpcServerClientProxy() {}; + 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_; }; diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h index ac7d4ca4a..1ee6680b9 100644 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.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, @@ -27,6 +27,7 @@ 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); diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h index b2abdb4f5..f27806218 100644 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_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, @@ -34,10 +34,7 @@ namespace OHOS { namespace DistributedHardware { -enum class ServiceRunningState { - STATE_NOT_START, - STATE_RUNNING -}; +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; class AppDeathRecipient : public IRemoteObject::DeathRecipient { public: @@ -47,23 +44,25 @@ public: }; class IpcServerStub : public SystemAbility, public IRemoteStub { -DECLARE_SYSTEM_ABILITY(IpcServerStub); -DECLARE_SINGLE_INSTANCE_BASE(IpcServerStub); + 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 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_; diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp index d87cd3eed..e81442c7d 100644 --- a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/lite/dm_ability_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, @@ -35,7 +35,7 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) void DmAbilityManager::waitForTimeout(uint32_t timeout_s) { - struct timespec ts; + struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += timeout_s; sem_timedwait(&mSem_, &ts); @@ -46,5 +46,5 @@ 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 index 991ab1346..a55d25b55 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_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, @@ -30,7 +30,7 @@ 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() { @@ -53,7 +53,7 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) LOGE("Start Ability faild"); mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; return mStatus_; - } + } waitForTimeout(ABILITY_START_TIMEOUT); return mStatus_; } @@ -71,5 +71,5 @@ 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 index 592176348..4d67265d1 100644 --- a/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/lite/dm_adapter_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, @@ -20,7 +20,7 @@ namespace OHOS { namespace DistributedHardware { -DmAdapterManager& DmAdapterManager::GetInstance() +DmAdapterManager &DmAdapterManager::GetInstance() { static DmAdapterManager instance; return instance; @@ -51,7 +51,5 @@ 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 index 112f34410..977d9999f 100644 --- a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_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, @@ -22,28 +22,28 @@ namespace OHOS { namespace DistributedHardware { -DmAdapterManager& DmAdapterManager::GetInstance() +DmAdapterManager &DmAdapterManager::GetInstance() { static DmAdapterManager instance; return instance; } -std::shared_ptr DmAdapterManager::GetDecisionAdapter(const std::string& soName) +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) +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) +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 index 4ad748c1d..fade56bcc 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.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, @@ -37,8 +37,7 @@ 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); + 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; @@ -71,8 +70,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() 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); + 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()); } @@ -129,11 +127,12 @@ void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) json[TAG_REPLY] = authResponseContext_->reply; json[TAG_DEVICE_ID] = authResponseContext_->deviceId; // json[TAG_GROUPIDS] = authResponseContext_->deviceId; //? - LOGI("AuthMessageProcessor::ParseAuthResponseMessage %d,%d",authResponseContext_->reply,authResponseContext_->code); - LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s",authResponseContext_->deviceId.c_str()); + 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()); + 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"); @@ -145,7 +144,8 @@ void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) 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()); + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s", groupId.c_str(), + authResponseContext_->groupName.c_str()); } } @@ -162,21 +162,21 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) LOGE("DecodeRequestAuth jsonStr error"); return DM_FAILED; } - //TODO::try to crypto first then parse json - if (!jsonObject.contains(TAG_TYPE)){ + 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); + 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)) { + if (!jsonObject.contains(TAG_INDEX) || !jsonObject.contains(TAG_DEVICE_ID) || + !jsonObject.contains(TAG_SLICE_NUM)) { LOGE("err json string, first time"); return DM_FAILED; } @@ -186,7 +186,7 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) authResponseContext_->token = jsonObject[TAG_TOKEN]; authResponseContext_->targetPkgName = jsonObject[TAG_TARGET]; authResponseContext_->appName = jsonObject[TAG_APP_NAME]; - LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s",authResponseContext_->deviceId.c_str()); + LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str()); sliceNum = jsonObject[TAG_SLICE_NUM]; if ((int32_t)authSplitJsonList_.size() < sliceNum) { authSplitJsonList_.push_back(message); @@ -213,7 +213,7 @@ void AuthMessageProcessor::ParseResponseFinishMessage(nlohmann::json &json) void AuthMessageProcessor::ParseAuthResponseMessage(nlohmann::json &json) { - LOGI("AuthMessageProcessor::ParseAuthResponseMessage "); + LOGI("AuthMessageProcessor::ParseAuthResponseMessage "); authResponseContext_->reply = json[TAG_REPLY]; authResponseContext_->deviceId = json[TAG_DEVICE_ID]; // authResponseContext_->deviceId = json[TAG_GROUPIDS]; @@ -223,7 +223,8 @@ void AuthMessageProcessor::ParseAuthResponseMessage(nlohmann::json &json) 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 %s,%s", authResponseContext_->groupId.c_str(), + authResponseContext_->groupName.c_str()); } LOGI("AuthMessageProcessor::ParseAuthResponseMessage "); } @@ -233,10 +234,10 @@ 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_->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()); + 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]; @@ -284,5 +285,5 @@ std::shared_ptr AuthMessageProcessor::GetRequestContext() { return authRequestContext_; } -} -} \ No newline at end of file +} // 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 index accf29ebb..2ceb10fa7 100644 --- a/services/devicemanagerservice/src/authentication/auth_request_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_request_state.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, @@ -23,11 +23,12 @@ namespace OHOS { namespace DistributedHardware { -void AuthRequestState::Leave() { - +void AuthRequestState::Leave() +{ } -void AuthRequestState::SetAuthManager(std::shared_ptr authManager) { +void AuthRequestState::SetAuthManager(std::shared_ptr authManager) +{ authManager_ = std::move(authManager); } @@ -35,18 +36,21 @@ void AuthRequestState::SetAuthManager(std::shared_ptr authManager // lastState_ = state; // } -void AuthRequestState::SetAuthContext(std::shared_ptr context) { +void AuthRequestState::SetAuthContext(std::shared_ptr context) +{ context_ = std::move(context); } -std::shared_ptr AuthRequestState::GetAuthContext() { +std::shared_ptr AuthRequestState::GetAuthContext() +{ return context_; } -void AuthRequestState::TransitionTo(std::shared_ptr state) { +void AuthRequestState::TransitionTo(std::shared_ptr state) +{ LOGE("AuthRequestState::TransitionTo"); std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } @@ -57,129 +61,145 @@ void AuthRequestState::TransitionTo(std::shared_ptr state) { state->Enter(); } -int32_t AuthRequestInitState::GetStateType() { +int32_t AuthRequestInitState::GetStateType() +{ return AuthState::AUTH_REQUEST_INIT; } -void AuthRequestInitState::Enter() { +void AuthRequestInitState::Enter() +{ std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->EstablishAuthChannel(context_->deviceId); } -int32_t AuthRequestNegotiateState::GetStateType() { +int32_t AuthRequestNegotiateState::GetStateType() +{ return AuthState::AUTH_REQUEST_NEGOTIATE; } -void AuthRequestNegotiateState::Enter() { -// //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 +void AuthRequestNegotiateState::Enter() +{ + // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->StartNegotiate(context_->sessionId); } -int32_t AuthRequestNegotiateDoneState::GetStateType() { +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); +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) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->SendAuthRequest(context_->sessionId); } -int32_t AuthRequestReplyState::GetStateType() { +int32_t AuthRequestReplyState::GetStateType() +{ return AuthState::AUTH_REQUEST_REPLY; } -void AuthRequestReplyState::Enter() { - //1. 收到请求响应,判断用户响应结果 +void AuthRequestReplyState::Enter() +{ + // 1. 收到请求响应,判断用户响应结果 - //2. 用户授权同意 + // 2. 用户授权同意 - //3. 回调给认证实现模块,启动认证 + // 3. 回调给认证实现模块,启动认证 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->StartRespAuthProcess(); } -int32_t AuthRequestInputState::GetStateType() { +int32_t AuthRequestInputState::GetStateType() +{ return AuthState::AUTH_REQUEST_INPUT; } -void AuthRequestInputState::Enter() { -// //1. 获取用户输入 -// -// //2. 验证认证信息 +void AuthRequestInputState::Enter() +{ + // //1. 获取用户输入 + // + // //2. 验证认证信息 LOGE("DmAuthManager::AuthRequestInputState"); std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->ShowStartAuthDialog(); } -int32_t AuthRequestJoinState::GetStateType() { +int32_t AuthRequestJoinState::GetStateType() +{ return AuthState::AUTH_REQUEST_JOIN; } -void AuthRequestJoinState::Enter() { - //1. 加入群组 +void AuthRequestJoinState::Enter() +{ + // 1. 加入群组 LOGE("DmAuthManager::AuthRequestJoinState"); std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->AddMember(context_->deviceId); } -int32_t AuthRequestNetworkState::GetStateType() { +int32_t AuthRequestNetworkState::GetStateType() +{ return AuthState::AUTH_REQUEST_NETWORK; } -void AuthRequestNetworkState::Enter() { - //1. 进行组网 +void AuthRequestNetworkState::Enter() +{ + // 1. 进行组网 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->JoinNetwork(); } -int32_t AuthRequestFinishState::GetStateType() { +int32_t AuthRequestFinishState::GetStateType() +{ return AuthState::AUTH_REQUEST_FINISH; } -void AuthRequestFinishState::Enter() { - //1. 清理资源 - //2. 通知对端认证结束,并关闭认证通道 +void AuthRequestFinishState::Enter() +{ + // 1. 清理资源 + // 2. 通知对端认证结束,并关闭认证通道 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + 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 index e3c22de6c..f6b74a711 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.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, @@ -24,14 +24,15 @@ namespace DistributedHardware { void AuthResponseState::Leave() { - } -void AuthResponseState::SetAuthContext(std::shared_ptr context) { +void AuthResponseState::SetAuthContext(std::shared_ptr context) +{ context_ = std::move(context); } -std::shared_ptr AuthResponseState::GetAuthContext() { +std::shared_ptr AuthResponseState::GetAuthContext() +{ return context_; } @@ -40,11 +41,6 @@ void AuthResponseState::SetAuthManager(std::shared_ptr authManage authManager_ = std::move(authManager); } -// void AuthResponseState::SetLastState(std::shared_ptr state) -// { -// lastState_ = state; -// } - void AuthResponseState::TransitionTo(std::shared_ptr state) { LOGI("AuthRequestState:: TransitionTo"); @@ -54,8 +50,6 @@ void AuthResponseState::TransitionTo(std::shared_ptr state) return; } state->SetAuthManager(stateAuthManager); - // state->SetLastState((std::shared_ptr)this); - // lastState_ = state; stateAuthManager->SetAuthResponseState(state); state->SetAuthContext(context_); this->Leave(); @@ -70,7 +64,7 @@ int32_t AuthResponseInitState::GetStateType() void AuthResponseInitState::Enter() { LOGI("AuthResponse:: AuthResponseInitState Enter"); - //1.认证通道建立后,进入该状态 + // 1.认证通道建立后,进入该状态 } int32_t AuthResponseNegotiateState::GetStateType() @@ -80,9 +74,9 @@ int32_t AuthResponseNegotiateState::GetStateType() void AuthResponseNegotiateState::Enter() { - //1.收到协商消息后进入 + // 1.收到协商消息后进入 - //2. 获取本地加解密模块信息,并回复消 + // 2. 获取本地加解密模块信息,并回复消 std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); @@ -117,8 +111,8 @@ int32_t AuthResponseGroupState::GetStateType() void AuthResponseGroupState::Enter() { -// //1.创建群组, -// authManagerPtr_->GetHiChainConnector()->CreateGroup(); + // //1.创建群组, + // authManagerPtr_->GetHiChainConnector()->CreateGroup(); LOGI("AuthResponse:: AuthResponseGroupState Enter"); std::string groupName = "1234567890"; std::shared_ptr stateAuthManager = authManager_.lock(); @@ -136,14 +130,13 @@ int32_t AuthResponseShowState::GetStateType() void AuthResponseShowState::Enter() { - //1.委托认证实现模块进行用户交互 + // 1.委托认证实现模块进行用户交互 std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; } stateAuthManager->ShowAuthInfoDialog(); - } int32_t AuthResponseFinishState::GetStateType() @@ -153,9 +146,9 @@ int32_t AuthResponseFinishState::GetStateType() void AuthResponseFinishState::Enter() { - //1.结束UI显示 + // 1.结束UI显示 - //2.清理资源,结束状态机 + // 2.清理资源,结束状态机 std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); @@ -163,5 +156,5 @@ void AuthResponseFinishState::Enter() } stateAuthManager->AuthenticateFinish(); } -} -} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp index 06287f619..c3b12a1c8 100644 --- a/services/devicemanagerservice/src/authentication/auth_ui.cpp +++ b/services/devicemanagerservice/src/authentication/auth_ui.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/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index a10eda9bf..25e4ad0d5 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_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, @@ -28,27 +28,28 @@ 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"; - - 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 CANCEL_PICODE_DISPLAY = 1; -} - -static void TimeOut(void *data){ +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"; + +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 CANCEL_PICODE_DISPLAY = 1; +} // namespace + +static void TimeOut(void *data) +{ LOGE("time out "); - DmAuthManager *authMgr = (DmAuthManager*)data; - if (authMgr == nullptr){ + DmAuthManager *authMgr = (DmAuthManager *)data; + if (authMgr == nullptr) { LOGE("time out error"); return; } @@ -56,13 +57,14 @@ static void TimeOut(void *data){ } DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, - std::shared_ptr listener) : softbusConnector_(softbusConnector), listener_(listener) + std::shared_ptr listener) + : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmAuthManager constructor"); - //TODO: load library so for different auth type + // TODO: load library so for different auth type DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); dmConfigManager.GetAuthAdapter(authenticationMap_); - + data_ = std::shared_ptr(this); std::string pkgName = "com.ohos.devicemangagerdemo"; sessionSession_->RegisterSessionCallback(pkgName, data_); @@ -74,9 +76,10 @@ DmAuthManager::~DmAuthManager() LOGI("DmAuthManager destructor"); } -int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) +int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra) { - //TODO:检查pkgName的权限 + // TODO:检查pkgName的权限 // std::shared_ptr authentication = authenticationMap_[authType]; // if (authentication == nullptr) { @@ -85,7 +88,8 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au // } LOGE("DmAuthManager::AuthenticateDevice is"); if (authRequestState_ != nullptr) { - LOGE("DmAuthManager::AuthenticateDevice %s is request authentication.", authRequestState_->GetAuthContext()->hostPkgName.c_str()); + LOGE("DmAuthManager::AuthenticateDevice %s is request authentication.", + authRequestState_->GetAuthContext()->hostPkgName.c_str()); return DM_AUTH_BUSINESS_BUSY; } if (authResponseState_ != nullptr) { @@ -139,7 +143,8 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st /* 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)); + 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; @@ -150,16 +155,16 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st std::vector groupList; hiChainConnector_ = std::make_shared(); hiChainConnector_->GetRelatedGroups(deviceUdid, groupList); - if(groupList.size() > 0){ + 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()); + deviceId.c_str(), deviceUdid.c_str()); hiChainConnector_->DeleteGroup(groupId); } else { LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0"); return DM_FAILED; } - //groupId = authResponseContext_->groupId; + // groupId = authResponseContext_->groupId; hiChainConnector_ = nullptr; return DM_OK; } @@ -173,18 +178,18 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) LOGE("DecodeRequestAuth jsonStr error"); return DM_FAILED; } - if (!jsonObject.contains(PIN_CODE_KEY)){ + if (!jsonObject.contains(PIN_CODE_KEY)) { LOGE("err json string, first time"); return DM_FAILED; } int32_t pinCode = jsonObject[PIN_CODE_KEY]; int32_t times = 0; - if (pinCode == authResponseContext_->code && authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT){ + if (pinCode == authResponseContext_->code && authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT) { authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); - }else if (pinCode != authResponseContext_->code && times < 3) { + } else if (pinCode != authResponseContext_->code && times < 3) { times++; - //TODO input again - }else { + // TODO input again + } else { authResponseContext_->reply = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = DM_AUTH_INPUT_FAILED; authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); @@ -212,10 +217,10 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI return; } } else { - if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { hiChainConnector_ = std::make_shared(); hiChainConnector_->RegisterHiChainCallback(pkgName, data_); - authRequestContext_ ->sessionId = sessionId; + authRequestContext_->sessionId = sessionId; authRequestState_->SetAuthContext(authRequestContext_); authMessageProcessor_->SetRequestContext(authRequestContext_); authResponseContext_ = std::make_shared(); @@ -238,7 +243,7 @@ void DmAuthManager::OnSessionClosed(const std::string &pkgName, int32_t sessionI void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message) { LOGI("DmAuthManager::OnDataReceived start"); - authResponseContext_ ->sessionId = sessionId; + authResponseContext_->sessionId = sessionId; authMessageProcessor_->SetResponseContext(authResponseContext_); int32_t ret = authMessageProcessor_->ParseMessage(message); if (ret != DM_OK) { @@ -246,10 +251,10 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId return; } authResponseContext_ = authMessageProcessor_->GetResponseContext(); - if (authResponseState_ == nullptr){ + if (authResponseState_ == nullptr) { authRequestContext_ = authMessageProcessor_->GetRequestContext(); authRequestState_->SetAuthContext(authRequestContext_); - }else{ + } else { authResponseState_->SetAuthContext(authResponseContext_); } switch (authResponseContext_->msgType) { @@ -303,11 +308,11 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId //创建群组成功 //发送认证响应消息给请求端 LOGI("DmAuthManager::OnGroupCreated start"); - if (authResponseState_ == nullptr){ + if (authResponseState_ == nullptr) { LOGI("DmAuthManager::AuthenticateDevice end"); return; } - if (groupId == "{}"){ + if (groupId == "{}") { authResponseContext_->reply = DM_HICHAIN_GROUP_CREATE_FAILED; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); @@ -332,12 +337,12 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); LOGE("DmAuthManager OnMemberJoin start"); - if (authRequestState_ != nullptr){ + if (authRequestState_ != nullptr) { timerMap_[ADD_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - if (status != DM_OK || authResponseContext_->requestId != requestId){ - if (authRequestState_ == nullptr){ + if (status != DM_OK || authResponseContext_->requestId != requestId) { + if (authRequestState_ == nullptr) { // authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); - }else { + } else { authResponseContext_->reply = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = DM_AUTH_INPUT_FAILED; authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); @@ -348,11 +353,12 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) } } -void DmAuthManager::HandleAuthenticateTimeout() { - //1. 状态机走到结束状态,并清理资源 +void DmAuthManager::HandleAuthenticateTimeout() +{ + // 1. 状态机走到结束状态,并清理资源 LOGI("DmAuthManager::HandleAuthenticateTimeout start"); - if (authRequestState_ !=nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH){ - if (authResponseContext_ == nullptr){ + if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { + if (authResponseContext_ == nullptr) { authResponseContext_ = std::make_shared(); } authResponseContext_->reply = authRequestState_->GetStateType(); @@ -364,8 +370,8 @@ void DmAuthManager::HandleAuthenticateTimeout() { void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) { - //TODO:检查crypto模块是否适配 - //TODO:兼容性处理,兼容与手机的认证 + // TODO:检查crypto模块是否适配 + // TODO:兼容性处理,兼容与手机的认证 int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); if (sessionId < 0) { LOGE("OpenAuthSession failed, stop the authentication"); @@ -382,8 +388,9 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) DmDeviceInfo localDevice; softbusConnector_->GetLocalDeviceInfo(localDevice); authRequestContext_->localDeviceId = localDevice.deviceId; - int32_t ret = hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); - if (ret != DM_OK){ + int32_t ret = + hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); + if (ret != DM_OK) { LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE; authRequestContext_->reason = DM_AUTH_DEVICE_AUTHED; @@ -400,8 +407,9 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) void DmAuthManager::RespNegotiate(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); - int32_t ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); - if (ret != DM_OK){ + int32_t ret = + hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); + if (ret != DM_OK) { LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = DM_AUTH_PEER_REJECT; return; @@ -409,14 +417,13 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); - if (jsonObject.is_discarded()){ + 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){ + 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; @@ -431,7 +438,7 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id"); timerMap_[NEGOTIATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - if (authResponseContext_->cryptoSupport == true){ + if (authResponseContext_->cryptoSupport == true) { isCryptoSupport_ = true; } std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); @@ -445,14 +452,15 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) void DmAuthManager::StartAuthProcess(const int32_t &action) { - //1. 收到请求响应,判断用户响应结果 - //2. 用户授权同意 - //3. 回调给认证实现模块,启动认证 + // 1. 收到请求响应,判断用户响应结果 + // 2. 用户授权同意 + // 3. 回调给认证实现模块,启动认证 LOGI("DmAuthManager:: StartAuthProcess"); authResponseContext_->reply = action; - if (authResponseContext_->reply == DM_OK && authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM){ + if (authResponseContext_->reply == DM_OK && + authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseGroupState())); - }else { + } else { authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); @@ -463,14 +471,14 @@ void DmAuthManager::StartRespAuthProcess() { LOGI("DmAuthManager::StartRespAuthProcess StartRespAuthProcess", authResponseContext_->sessionId); timerMap_[CONFIRM_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - if (authResponseContext_->reply == 0){ + if (authResponseContext_->reply == 0) { 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 { + } else { LOGE("do not accept"); - authResponseContext_->reply = AuthState::AUTH_REQUEST_REPLY; + authResponseContext_->reply = AuthState::AUTH_REQUEST_REPLY; authRequestContext_->reason = DM_AUTH_PEER_REJECT; authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } @@ -496,7 +504,7 @@ void DmAuthManager::AddMember(const std::string &deviceId) timerMap_[ADD_TIMEOUT_TASK] = joinStartTimer; joinStartTimer->Start(ADD_TIMEOUT, TimeOut, this); int32_t ret = hiChainConnector_->AddMember(deviceId, connectInfo); - if (ret != 0){ + if (ret != 0) { return; } } @@ -511,7 +519,7 @@ std::string DmAuthManager::GetConnectAddr(std::string deviceId) void DmAuthManager::JoinNetwork() { - //TODO: + // TODO: LOGE("DmAuthManager JoinNetwork start"); timerMap_[AUTHENTICATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); authResponseContext_->reply = AuthState::AUTH_REQUEST_FINISH; @@ -522,35 +530,35 @@ void DmAuthManager::JoinNetwork() void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); - if (authRequestState_ == nullptr){ - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW){ - //todo close show pin dialog + if (authRequestState_ == nullptr) { + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { + // todo close show pin dialog } authResponseContext_ = nullptr; authResponseState_ = nullptr; authMessageProcessor_ = nullptr; - }else if(authRequestState_ != nullptr){ + } else if (authRequestState_ != nullptr) { std::string flag = ""; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - if (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN){ + if (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN) { listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, DM_AUTH_INPUT_FAILED, flag); } - if (authResponseContext_->reply == AuthState::AUTH_REQUEST_FINISH){ - listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, - DM_OK, flag); + if (authResponseContext_->reply == AuthState::AUTH_REQUEST_FINISH) { + listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, DM_OK, flag); } - listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, authRequestContext_->token, - authResponseContext_->reply, std::to_string(authRequestContext_->reason)); + listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, + authRequestContext_->token, authResponseContext_->reply, + std::to_string(authRequestContext_->reason)); sessionSession_->UnRegisterSessionCallback(authRequestContext_->hostPkgName); softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); - if (!timerMap_.empty()){ - for(auto & iter : timerMap_) { + if (!timerMap_.empty()) { + for (auto &iter : timerMap_) { iter.second->Stop(SESSION_CANCEL_TIMEOUT); } timerMap_.clear(); @@ -569,9 +577,8 @@ void DmAuthManager::CancelDisplay() nlohmann::json jsonObj; jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PICODE_DISPLAY; std::string paramJson = jsonObj.dump(); - std::string pkgName = "com.ohos.devicemanagerui"; + std::string pkgName = "com.ohos.devicemanagerui"; listener_->OnFaCall(pkgName, paramJson); - } int32_t DmAuthManager::GeneratePincode() @@ -582,23 +589,23 @@ int32_t DmAuthManager::GeneratePincode() void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) { LOGI("DmAuthManager::GetIsCryptoSupport start"); - if (authResponseState_ == nullptr){ + if (authResponseState_ == nullptr) { isCryptoSupport = false; return; } - if (authRequestState_ == nullptr){ - if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE){ + if (authRequestState_ == nullptr) { + if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { isCryptoSupport = false; return; } - }else { + } else { if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE){ + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { isCryptoSupport = false; return; + } } - } - + isCryptoSupport = isCryptoSupport_; } @@ -639,7 +646,6 @@ void DmAuthManager::ShowStartAuthDialog() } dmAbilityMgr_ = std::make_shared(); ptr->StartAuth(dmAbilityMgr_);*/ - } int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) @@ -663,5 +669,5 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) } 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 index 6d92b2d34..cd4d1e76b 100644 --- a/services/devicemanagerservice/src/config/config_manager.cpp +++ b/services/devicemanagerservice/src/config/config_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, @@ -23,12 +23,12 @@ namespace OHOS { namespace DistributedHardware { -void from_json(const nlohmann::json& jsonObject, AdapterSoLoadInfo& soLoadInfo) +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; + return; } jsonObject["name"].get_to(soLoadInfo.name); @@ -39,13 +39,13 @@ void from_json(const nlohmann::json& jsonObject, AdapterSoLoadInfo& soLoadInfo) jsonObject["soPath"].get_to(soLoadInfo.soPath); } -void from_json(const nlohmann::json& jsonObject, AuthSoLoadInfo& soLoadInfo) +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; + return; } jsonObject["name"].get_to(soLoadInfo.name); @@ -57,7 +57,7 @@ void from_json(const nlohmann::json& jsonObject, AuthSoLoadInfo& soLoadInfo) jsonObject["soPath"].get_to(soLoadInfo.soPath); } -DmConfigManager& DmConfigManager::GetInstance() +DmConfigManager &DmConfigManager::GetInstance() { static DmConfigManager instance; return instance; @@ -67,23 +67,21 @@ DmConfigManager::DmConfigManager() { LOGI("DmConfigManager constructor"); do { - nlohmann::json adapterJsonObject = nlohmann::json::parse(adapterJsonConfigString, nullptr, false); + 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(); + } + 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) { + 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; } @@ -98,23 +96,21 @@ DmConfigManager::DmConfigManager() } while (0); do { - nlohmann::json authJsonObject = nlohmann::json::parse(authJsonConfigString, nullptr, false); + 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(); + 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) { + 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; } @@ -140,7 +136,6 @@ DmConfigManager::~DmConfigManager() 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); @@ -151,36 +146,32 @@ DmConfigManager::~DmConfigManager() LOGI("DmAdapterManager destructor"); } -std::shared_ptr DmConfigManager::GetDecisionAdapter(const std::string& soName) +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) { + 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()); + 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) { @@ -192,7 +183,7 @@ std::shared_ptr DmConfigManager::GetDecisionAdapter(const std: return decisionAdapterPtr_[soName]; } -std::shared_ptr DmConfigManager::GetProfileAdapter(const std::string& soName) +std::shared_ptr DmConfigManager::GetProfileAdapter(const std::string &soName) { if (soName.empty()) { LOGE("soName size is zero"); @@ -204,24 +195,21 @@ std::shared_ptr DmConfigManager::GetProfileAdapter(const std::s 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) { + 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()); + 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) { @@ -233,7 +221,7 @@ std::shared_ptr DmConfigManager::GetProfileAdapter(const std::s return profileAdapterPtr_[soName]; } -std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::string& soName) +std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::string &soName) { if (soName.empty()) { LOGE("soName size is zero"); @@ -245,7 +233,7 @@ std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::str 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()) { @@ -255,10 +243,10 @@ std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::str 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) { + 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()); + if (so_handle == nullptr) { + LOGE("load crypto so %s failed", soName.c_str()); return nullptr; } } @@ -275,7 +263,7 @@ std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::str return cryptoAdapterPtr_[soName]; } -void DmConfigManager::GetAuthAdapter(std::map>& authAdapter) +void DmConfigManager::GetAuthAdapter(std::map> &authAdapter) { authAdapter.clear(); for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) { @@ -287,12 +275,12 @@ void DmConfigManager::GetAuthAdapter(std::mapsecond).soPath + (iter->second).soName; so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); - if (so_handle == nullptr) { + 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()); + if (so_handle == nullptr) { + LOGE("load auth so %s failed", (iter->second).soName.c_str()); continue; - } + } } dlerror(); @@ -303,7 +291,7 @@ void DmConfigManager::GetAuthAdapter(std::map iAuthentication(func()); - authAdapter[iter->first] = iAuthentication; + authAdapter[iter->first] = iAuthentication; LOGI("so name: %s, auth type: %d", (iter->second).soName.c_str(), iter->first); } } diff --git a/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp b/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp index 06386d2b9..91e7fba25 100644 --- a/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.cpp +++ b/services/devicemanagerservice/src/dependency/commonevent/event_manager_adapt.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, @@ -28,28 +28,28 @@ std::list DmCommonEventManager::callbackQueue_; std::mutex DmCommonEventManager::callbackQueueMutex_; std::condition_variable DmCommonEventManager::notEmpty_; -DmCommonEventManager& DmCommonEventManager::GetInstance() +DmCommonEventManager &DmCommonEventManager::GetInstance() { static DmCommonEventManager instance; - std::call_once(onceFlag_, [] { + 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(); }); + notEmpty_.wait(callbackQueueLock, [] { return !callbackQueue_.empty(); }); CommomEventCallback funcPrt = callbackQueue_.front(); - funcPrt();/////// + funcPrt(); callbackQueue_.pop_front(); } } -bool DmCommonEventManager::SubscribeServiceEvent(const std::string& event, CommomEventCallback callback) +bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, CommomEventCallback callback) { LOGI("Subscribe event: %s", event.c_str()); if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end()) { @@ -76,10 +76,10 @@ bool DmCommonEventManager::SubscribeServiceEvent(const std::string& event, Commo LOGE("Subscribe service event failed: %s", event.c_str()); return false; } - } -bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string& event) { +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()); @@ -98,7 +98,7 @@ bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string& event) { } } -DmCommonEventManager::~DmCommonEventManager() +DmCommonEventManager::~DmCommonEventManager() { for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { bool unsubscribeResult = CommonEventManager::UnSubscribeCommonEvent(iter->second); @@ -106,7 +106,7 @@ DmCommonEventManager::~DmCommonEventManager() LOGI("Unsubscribe service event success: %s", iter->first.c_str()); } } -} +} void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) { @@ -128,8 +128,8 @@ void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData } } } - -void DmCommonEventManager::EventSubscriber::addEventCallback(const std::string& event, CommomEventCallback callback) + +void DmCommonEventManager::EventSubscriber::addEventCallback(const std::string &event, CommomEventCallback callback) { std::unique_lock callbackLock(callbackLock_); if (dmEventCallback_.find(event) == dmEventCallback_.end()) { @@ -138,14 +138,14 @@ void DmCommonEventManager::EventSubscriber::addEventCallback(const std::string& } } -void DmCommonEventManager::EventSubscriber::deleteEventCallback(const std::string& event) +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()); + dmEventCallback_.erase(event); + LOGI("delete event failed: %s", event.c_str()); } } - + } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/eventbus/event_bus.cpp b/services/devicemanagerservice/src/dependency/eventbus/event_bus.cpp deleted file mode 100644 index 1512d73ef..000000000 --- a/services/devicemanagerservice/src/dependency/eventbus/event_bus.cpp +++ /dev/null @@ -1,24 +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 "event_bus.h" - - -namespace OHOS { -namespace DistributedHardware { -EventBus *EventBus::instance_ = nullptr; -std::shared_ptr EventBus::eventBusHandler_ = nullptr; -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 270ee7363..83500dc9e 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.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, @@ -31,7 +31,7 @@ namespace OHOS { namespace DistributedHardware { -void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) +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(); @@ -59,12 +59,10 @@ std::map> HiChainConnect HiChainConnector::HiChainConnector() { LOGI("HiChainConnector::constructor"); - deviceAuthCallback_ = { - .onTransmit = nullptr, - .onFinish = HiChainConnector::onFinish, - .onError = HiChainConnector::onError, - .onRequest = HiChainConnector::onRequest - }; + deviceAuthCallback_ = {.onTransmit = nullptr, + .onFinish = HiChainConnector::onFinish, + .onError = HiChainConnector::onError, + .onRequest = HiChainConnector::onRequest}; InitDeviceAuthService(); deviceGroupManager_ = GetGmInstance(); if (deviceGroupManager_ == nullptr) { @@ -78,16 +76,17 @@ HiChainConnector::HiChainConnector() HiChainConnector::~HiChainConnector() { LOGI("HiChainConnector::destructor."); - //TODO:delete resource } -int32_t HiChainConnector::RegisterHiChainCallback(const std::string &pkgName, std::shared_ptr callback) +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) { +int32_t HiChainConnector::UnRegisterHiChainCallback(const std::string &pkgName) +{ hiChainConnectorCallbackMap_.erase(pkgName); return DM_OK; } @@ -113,7 +112,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou 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()); + 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; @@ -176,7 +175,6 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectIn 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"); @@ -198,9 +196,9 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectIn 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()); + 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; @@ -215,13 +213,13 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const LOGI("HiChainConnector::onFinish reqId:%lld, operation:%d", requestId, operationCode); if (operationCode == GroupOperationCode::MEMBER_JOIN) { LOGI("Add Member To Group success"); - for(auto & iter : hiChainConnectorCallbackMap_) { + for (auto &iter : hiChainConnectorCallbackMap_) { iter.second->OnMemberJoin(requestId, DM_OK); } } if (operationCode == GroupOperationCode::GROUP_CREATE) { LOGI("Create group success"); - for(auto & iter : hiChainConnectorCallbackMap_) { + for (auto &iter : hiChainConnectorCallbackMap_) { iter.second->OnGroupCreated(requestId, data); } } @@ -233,21 +231,19 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const } } -void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, - const char *errorReturn) +void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn) { (void)errorReturn; - LOGI("HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", - requestId, operationCode, errorCode); + 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_) { + for (auto &iter : hiChainConnectorCallbackMap_) { iter.second->OnMemberJoin(requestId, DM_FAILED); } } if (operationCode == GroupOperationCode::GROUP_CREATE) { LOGE("Create group failed"); - for(auto & iter : hiChainConnectorCallbackMap_) { + for (auto &iter : hiChainConnectorCallbackMap_) { iter.second->OnGroupCreated(requestId, "{}"); } } @@ -266,7 +262,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, cons return nullptr; } int32_t pinCode = 0; - for(auto & iter : hiChainConnectorCallbackMap_) { + for (auto &iter : hiChainConnectorCallbackMap_) { pinCode = iter.second->GetPinCode(); } nlohmann::json jsonObj; @@ -290,14 +286,13 @@ 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_) { + for (auto &iter : hiChainConnectorCallbackMap_) { connectAddr = iter.second->GetConnectAddr(deviceId); } - LOGE("HiChainConnector::GetConnectPara get addrInfo"); + LOGE("HiChainConnector::GetConnectPara get addrInfo"); nlohmann::json jsonObject = nlohmann::json::parse(connectAddr, nullptr, false); if (jsonObject.is_discarded()) { LOGE("DecodeRequestAuth jsonStr error"); @@ -313,8 +308,8 @@ void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vectorgetRelatedGroups(DM_PKG_NAME.c_str(), deviceId.c_str(), - &returnGroups, &groupNum); + 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; @@ -364,7 +359,7 @@ int32_t HiChainConnector::IsDevicesInGroup(std::string hostDevice, std::string p GetRelatedGroups(peerDevice, peerGroupInfoList); for (auto &hostGroupInfo : hostGroupInfoList) { for (auto &peerGroupInfo : peerGroupInfoList) { - if (hostGroupInfo.groupId == peerGroupInfo.groupId && hostGroupInfo.groupName == peerGroupInfo.groupName){ + if (hostGroupInfo.groupId == peerGroupInfo.groupId && hostGroupInfo.groupName == peerGroupInfo.groupName) { LOGE("these are authenticated"); return DM_FAILED; } @@ -400,14 +395,13 @@ void HiChainConnector::SyncGroups(std::string deviceId, std::vector 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()); + 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()); + 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; @@ -426,5 +420,5 @@ void HiChainConnector::DeleteGroup(std::string &groupId) 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 index 228983edf..7fea2e896 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.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, @@ -37,24 +37,19 @@ std::map> SoftbusConnector::discoveryDe std::map> SoftbusConnector::stateCallbackMap_ = {}; std::map> SoftbusConnector::discoveryCallbackMap_ = {}; - -IPublishCallback SoftbusConnector::softbusPublishCallback_ = { - .OnPublishSuccess = SoftbusConnector::OnPublishSuccess, - .OnPublishFail = SoftbusConnector::OnPublishFail - }; +IPublishCallback SoftbusConnector::softbusPublishCallback_ = {.OnPublishSuccess = SoftbusConnector::OnPublishSuccess, + .OnPublishFail = SoftbusConnector::OnPublishFail}; IDiscoveryCallback SoftbusConnector::softbusDiscoveryCallback_ = { .OnDeviceFound = SoftbusConnector::OnSoftbusDeviceFound, .OnDiscoverFailed = SoftbusConnector::OnSoftbusDiscoveryFailed, - .OnDiscoverySuccess = SoftbusConnector::OnSoftbusDiscoverySuccess -}; - + .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 -}; + .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged}; SoftbusConnector::SoftbusConnector() { @@ -62,13 +57,13 @@ SoftbusConnector::SoftbusConnector() Init(); } -SoftbusConnector::~SoftbusConnector() { +SoftbusConnector::~SoftbusConnector() +{ LOGI("SoftbusConnector destructor"); } int32_t SoftbusConnector::Init() { - //TODO:optimize implementation later use semaphore instead int32_t ret; int32_t retryTimes = 0; do { @@ -81,7 +76,6 @@ int32_t SoftbusConnector::Init() } while (ret != DM_OK); LOGI("RegNodeDeviceStateCb success."); - // TODO:check system properties first PublishInfo dmPublishInfo; dmPublishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE; @@ -90,11 +84,11 @@ int32_t SoftbusConnector::Init() 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()); + 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_); @@ -109,7 +103,7 @@ int32_t SoftbusConnector::Init() } 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); + ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); if (ret == DM_OK) { publishStatus = NOT_ALLOW_BE_DISCOVERY; } @@ -121,7 +115,8 @@ int32_t SoftbusConnector::Init() return ret; } -int32_t SoftbusConnector::RegisterSoftbusDiscoveryCallback(const std::string &pkgName, const std::shared_ptr callback) +int32_t SoftbusConnector::RegisterSoftbusDiscoveryCallback(const std::string &pkgName, + const std::shared_ptr callback) { discoveryCallbackMap_.emplace(pkgName, callback); return DM_OK; @@ -133,7 +128,8 @@ int32_t SoftbusConnector::UnRegisterSoftbusDiscoveryCallback(const std::string & return DM_OK; } -int32_t SoftbusConnector::RegisterSoftbusStateCallback(const std::string &pkgName, const std::shared_ptr callback) +int32_t SoftbusConnector::RegisterSoftbusStateCallback(const std::string &pkgName, + const std::shared_ptr callback) { stateCallbackMap_.emplace(pkgName, callback); return DM_OK; @@ -200,39 +196,6 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) subscribeInfo.capability = dmSubscribeInfo.capability; subscribeInfo.capabilityData = nullptr; subscribeInfo.dataLen = 0; - - //TODO:check these later - // 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); - // } - // LOGD("StartDiscovery, pkgName: %s, subscribeId %d, prefix %d, origin %d", - // pkgName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); - // LOGD("Capability: %s", subinfo->info.capability); int32_t ret = ::StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_); if (ret != 0) { LOGE("StartDiscovery failed with ret %d.", ret); @@ -253,8 +216,8 @@ int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) return DM_OK; } -int32_t SoftbusConnector::GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, - uint8_t *info, int32_t infoLen) +int32_t SoftbusConnector::GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info, + int32_t infoLen) { LOGI("GetNodeKeyInfoByNetworkId begin"); @@ -290,8 +253,8 @@ bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) 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)); + 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; @@ -306,7 +269,8 @@ bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId) return bDeviceOnline; } -std::shared_ptr SoftbusConnector::GetSoftbusSession() { +std::shared_ptr SoftbusConnector::GetSoftbusSession() +{ return softbusSession_; } @@ -401,11 +365,11 @@ void SoftbusConnector::CovertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBa { (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) { + 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) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DM_OK) { LOGE("copy data failed"); } dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId; @@ -415,11 +379,11 @@ void SoftbusConnector::CovertDeviceInfoToDmDevice(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))) != DM_OK) { + 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) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { LOGE("copy data failed"); } dmDeviceInfo.deviceTypeId = deviceInfo.devType; @@ -443,18 +407,18 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) return; } - if (discoveryDeviceInfoMap_.empty()){ + if (discoveryDeviceInfoMap_.empty()) { return; } DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); - for (auto & iter : stateCallbackMap_) { + for (auto &iter : stateCallbackMap_) { iter.second->OnDeviceOnline(iter.first, dmDeviceInfo); } - //remove the discovery node map + // 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)); + 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; @@ -472,7 +436,7 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) } DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); - for (auto & iter : stateCallbackMap_) { + for (auto &iter : stateCallbackMap_) { iter.second->OnDeviceOffline(iter.first, dmDeviceInfo); } } @@ -480,12 +444,11 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) { LOGI("SoftbusConnector::OnSoftbusDeviceInfoChanged."); - //TODO: } void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) { - if (device == nullptr) { + if (device == nullptr) { LOGE("device is null"); return; } @@ -517,7 +480,7 @@ void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFa { 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_) { + for (auto &iter : discoveryCallbackMap_) { iter.second->OnDiscoveryFailed(iter.first, originId, (int32_t)failReason); } } @@ -526,7 +489,7 @@ 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_) { + for (auto &iter : discoveryCallbackMap_) { iter.second->OnDiscoverySuccess(iter.first, originId); } } @@ -548,7 +511,7 @@ void SoftbusConnector::OnParameterChgCallback(const char *key, const char *value } 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); + int32_t ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); if (ret == DM_OK) { publishStatus = NOT_ALLOW_BE_DISCOVERY; } diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 2e6fa04c8..572d1d28f 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.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, @@ -27,17 +27,15 @@ std::map> SoftbusSession:: SoftbusSession::SoftbusSession() { - ISessionListener sessionListener = { - .OnSessionOpened = SoftbusSession::OnSessionOpened, - .OnSessionClosed = SoftbusSession::OnSessionClosed, - .OnBytesReceived = SoftbusSession::OnBytesReceived, - .OnMessageReceived = nullptr, - .OnStreamReceived = nullptr - }; + 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 { + } else { LOGI("CreateSessionServer ok"); } } @@ -48,7 +46,7 @@ SoftbusSession::~SoftbusSession() } int32_t SoftbusSession::RegisterSessionCallback(const std::string &pkgName, - std::shared_ptr callback) + std::shared_ptr callback) { sessionCallbackMap_[pkgName] = callback; return DM_OK; @@ -91,8 +89,7 @@ void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) 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()); + LOGI("GetPeerDeviceId success for session:%d, peerDeviceId:%s", sessionId, GetAnonyString(peerDevId).c_str()); return; } LOGE("GetPeerDeviceId failed for session:%d", sessionId); @@ -108,9 +105,9 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) return DM_FAILED; } int32_t msgType = jsonObject[TAG_TYPE]; - LOGI("AuthMessageProcessor::ParseAuthRequestMessage msgType = %d",msgType); + LOGI("AuthMessageProcessor::ParseAuthRequestMessage msgType = %d", msgType); bool isCryptoSupport = false; - for (auto & iter : sessionCallbackMap_) { + for (auto &iter : sessionCallbackMap_) { iter.second->GetIsCryptoSupport(isCryptoSupport); } if (isCryptoSupport) { @@ -119,20 +116,10 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) LOGE("SendData: malloc memory failed"); return DM_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 != DM_OK || outLen > MSG_MAX_SIZE) { - // LOGE("MbedtlsEncrypt data failed"); - // free(buf); - // return ENCRYPT_UTILS_AES_GCM_ENCRYPT_FAILED; - // } - // int32_t ret = SendBytes(sessionId, buf, strlen(buf)); free(buf); } int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); - if (ret != DM_OK) - { + if (ret != DM_OK) { LOGE("SendData Start failed"); return DM_FAILED; } @@ -143,7 +130,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) { int32_t sessionSide = GetSessionSide(sessionId); - for (auto & iter : sessionCallbackMap_) { + for (auto &iter : sessionCallbackMap_) { iter.second->OnSessionOpened(iter.first, sessionId, sessionSide, result); } LOGI("OnSessionOpened, success:"); @@ -153,9 +140,6 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) void SoftbusSession::OnSessionClosed(int32_t sessionId) { LOGI("OnSessionClosed, sessionId:%d", sessionId); - // for (auto & iter : sessionCallbackMap_) { - // iter.second->OnSessionClosed(iter.first, sessionId); - // } } void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) @@ -166,31 +150,24 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 return; } bool isCryptoSupport = false; - for (auto & iter : sessionCallbackMap_) { + for (auto &iter : sessionCallbackMap_) { iter.second->GetIsCryptoSupport(isCryptoSupport); } - if (isCryptoSupport){ + if (isCryptoSupport) { uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); if (buf == nullptr) { LOGE("SendMsg: malloc memory failed"); return; } - // int32_t outLen = 0; - // int32_t ret = EncryptUtils::MbedtlsDecrypt((const uint8_t*)data, dataLen, buf, dataLen, &outLen); - // if (ret != DM_OK || outLen > (int32_t)dataLen) { - // LOGE("MbedtlsDecrypt data failed"); - // free(buf); - // return; - // } std::string message = (char *)buf; - for (auto & iter : sessionCallbackMap_) { + for (auto &iter : sessionCallbackMap_) { iter.second->OnDataReceived(iter.first, sessionId, message); } free(buf); } - char *dataChar = (char *)data; + char *dataChar = (char *)data; std::string message = dataChar; - for (auto & iter : sessionCallbackMap_) { + for (auto &iter : sessionCallbackMap_) { iter.second->OnDataReceived(iter.first, sessionId, message); } LOGI("OnBytesReceived completed"); diff --git a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp index a9e5518ea..dc9a82b9c 100644 --- a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/dependency/timer/dm_timer.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, @@ -59,7 +59,7 @@ DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) } mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; - mThread_ = std::thread(&DmTimer::WiteforTimeout, this); + mThread_ = std::thread(&DmTimer::WaitForTimeout, this); mThread_.detach(); return mStatus_; @@ -80,7 +80,7 @@ void DmTimer::Stop(int32_t code) return; } -void DmTimer::WiteforTimeout() +void DmTimer::WaitForTimeout() { LOGI("DmTimer %s start timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); @@ -149,5 +149,5 @@ void DmTimer::Release() 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 index 9085d5579..e5fca1b79 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.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, @@ -31,7 +31,6 @@ int32_t DeviceManagerService::Init() LOGE("Init failed, singleton cannot be initialized multiple times"); return DM_INT_MULTIPLE; } - if (softbusConnector_ == nullptr) { softbusConnector_ = std::make_shared(); if (softbusConnector_ == nullptr) { @@ -39,7 +38,6 @@ int32_t DeviceManagerService::Init() return DM_MAKE_SHARED_FAIL; } } - if (listener_ == nullptr) { listener_ = std::make_shared(); if (softbusConnector_ == nullptr) { @@ -47,15 +45,13 @@ int32_t DeviceManagerService::Init() return DM_MAKE_SHARED_FAIL; } } - if (deviceInfoMgr_ == nullptr) { deviceInfoMgr_ = std::make_shared(softbusConnector_); - if (deviceInfoMgr_ == nullptr) { + 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) { @@ -63,7 +59,6 @@ int32_t DeviceManagerService::Init() return DM_MAKE_SHARED_FAIL; } } - if (discoveryMgr_ == nullptr) { discoveryMgr_ = std::make_shared(softbusConnector_, listener_); if (discoveryMgr_ == nullptr) { @@ -71,27 +66,25 @@ int32_t DeviceManagerService::Init() return DM_MAKE_SHARED_FAIL; } } - - if(authMgr_ == nullptr) { + if (authMgr_ == nullptr) { authMgr_ = std::make_shared(softbusConnector_, listener_); if (authMgr_ == nullptr) { LOGE("Init failed, authMgr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } } - 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) +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; @@ -105,17 +98,16 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); return DM_NOT_INIT; } - return deviceInfoMgr_->GetLocalDeviceInfo(info); } -int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) +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; @@ -129,7 +121,6 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui 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; @@ -137,18 +128,17 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); } -int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) +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; @@ -162,7 +152,6 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c 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; @@ -180,8 +169,6 @@ int32_t DeviceManagerService::VerifyAuthentication(const std::string &authParam) LOGE("VerifyAuthentication failed, singleton not init or init fail"); return DM_NOT_INIT; } - - return authMgr_->VerifyAuthentication(authParam); } @@ -201,7 +188,6 @@ int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t act LOGE("SetUserOperation failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - authMgr_->StartAuthProcess(action); return DM_OK; } diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 6d9df3433..1b557fb7d 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.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, @@ -30,7 +30,8 @@ namespace OHOS { namespace DistributedHardware { -void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) +void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, + const DmDeviceInfo &info) { LOGI("OnDeviceStateChange"); std::shared_ptr pReq = std::make_shared(); @@ -41,10 +42,11 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } -void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) +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()); + 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(); @@ -54,7 +56,8 @@ void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uin ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } -void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) +void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, + int32_t failedReason) { LOGI("OnDiscoveryFailed"); std::shared_ptr pReq = std::make_shared(); @@ -78,10 +81,10 @@ void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName 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) +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()); + 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(); @@ -89,20 +92,18 @@ void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, cons pReq->SetDeviceId(deviceId); pReq->SetToken(token); pReq->SetStatus(status); -// pReq->SetReason(reason); + // 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) +void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, const std::string &flag) { -// LOGI("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(deviceId); pReq->SetResult(resultCode); -// pReq->SetFlag(flag); ipcServerListener_.SendAll(SERVER_VERIFY_AUTH_RESULT, pReq, pRsp); } diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index 9a28fddba..b56c7ff7a 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_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, @@ -20,12 +20,14 @@ namespace OHOS { namespace DistributedHardware { -DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr& softbusConnectorPtr) : softbusConnector_(softbusConnectorPtr) +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 DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) { int32_t ret = softbusConnector_->GetTrustedDeviceList(deviceList); if (ret != DM_OK) { @@ -35,13 +37,12 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co if (!extra.empty() && !deviceList.empty()) { std::string soName; - DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(soName); if (decisionAdapter != nullptr) { - //decisionAdapter->FilterDeviceList(deviceList, extra); + decisionAdapter->FilterDeviceList(deviceList, extra); } else { - //LOGE("GetTrustedDeviceList decisionAdapter is nullptr"); - //return DM_POINT_NULL; + LOGE("GetTrustedDeviceList decisionAdapter is nullptr"); } } @@ -52,7 +53,7 @@ int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info) { int32_t ret = softbusConnector_->GetLocalDeviceInfo(info); if (ret != DM_OK) { - LOGE("GetLocalDeviceInfo failed"); + LOGE("GetLocalDeviceInfo failed"); return ret; } return DM_OK; diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 1a0ab70f0..81b30c3f7 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_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, @@ -21,7 +21,8 @@ namespace OHOS { namespace DistributedHardware { DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnector, - std::shared_ptr listener) : softbusConnector_(softbusConnector), listener_(listener) + std::shared_ptr listener) + : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmDeviceStateManager constructor"); softbusConnector_->RegisterSoftbusStateCallback("", std::shared_ptr(this)); @@ -33,38 +34,36 @@ DmDeviceStateManager::~DmDeviceStateManager() softbusConnector_->UnRegisterSoftbusStateCallback(""); } -void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) { +void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) +{ std::string soName; - DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); - if (profileAdapter == nullptr){ + if (profileAdapter == nullptr) { LOGE("OnDeviceOnline profile adapter is null"); - // return; } DmDeviceState state = DEVICE_STATE_ONLINE; - // profileAdapter->RegisterProfileListener(); listener_->OnDeviceStateChange(pkgName, state, info); } -void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) { +void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) +{ std::string soName; - DmAdapterManager& adapterMgrPtr = DmAdapterManager::GetInstance(); + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); - if (profileAdapter == nullptr){ + if (profileAdapter == nullptr) { LOGE("OnDeviceOnline profile adapter is null"); - // return; } DmDeviceState state = DEVICE_STATE_OFFLINE; - // profileAdapter->UnRegisterProfileListener(); listener_->OnDeviceStateChange(pkgName, state, info); } -void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) { - +void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) +{ } -void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info) { - -} -} +void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info) +{ } +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 6dfa1f368..4e6a7fd82 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_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, @@ -20,14 +20,15 @@ namespace OHOS { namespace DistributedHardware { -namespace{ - std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout"; - int32_t DISCOVERY_TIMEOUT = 120; -} -static void TimeOut(void *data){ +namespace { +std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout"; +int32_t DISCOVERY_TIMEOUT = 120; +} // namespace +static void TimeOut(void *data) +{ LOGE("time out "); - DmDiscoveryManager *discoveryMgr = (DmDiscoveryManager*)data; - if (discoveryMgr == nullptr){ + DmDiscoveryManager *discoveryMgr = (DmDiscoveryManager *)data; + if (discoveryMgr == nullptr) { LOGE("time out error"); return; } @@ -35,7 +36,8 @@ static void TimeOut(void *data){ } DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnector, - std::shared_ptr listener) : softbusConnector_(softbusConnector), listener_(listener) + std::shared_ptr listener) + : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmDiscoveryManager constructor"); } @@ -45,16 +47,17 @@ DmDiscoveryManager::~DmDiscoveryManager() LOGI("DmDiscoveryManager destructor"); } -int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) +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()); + LOGD("DmDiscoveryManager::StartDeviceDiscovery stop preview discovery first, the preview pkgName is %s", + discoveryQueue_.front().c_str()); StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); - // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); } } discoveryQueue_.push(pkgName); @@ -74,37 +77,35 @@ int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint return softbusConnector_->StopDiscovery(subscribeId); } -void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) { +void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) +{ LOGI("DmDiscoveryManager::OnDeviceFound deviceId=%s", GetAnonyString(info.deviceId).c_str()); - // std::string pkgName = discoveryQueue_.front(); auto iter = discoveryContextMap_.find(pkgName); if (iter == discoveryContextMap_.end()) { LOGE("subscribeId not found by pkgName %s", GetAnonyString(pkgName).c_str()); return; } - //TODO:获取Extra信息判断是否进行筛选,完成后上报设备信息 listener_->OnDeviceFound(pkgName, iter->second.subscribeId, info); } -void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) { +void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) +{ LOGI("DmDiscoveryManager::OnDiscoveryFailed subscribeId=%d reason=%d", subscribeId, failedReason); - // std::string pkgName = discoveryQueue_.front(); - // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); StopDeviceDiscovery(pkgName, subscribeId); listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); } -void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) { +void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +{ LOGI("DmDiscoveryManager::OnDiscoverySuccess subscribeId=%d", subscribeId); -// std::string pkgName = discoveryQueue_.front(); discoveryContextMap_[pkgName].subscribeId = subscribeId; listener_->OnDiscoverySuccess(pkgName, subscribeId); } -void DmDiscoveryManager::HandleDiscoveryTimeout() { +void DmDiscoveryManager::HandleDiscoveryTimeout() +{ LOGI("DmDiscoveryManager::HandleDiscoveryTimeout"); StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); - // softbusConnector_->UnRegisterSoftbusDiscoveryCallback(discoveryQueue_.front()); -} -} } +} // 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 index 89830c1bb..c70fbda0b 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/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, @@ -28,8 +28,8 @@ namespace OHOS { namespace DistributedHardware { -ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +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(); @@ -49,8 +49,8 @@ ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +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(); @@ -70,8 +70,8 @@ ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, IpcIo &reply, std::shared_ptr return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +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(); @@ -91,8 +91,8 @@ ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +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(); @@ -116,10 +116,11 @@ ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr p return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_VERIFY_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, - uint8_t *buffer, size_t buffLen) +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::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string deviceId = pReq->GetDeviceId(); int32_t result = pReq->GetResult(); @@ -182,7 +183,7 @@ ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) std::string extra = (const char *)IpcIoPopString(&req, nullptr); uint32_t size = 0; - DmSubscribeInfo *pDmSubscribeInfo = (DmSubscribeInfo*)IpcIoPopFlatObj(&req, &size); + DmSubscribeInfo *pDmSubscribeInfo = (DmSubscribeInfo *)IpcIoPopFlatObj(&req, &size); int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo, extra); IpcIoPushInt32(&reply, ret); } @@ -233,12 +234,11 @@ ON_IPC_SERVER_CMD(SERVER_USER_AUTH_OPERATION, IpcIo &req, IpcIo &reply) 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) +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(); @@ -248,7 +248,7 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr pBaseReq, Ip return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, IpcIo& request, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, IpcIo &request, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp index 02a41e89f..0dbc01b96 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.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/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp index e9fbed7b3..c223a0104 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.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/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp index 7bb471cf0..db8dff1e4 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.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, @@ -27,7 +27,6 @@ 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"); diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp index bb7030e20..87e61ac79 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_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, @@ -31,10 +31,10 @@ #include "ipc_server_listenermgr.h" namespace { - const int32_t WAIT_FOR_SERVER = 2; - const int32_t STACK_SIZE = 0x1000; - const int32_t QUEUE_SIZE = 32; -} +const int32_t WAIT_FOR_SERVER = 2; +const int32_t STACK_SIZE = 0x1000; +const int32_t QUEUE_SIZE = 32; +} // namespace using namespace OHOS::DistributedHardware; @@ -181,8 +181,7 @@ static TaskConfig GetTaskConfig(Service *service) return config; } -static int32_t OnRemoteRequest(IServerProxy *iProxy, int32_t funcId, void *origin, - IpcIo *req, IpcIo *reply) +static int32_t OnRemoteRequest(IServerProxy *iProxy, int32_t funcId, void *origin, IpcIo *req, IpcIo *reply) { LOGI("Receive funcId:%d", funcId); (void)origin; diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index b01d7907a..f773523c4 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/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, @@ -152,7 +152,8 @@ ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, MessageParcel &reply, 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 deviceId = pReq->GetDeviceId(); int32_t result = pReq->GetResult(); @@ -182,7 +183,7 @@ ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::share return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) +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(); @@ -191,15 +192,14 @@ ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr pBaseReq, Me LOGE("write pkgName failed"); return DM_FLATTEN_OBJECT; } - if (!data.WriteString(paramJson)) - { + 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) +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; @@ -210,7 +210,6 @@ 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()); - //TODO: std::vector deviceList; int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); int32_t infoNum = deviceList.size(); @@ -219,8 +218,8 @@ ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) LOGE("write infoNum failed"); return DM_WRITE_FAILED; } - if (!deviceList.empty()){ - for (; !deviceList.empty();){ + if (!deviceList.empty()) { + for (; !deviceList.empty();) { deviceInfo = deviceList.back(); deviceList.pop_back(); @@ -296,10 +295,9 @@ ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); std::string extra = data.ReadString(); - std::string deviceId = 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)) { @@ -310,20 +308,18 @@ ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) return DM_OK; } -ON_IPC_CMD(UNAUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) { +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; + return DM_OK; } ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) @@ -332,30 +328,32 @@ ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) std::string authPara = data.ReadString(); int32_t result = DeviceManagerService::GetInstance().VerifyAuthentication(authPara); if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return DM_WRITE_FAILED; + 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_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(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { +ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) +{ std::string packName = data.ReadString(); DmAuthParam authParam; int32_t ret = DM_OK; @@ -378,14 +376,12 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { 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; } @@ -394,7 +390,6 @@ 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; diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp index 2f3eb73dc..a7989564e 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_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, @@ -31,7 +31,6 @@ int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr r LOGE("remote service null"); return DM_POINT_NULL; } - MessageParcel data; MessageParcel reply; MessageOption option; diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp index 597f07487..9176b9291 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.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/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp index 10043dfa7..6d1abdabb 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_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, @@ -29,7 +29,6 @@ #include "dm_log.h" #include "device_manager_service.h" -// #include "ipc_server_adapter.h" #include "ipc_cmd_register.h" #include "device_manager_impl.h" @@ -70,12 +69,7 @@ bool IpcServerStub::Init() } registerToService_ = true; } - - std::thread { - [] { - DeviceManagerService::GetInstance().Init(); - } - }.detach(); + std::thread{[] { DeviceManagerService::GetInstance().Init(); }}.detach(); return true; } @@ -86,8 +80,7 @@ void IpcServerStub::OnStop() registerToService_ = false; } -int32_t IpcServerStub::OnRemoteRequest(uint32_t code, - MessageParcel &data, MessageParcel &reply, MessageOption &option) +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; @@ -115,7 +108,6 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< 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); @@ -123,7 +115,6 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< LOGI("RegisterDeviceManagerListener: listener already exists"); return DM_OK; } - sptr appRecipient = sptr(new AppDeathRecipient()); if (!listener->AddDeathRecipient(appRecipient)) { LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); @@ -139,7 +130,6 @@ int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) 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); @@ -147,14 +137,12 @@ int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) 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); diff --git a/utils/include/dm_anonymous.h b/utils/include/dm_anonymous.h index e8e55878d..d8059e0b1 100644 --- a/utils/include/dm_anonymous.h +++ b/utils/include/dm_anonymous.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, @@ -25,4 +25,4 @@ std::string GetAnonyInt32(const int32_t value); } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_ANONYMOUS_H \ No newline at end of file +#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 index 452261707..cd0415926 100644 --- a/utils/include/dm_log.h +++ b/utils/include/dm_log.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, @@ -28,17 +28,17 @@ typedef enum { 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 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 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 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__) +#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 index 92ea87523..dcbe1ef1e 100644 --- a/utils/include/dm_random.h +++ b/utils/include/dm_random.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, diff --git a/utils/include/ipc/lite/ipc_cmd_register.h b/utils/include/ipc/lite/ipc_cmd_register.h index 615e07b91..6f95e3a30 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, @@ -28,59 +28,60 @@ 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 +99,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_; diff --git a/utils/include/ipc/standard/ipc_cmd_register.h b/utils/include/ipc/standard/ipc_cmd_register.h index ce3123d25..c1f0b02db 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, @@ -29,37 +29,37 @@ 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 +67,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_; diff --git a/utils/src/dm_anonymous.cpp b/utils/src/dm_anonymous.cpp index 0b7369606..8d9a7be38 100644 --- a/utils/src/dm_anonymous.cpp +++ b/utils/src/dm_anonymous.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, @@ -22,7 +22,7 @@ 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) { @@ -50,10 +50,10 @@ std::string GetAnonyInt32(const int32_t value) if (length == 0x01) { tempString[0] = '*'; return tempString; - } + } for (int32_t i = 1; i < length - 1; i++) { - tempString[i] = '*'; + tempString[i] = '*'; } return tempString; } diff --git a/utils/src/dm_log.cpp b/utils/src/dm_log.cpp index 9887471b9..2284eabda 100644 --- a/utils/src/dm_log.cpp +++ b/utils/src/dm_log.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/utils/src/dm_random.cpp b/utils/src/dm_random.cpp index 52f264d30..9e550212f 100644 --- a/utils/src/dm_random.cpp +++ b/utils/src/dm_random.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, @@ -89,7 +89,7 @@ bool MbedtlsGenRandomStr(char *szOut, int32_t szOutLen, bool numberOnly) return false; } szOut[--szOutLen] = 0; - GetRandomData((uint8_t*)szOut, szOutLen); + GetRandomData((uint8_t *)szOut, szOutLen); const int32_t NUMBER_COUNT = 10; const int32_t ALPHA_COUNT = 26; const int32_t ALPHA_BYTE_COUNT = 2; diff --git a/utils/src/ipc/lite/ipc_cmd_register.cpp b/utils/src/ipc/lite/ipc_cmd_register.cpp index 9d094af27..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, @@ -22,8 +22,8 @@ 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()) { diff --git a/utils/src/ipc/standard/ipc_cmd_register.cpp b/utils/src/ipc/standard/ipc_cmd_register.cpp index a1949d07d..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, -- Gitee From 2932e2062eecb263ba815b5a41d4ee85bcd0d639 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Thu, 6 Jan 2022 12:34:26 +0800 Subject: [PATCH 072/110] =?UTF-8?q?so=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index fb3383ce0..dba4f7581 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -176,13 +176,11 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) LOGI("DmAuthManager::VerifyAuthentication"); timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - DmConfigManager& temp = DmConfigManager::GetInstance(); - std::string soName = "libdevicemanagerext_pin_auth.z.so"; - std::shared_ptr ptr = temp.GetAuthAdapter(soName); - if (ptr == nullptr) { - LOGE("VerifyAuthentication ptr is null"); + std::shared_ptr ptr; + if (authenticationMap_.find(1) != authenticationMap_.end()) + { + ptr = authenticationMap_[1]; } - int32_t ret = ptr->VerifyAuthentication(authRequestContext_->token, authResponseContext_->code, authParam); switch (ret) @@ -665,14 +663,13 @@ void DmAuthManager::ShowAuthInfoDialog() void DmAuthManager::ShowStartAuthDialog() { - /*DmConfigManager& temp = DmConfigManager::GetInstance(); - std::string soName = "libdevicemanagerext_pin_auth.z.so"; - std::shared_ptr ptr = temp.GetAuthAdapter(soName); - if (ptr == nullptr) { - LOGE("ShowStartAuthDialog ptr is null"); - } dmAbilityMgr_ = std::make_shared(); - ptr->StartAuth(dmAbilityMgr_);*/ + std::shared_ptr ptr; + if (authenticationMap_.find(1) != authenticationMap_.end()) + { + ptr = authenticationMap_[1]; + } + ptr->StartAuth(dmAbilityMgr_); } -- Gitee From ea1cee24976f665344a49888238fb7be79ac3082 Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Thu, 6 Jan 2022 14:13:01 +0800 Subject: [PATCH 073/110] =?UTF-8?q?so=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 38 ------------------- .../src/ipc/standard/ipc_cmd_parser.cpp | 5 --- 2 files changed, 43 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 23467012d..77c402006 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -28,7 +28,6 @@ namespace OHOS { namespace DistributedHardware { - namespace { std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask"; std::string NEGOTIATE_TIMEOUT_TASK = "negotiateTimeoutTask"; @@ -223,16 +222,9 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } } else { -<<<<<<< HEAD if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this()); authRequestContext_ ->sessionId = sessionId; -======= - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { - hiChainConnector_ = std::make_shared(); - hiChainConnector_->RegisterHiChainCallback(pkgName, data_); - authRequestContext_->sessionId = sessionId; ->>>>>>> 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 authRequestState_->SetAuthContext(authRequestContext_); authMessageProcessor_->SetRequestContext(authRequestContext_); authResponseContext_ = std::make_shared(); @@ -407,14 +399,8 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) DmDeviceInfo localDevice; softbusConnector_->GetLocalDeviceInfo(localDevice); authRequestContext_->localDeviceId = localDevice.deviceId; -<<<<<<< HEAD bool ret = hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); if (ret != true){ -======= - int32_t ret = - hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); - if (ret != DM_OK) { ->>>>>>> 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE; authRequestContext_->reason = DM_AUTH_DEVICE_AUTHED; @@ -431,14 +417,8 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) void DmAuthManager::RespNegotiate(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); -<<<<<<< HEAD bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); if (ret != true){ -======= - int32_t ret = - hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); - if (ret != DM_OK) { ->>>>>>> 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = DM_AUTH_PEER_REJECT; return; @@ -561,34 +541,21 @@ void DmAuthManager::JoinNetwork() void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); -<<<<<<< HEAD if (authRequestState_ == nullptr){ if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW){ CancelDisplay(); -======= - if (authRequestState_ == nullptr) { - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { - // todo close show pin dialog ->>>>>>> 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 } authResponseContext_ = nullptr; authResponseState_ = nullptr; authMessageProcessor_ = nullptr; } else if (authRequestState_ != nullptr) { std::string flag = ""; -<<<<<<< HEAD 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 (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN){ -======= - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - if (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN) { ->>>>>>> 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, DM_AUTH_INPUT_FAILED, flag); } @@ -695,17 +662,12 @@ void DmAuthManager::ShowAuthInfoDialog() void DmAuthManager::ShowStartAuthDialog() { dmAbilityMgr_ = std::make_shared(); -<<<<<<< HEAD std::shared_ptr ptr; if (authenticationMap_.find(1) != authenticationMap_.end()) { ptr = authenticationMap_[1]; } ptr->StartAuth(dmAbilityMgr_); - -======= - ptr->StartAuth(dmAbilityMgr_);*/ ->>>>>>> 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 } int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 3ca879304..e7271010a 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -352,7 +352,6 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) return DM_OK; } -<<<<<<< HEAD ON_IPC_CMD(GET_UDID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); std::string netWorkId = data.ReadString(); @@ -388,10 +387,6 @@ ON_IPC_CMD(GET_UUID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) { } ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { -======= -ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) -{ ->>>>>>> 6a5fbaac8bd70ea5d5aaed28e1eec89b7a3bc451 std::string packName = data.ReadString(); DmAuthParam authParam; int32_t ret = DM_OK; -- Gitee From c3d83299010de010c94df265417fca1d5518ec7b Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Thu, 6 Jan 2022 15:42:31 +0800 Subject: [PATCH 074/110] =?UTF-8?q?=E6=9E=9A=E4=B8=BE=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 9dda0bd60..6b685ef22 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -142,6 +142,8 @@ 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; -- Gitee From 5240b62275f74ce37d054d740423ca06e42cb70d Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Thu, 6 Jan 2022 16:55:36 +0800 Subject: [PATCH 075/110] =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 77c402006..f819f20d7 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -43,6 +43,7 @@ int32_t NEGOTIATE_TIMEOUT = 10; int32_t INPUT_TIMEOUT = 60; int32_t ADD_TIMEOUT = 10; int32_t CANCEL_PICODE_DISPLAY = 1; +int32_t DEVICE_ID_HALF = 2; } // namespace static void TimeOut(void *data) @@ -180,22 +181,21 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); std::shared_ptr ptr; - if (authenticationMap_.find(1) != authenticationMap_.end()) - { + if (authenticationMap_.find(1) != authenticationMap_.end()) { 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: - //todo Prompt for input pin code error - //break; - default: - CancelDisplay(); + 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: + //todo Prompt for input pin code error + //break; + default: + CancelDisplay(); + } LOGI("DmAuthManager::VerifyAuthentication complete"); return DM_OK; -- Gitee From 05999a2f2d303594447ee246c1f0a64319b45c2c Mon Sep 17 00:00:00 2001 From: "jia.li" Date: Thu, 6 Jan 2022 18:57:10 +0800 Subject: [PATCH 076/110] TDD lijia new --- test/unittest/BUILD.gn | 191 ++++++++- .../UTTest_device_manager_service.cpp | 365 ++++++++++++++---- test/unittest/UTTest_device_manager_service.h | 24 +- ...UTTest_device_manager_service_listener.cpp | 106 +++++ .../UTTest_device_manager_service_listener.h | 43 +++ .../UTTest_dm_device_info_manager.cpp | 62 +++ test/unittest/UTTest_dm_device_info_manager.h | 44 +++ test/unittest/mock/ipc_server_listener.cpp | 31 ++ test/unittest/mock/ipc_server_listener.h | 37 ++ 9 files changed, 819 insertions(+), 84 deletions(-) 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_dm_device_info_manager.cpp create mode 100644 test/unittest/UTTest_dm_device_info_manager.h create mode 100644 test/unittest/mock/ipc_server_listener.cpp create mode 100644 test/unittest/mock/ipc_server_listener.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 27c0e381d..e1f54a5a0 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -24,7 +24,9 @@ group("unittest") { ":UTTest_softbus_connector", ":UTTest_softbus_session", ":UTTest_hichain_connector", - + ":UTTest_dm_device_state_manager", + ":UTTest_device_manager_service_listener", + ":UTTest_dm_device_info_manager", ] } @@ -61,6 +63,29 @@ ohos_unittest("UTTest_hichain_connector") { ## 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 @@ -81,14 +106,63 @@ ohos_unittest("UTTest_softbus_session") { } ## UnitTest UTTest_softbus_session }}} +## UnitTest UTTest_dm_device_state_manager {{{ +ohos_unittest("UTTest_dm_device_state_manager") { + module_out_path = module_out_path + + sources = [ "UTTest_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/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/test/unittest/mock/parameter.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", + + ] + + + deps = [ ":device_manager_test_common" ] +} + +## 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 = [ + "UTTest_device_manager_service_listener.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_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 = [ "UTTest_dm_discovery_manager.cpp" ] - - deps = [ ":device_manager_test_common" ] + sources = [ + "UTTest_dm_discovery_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/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/test/unittest/mock/parameter.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", + ] + + deps = [ ":device_manager_test" ] } ## UnitTest UTTest_dm_discovery_manager }}} @@ -108,12 +182,12 @@ config("device_manager_test_common_public_config") { "${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/dsoftbus/interfaces/kits/transport", "//foundation/communication/ipc_lite/interfaces/kits", "//foundation/communication/dsoftbus/interfaces/kits/common", "//foundation/communication/dsoftbus/interfaces/kits/discovery", @@ -124,10 +198,11 @@ config("device_manager_test_common_public_config") { "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ipc/standard", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/discovery", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dependency/hichain", - "//base/security/deviceauth/interfaces/innerkits", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/deviceinfo/", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/devicestate", - "//foundation/multimedia/histreamer/engine/pipeline/core", + "//foundation/distributedhardware/devicemanager/test/unittest/mock", + "//base/security/deviceauth/interfaces/innerkits", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ability", ] cflags = [ @@ -137,6 +212,12 @@ cflags = [ "-Dprivate=public", "-Dprotected=public", ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"device_manager_UTtest\"", + "LOG_DOMAIN=0xD004190", + ] } ohos_static_library("device_manager_test_common") { @@ -159,4 +240,98 @@ ohos_static_library("device_manager_test_common") { "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager", ] } -## Build device_manager_test_common.a }}} \ No newline at end of file +## 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", + ] + +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/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock", + "//third_party/googletest:gtest", + "//utils/native/base:utils", + "//foundation/distributedhardware/devicemanager/interfaces/kits/js:devicemanager", + ] + + 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 = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "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", + ] +} +## Build device_manager_test.a }}} \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 133f250e4..effdf8c11 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1,121 +1,342 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_device_info.h" #include "UTTest_device_manager_service.h" +namespace OHOS { +namespace DistributedHardware { + +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); -namespace OHOS +void DeviceManagerServiceTest::SetUp() { -namespace DistributedHardware +} + +void DeviceManagerServiceTest::TearDown() { +} -IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); +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); +} -void DeviceManagerImplTest::SetUp() +/** + * @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); } -void DeviceManagerImplTest::TearDown() +/** + * @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); } -void DeviceManagerImplTest::SetUpTestCase() +/** + * @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); } -void DeviceManagerImplTest::TearDownTestCase() +/** + * @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); } -namespace + +/** + * @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); +} -HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery1, testing::ext::TestSize.Level0) +/** + * @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) { - 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); - // ASSERT_NE(ret,DM_NOT_INIT); + DeviceManagerService::GetInstance().intFlag_ = false; + std::shared_ptr softbusConnector_ = nullptr; + int ret = DeviceManagerService::GetInstance().Init(); + EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Level0) + +/** + * @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) { - std::string pkgName = "com.ohos.test"; - DmSubscribeInfo subscribeInfo; - std::string extra = "test"; - // DeviceManagerService::GetInstance().Init(); - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - pkgName = "1com.ohos.test1"; - ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - ASSERT_NE(ret, DM_DISCOVERY_REPEATED); + 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); } -HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery1, testing::ext::TestSize.Level0) +/** + * @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) { - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, DM_NOT_INIT); + 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); } -HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo1, testing::ext::TestSize.Level0) + +/** + * @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) { - DmDeviceInfo info; - //DeviceManagerService::GetInstance().Init(); - int ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); - EXPECT_EQ(ret, DM_NOT_INIT); + 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); } -HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo2, testing::ext::TestSize.Level0) +/** + * @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) { - DmDeviceInfo info; - DeviceManagerService::GetInstance().Init(); - int ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); - EXPECT_EQ(ret, 0); + 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); } -HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, testing::ext::TestSize.Level0) + +/** + * @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) { - 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); + 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); } -HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery2, testing::ext::TestSize.Level0) +/** + * @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) { - std::string pkgName = ""; - uint16_t subscribeId = 1; - DeviceManagerService::GetInstance().Init(); - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); + 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); } -HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery3, testing::ext::TestSize.Level0) + +/** + * @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) { - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - int32_t freq = -1; - int32_t mode = -1; - int32_t medium = -1; - DmSubscribeInfo testInfo = { - .subscribeId = 1, - .mode = (DmDiscoverMode)mode, - .medium = (DmExchangeMedium)medium, - .freq = (DmExchangeFreq)freq, - .isSameAccount = true, - .isWakeRemote = true, - .capability = "osdCapability", - }; - std::string extra = "test"; - DeviceManagerService::GetInstance().Init(); - DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, testInfo, extra); - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_TRUE(ret != DM_OK); + 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); +} } } } diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index 1d0ad1e69..787bd7331 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -1,7 +1,20 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 @@ -19,12 +32,15 @@ namespace OHOS { namespace DistributedHardware { - class DeviceManagerImplTest : public testing::Test { +class DeviceManagerServiceTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); virtual void SetUp() override; virtual void TearDown() override; }; -}} -#endif // OHOS_DM_SERVICE_H +} +} +#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..63904c473 --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_listener.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 + +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_anonymous.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_verify_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 "UTTest_device_manager_service_listener.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); +} +} +} +} \ 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..5b9d3b155 --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_listener.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_SERVICE_LISTENER_H +#define OHOS_UTTEST_DM_SERVICE_LISTENER_H + +#define private public +#define protected public + +#include +#include +#include + +#include "dm_device_info.h" +#include "ipc_server_listener.h" +#include "device_manager_service_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; +}; +} +} +#undef private +#undef protected +#endif \ No newline at end of file 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..a49de8334 --- /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_log.h" +#include "dm_constants.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); +} +} +} +} \ 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..0c2e054ee --- /dev/null +++ b/test/unittest/UTTest_dm_device_info_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_DEVICEINFO_MANAGER_H +#define OHOS_UTTEST_DM_DEVICEINFO_MANAGER_H + +#include +#include +#include +#include + +#include "dm_device_info_manager.h" +#include "dm_device_info.h" +#include "softbus_connector.h" +#include "dm_adapter_manager.h" +#include "device_manager_service_listener.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; +}; +} +} +#undef private +#undef protected +#endif \ No newline at end of file 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..20462face --- /dev/null +++ b/test/unittest/mock/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 +#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 -- Gitee From 6df363851ecc2450e34c7e1c4c4816f8b4b92af7 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Thu, 6 Jan 2022 19:37:35 +0800 Subject: [PATCH 077/110] bug modify --- common/include/dm_constants.h | 2 +- .../src/authentication/auth_message_processor.cpp | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 6b685ef22..46fbe0683 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -22,7 +22,7 @@ namespace OHOS { namespace DistributedHardware { const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; -const std::string DM_SESSION_NAME = "distributedhardware.devicemanager.resident"; +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"; diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index fade56bcc..3574da71f 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -126,6 +126,7 @@ 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); @@ -216,6 +217,7 @@ 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]; -- Gitee From 640877d49e4e1d125d489aef0f99c374f61f5966 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Thu, 6 Jan 2022 21:15:10 +0800 Subject: [PATCH 078/110] nullptr --- .../include/authentication/dm_auth_manager.h | 1 - .../src/authentication/dm_auth_manager.cpp | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 09d7286dc..6f2517f9d 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -162,7 +162,6 @@ public: private: std::shared_ptr softbusConnector_; - std::shared_ptr sessionSession_; std::shared_ptr hiChainConnector_; std::shared_ptr listener_; std::shared_ptr adapterMgr_; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index f819f20d7..03a7ff36b 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -64,7 +64,7 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, LOGI("DmAuthManager constructor"); //TODO: load library so for different auth type hiChainConnector_ = std::make_shared(); - sessionSession_->RegisterSessionCallback(DM_PKG_NAME, shared_from_this()); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(DM_PKG_NAME, shared_from_this()); DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); dmConfigManager.GetAuthAdapter(authenticationMap_); @@ -103,8 +103,8 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au LOGE("AuthenticateDevice failed, authType is not support"); return DM_INPUT_PARA_EMPTY; } - sessionSession_->UnRegisterSessionCallback(pkgName); - sessionSession_->RegisterSessionCallback(pkgName, shared_from_this()); + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(pkgName); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(pkgName, shared_from_this()); authMessageProcessor_ = std::make_shared(shared_from_this()); authRequestContext_ = std::make_shared(); @@ -568,7 +568,7 @@ void DmAuthManager::AuthenticateFinish() authRequestContext_->token, authResponseContext_->reply, std::to_string(authRequestContext_->reason)); - sessionSession_->UnRegisterSessionCallback(authRequestContext_->hostPkgName); + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(authRequestContext_->hostPkgName); softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); if (!timerMap_.empty()) { for (auto &iter : timerMap_) { -- Gitee From bc0a2a0f6c9a36ba1bc483176e97ae2a21855587 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Thu, 6 Jan 2022 21:41:22 +0800 Subject: [PATCH 079/110] add by weidong.liu@thundersoft.com change: add profile_connector --- ext/profile/BUILD.gn | 59 +++++---- ext/profile/include/device_profile_adapter.h | 18 ++- ext/profile/include/profile_connector.h | 57 +++++++++ .../include/profile_connector_callback.h | 28 +++++ ext/profile/src/device_profile_adapter.cpp | 54 ++++++++ ext/profile/src/profile_connector.cpp | 116 ++++++++++++++++++ .../include/notify/device_manager_notify.h | 1 + .../src/ipc/standard/ipc_cmd_parser.cpp | 3 + .../src/notify/device_manager_notify.cpp | 11 ++ ohos.build | 3 +- .../include/adapter/profile_adapter.h | 4 +- .../include/device_manager_service_listener.h | 2 + .../devicestate/dm_device_state_manager.h | 1 + .../src/device_manager_service_listener.cpp | 23 +++- .../devicestate/dm_device_state_manager.cpp | 36 +++++- 15 files changed, 386 insertions(+), 30 deletions(-) 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/profile_connector.cpp diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn index 5db7565da..419c83df0 100644 --- a/ext/profile/BUILD.gn +++ b/ext/profile/BUILD.gn @@ -19,28 +19,43 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -shared_library("devicemanagerext_profile") { - include_dirs = [ - "${common_path}/include", - "${services_path}/include/adapter/", - "crypto/include", - "ds/include", - ] - - include_dirs += [ - ] - - sources = [ - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerext\"", - "LOG_DOMAIN=0xD004100", - ] - - deps = [ +if (defined(ohos_lite)) { - ] +} else { + ohos_shared_library("devicemanagerext_profile") { + include_dirs = [ + "include", + "${common_path}/include", + "${ext_path}/profile/include", + "${utils_path}/include", + "${services_path}/include/adapter", + ] + + sources = [ + "src/device_profile_adapter.cpp", + "src/profile_connector.cpp", + ] + + deps = [ + "${utils_path}:devicemanagerutils", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "device_profile_core:distributed_device_profile_client", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerext\"", + "LOG_DOMAIN=0xD004100", + ] + + subsystem_name = "distributedhardware" + + part_name = "device_manager_base" + } } diff --git a/ext/profile/include/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h index fb27cbdd5..3ca004072 100644 --- a/ext/profile/include/device_profile_adapter.h +++ b/ext/profile/include/device_profile_adapter.h @@ -16,15 +16,31 @@ #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 { +class DeviceProfileAdapter : public IProfileAdapter , public IProfileConnectorCallback{ + public: DeviceProfileAdapter(); + ~DeviceProfileAdapter(); + int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, DeviceProfileAdapterCallback callback); + int32_t UnRegisterProfileListener(); + int32_t OnProfileClientDeviceReady(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: + +public: private: + DeviceProfileAdapterCallback deviceProfileAdapterCallback_; + static std::shared_ptr profileConnector_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/ext/profile/include/profile_connector.h b/ext/profile/include/profile_connector.h new file mode 100644 index 000000000..7df8313b3 --- /dev/null +++ b/ext/profile/include/profile_connector.h @@ -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. + */ + +#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); + void OnProfileChanged(const ProfileChangeNotification& changeNotification); + 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: +public: + +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 index 2fe6d6f51..b3e0b6fff 100644 --- a/ext/profile/src/device_profile_adapter.cpp +++ b/ext/profile/src/device_profile_adapter.cpp @@ -14,10 +14,64 @@ */ #include "device_profile_adapter.h" +#include "dm_log.h" #include "dm_constants.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, DeviceProfileAdapterCallback callback) +{ + LOGI("DeviceProfileAdapter::RegisterProfileListener"); + deviceProfileAdapterCallback_ = callback; + profileConnector_->RegisterProfileCallback(pkgName, deviceId, std::shared_ptr(this)); + return DM_OK; +} + +int32_t DeviceProfileAdapter::UnRegisterProfileListener() +{ + LOGI("DeviceProfileAdapter::RegisterProfileListener"); + deviceProfileAdapterCallback_ = nullptr; + profileConnector_->UnRegisterProfileCallback(""); + return DM_OK; +} + +int32_t DeviceProfileAdapter::OnProfileClientDeviceReady(const std::string &deviceId) +{ + LOGI("DeviceProfileAdapter::OnProfileClientDeviceReady"); + if(nullptr != deviceProfileAdapterCallback_) + { + deviceProfileAdapterCallback_(deviceId); + } + else { + LOGI("deviceProfileAdapterCallback_ is nullptr"); + } + return DM_OK; +} + +void DeviceProfileAdapter::OnProfileChanged(const std::string &pkgName, const std::string &deviceId) +{ + OnProfileClientDeviceReady(deviceId); +} + +void DeviceProfileAdapter::OnProfileComplete(const std::string &pkgName, const std::string &deviceId) +{ + OnProfileClientDeviceReady(deviceId); +} + +extern "C" IProfileAdapter* CreateDeviceProfileObject (void) { + return new DeviceProfileAdapter; +} } } // namespace OHOS diff --git a/ext/profile/src/profile_connector.cpp b/ext/profile/src/profile_connector.cpp new file mode 100644 index 000000000..2407bd63c --- /dev/null +++ b/ext/profile/src/profile_connector.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_log.h" +#include "dm_constants.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"}, "5CA4CA0ED9A14B680BBD566307B670E7DF4F9AE932C1145732B660538485307E"); + 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 eventChange; + eventChange.profileEvent = ProfileEvent::EVENT_PROFILE_CHANGED; + eventChange.extraInfo = std::move(extraInfo); + subscribeInfos.emplace_back(eventChange); + + 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("", deviceId); + } +} + +void ProfileEventCallback::OnProfileChanged(const ProfileChangeNotification& changeNotification) +{ + std::string deviceId = changeNotification.GetDeviceId(); + LOGI("ProfileEventCallback::OnProfileChanged, deviceId = %s", deviceId.c_str()); + for (auto & iter : profileConnectorCallback_) { + iter.second->OnProfileChanged("", deviceId); + } +} + +} +} \ No newline at end of file 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 eb652f136..34e7a4492 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 @@ -54,6 +54,7 @@ public: 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); 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 a0e13d729..611b24ffe 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 @@ -373,6 +373,9 @@ 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: LOGE("unknown device state:%d", deviceState); break; 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 029111728..89c3193b8 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 @@ -175,6 +175,17 @@ void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDe deviceStateCallback_[pkgName]->OnDeviceChanged(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) { diff --git a/ohos.build b/ohos.build index cc05623b0..59995c055 100644 --- a/ohos.build +++ b/ohos.build @@ -23,7 +23,8 @@ "//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/ext/pin_auth:devicemanagerext_pin_auth" + "//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/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index c18d1e5ac..a3e8ca8d6 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -17,13 +17,15 @@ #define OHOS_DM_PROFILE_ADAPTER_H #include +#include namespace OHOS { namespace DistributedHardware { +using DeviceProfileAdapterCallback = std::function; class IProfileAdapter { public: virtual ~IProfileAdapter() = default; - virtual int32_t RegisterProfileListener() = 0; + virtual int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, DeviceProfileAdapterCallback callback) = 0; virtual int32_t UnRegisterProfileListener() = 0; }; diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index 071f723f7..ade397cdc 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -17,6 +17,7 @@ #define OHOS_DM_SERVICE_LISTENER_H #include +#include #include "dm_device_info.h" #include "ipc_server_listener.h" @@ -38,6 +39,7 @@ public: private: IpcServerListener ipcServerListener_; + std::map remoteDeviceInfos_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 63200319e..10420a433 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -32,6 +32,7 @@ public: 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); + static void OnProfileReady(const std::string deviceId); private: std::shared_ptr softbusConnector_; diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 1b557fb7d..eae398c93 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -33,12 +33,33 @@ namespace DistributedHardware { void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) { - LOGI("OnDeviceStateChange"); + LOGI("OnDeviceStateChange, state=%d", state); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); + DmDeviceInfo saveInfo; pReq->SetDeviceState(state); pReq->SetDeviceInfo(info); + + if(state == DEVICE_INFO_CHANGED) { + auto iter = remoteDeviceInfos_.find(info.deviceId); + if (iter == remoteDeviceInfos_.end()) { + LOGE("DeviceManagerServiceListener::OnDeviceStateChange complete not find deviceID"); + } else { + saveInfo = iter->second; + pReq->SetDeviceInfo(saveInfo); + } + } else if(state == DEVICE_STATE_ONLINE) { + DmDeviceInfo saveInfo = info; + remoteDeviceInfos_[info.deviceId] = saveInfo; + } else if(state == DEVICE_STATE_OFFLINE) { + auto iter = remoteDeviceInfos_.find(info.deviceId); + if (iter == remoteDeviceInfos_.end()) { + } else { + remoteDeviceInfos_.erase(info.deviceId); + } + } + ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 3a13a1639..3e4a1a994 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -19,6 +19,7 @@ #include "dm_adapter_manager.h" namespace OHOS { namespace DistributedHardware { +std::shared_ptr m_self_; DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnector, std::shared_ptr listener) @@ -36,16 +37,31 @@ DmDeviceStateManager::~DmDeviceStateManager() void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) { - std::string soName; + LOGI("DmDeviceStateManager::OnDeviceOnline in"); + std::string soName = "libdevicemanagerext_profile.z.so"; DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); if (profileAdapter == nullptr) { LOGE("OnDeviceOnline profile adapter is null"); + } else { + m_self_ = std::shared_ptr(this); + 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; + LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener in, deviceId = %s", deviceUdid.c_str()); + //5CA4CA0ED9A14B680BBD566307B670E7DF4F9AE932C1145732B660538485307E + profileAdapter->RegisterProfileListener(pkgName, deviceUdid, this->OnProfileReady); + LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener out"); + } } DmDeviceState state = DEVICE_STATE_ONLINE; - // profileAdapter->RegisterProfileListener(); 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) @@ -54,10 +70,11 @@ void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmD DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); if (profileAdapter == nullptr) { - LOGE("OnDeviceOnline profile adapter is null"); + LOGE("OnDeviceOffline profile adapter is null"); + } else { + profileAdapter->UnRegisterProfileListener(); } DmDeviceState state = DEVICE_STATE_OFFLINE; - // profileAdapter->UnRegisterProfileListener(); deviceStateMap_[info.deviceId] = DEVICE_STATE_OFFLINE; listener_->OnDeviceStateChange(pkgName, state, info); } @@ -71,5 +88,16 @@ void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDev { deviceStateMap_[info.deviceId] = DEVICE_INFO_READY; } + +void DmDeviceStateManager::OnProfileReady(const std::string deviceId) +{ + DmDeviceInfo info; + std::string pkgName = ""; + strcpy(info.deviceId, deviceId.c_str()); + DmDeviceState state = DEVICE_INFO_READY; + if(nullptr != m_self_) { + m_self_->listener_->OnDeviceStateChange(pkgName, state, info); + } +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From f0d78a81114cf72ab49b6c8b9c7e950e96471508 Mon Sep 17 00:00:00 2001 From: puhui Date: Fri, 7 Jan 2022 00:22:00 +0800 Subject: [PATCH 080/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9WGR=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=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 | 4 +--- .../src/dependency/softbus/softbus_connector.cpp | 1 - 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index 5669910ef..8f9c21897 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -43,18 +43,16 @@ if (defined(ohos_lite)) { "//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", - "appexecfwk_standard:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", "startup_l2:syspara", - "startup_l2:syspara_watchagent", ] defines = [ diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 8e80f96f8..0be1b9fcc 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -178,7 +178,6 @@ int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) LOGE("GetLocalNodeDeviceInfo failed with ret %d", ret); return DM_FAILED; } - // DmDeviceInfo *pInfo = &deviceInfo; CovertNodeBasicInfoToDmDevice(nodeBasicInfo, deviceInfo); LOGD("SoftbusConnector::GetLocalDeviceInfo success"); return DM_OK; -- Gitee From 48448a632d56f3dff6f0072c48e72b91c857b518 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Fri, 7 Jan 2022 13:57:22 +0800 Subject: [PATCH 081/110] modify bug --- .../include/authentication/dm_auth_manager.h | 1 + .../src/authentication/dm_auth_manager.cpp | 14 ++++++++++---- .../src/device_manager_service.cpp | 1 + 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 6f2517f9d..3a75aeb89 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -159,6 +159,7 @@ public: void ShowAuthInfoDialog(); void ShowStartAuthDialog(); int32_t GetAuthenticationParam(DmAuthParam &authParam); + int32_t RegisterSessionCallback(); private: std::shared_ptr softbusConnector_; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 03a7ff36b..2cba4c431 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -64,7 +64,6 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, LOGI("DmAuthManager constructor"); //TODO: load library so for different auth type hiChainConnector_ = std::make_shared(); - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(DM_PKG_NAME, shared_from_this()); DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); dmConfigManager.GetAuthAdapter(authenticationMap_); @@ -231,9 +230,9 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); } else { LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType()); - authResponseContext_ = std::make_shared(); - authResponseContext_->reply = AuthState::AUTH_REQUEST_INIT; - authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + // authResponseContext_ = std::make_shared(); + // authResponseContext_->reply = AuthState::AUTH_REQUEST_INIT; + // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } } } @@ -691,5 +690,12 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) } return DM_OK; } + +int32_t DmAuthManager::RegisterSessionCallback() +{ + LOGI("DmAuthManager constructor111"); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(DM_PKG_NAME, shared_from_this()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 6b2f085cf..e283de80a 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -72,6 +72,7 @@ int32_t DeviceManagerService::Init() LOGE("Init failed, authMgr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } + authMgr_->RegisterSessionCallback(); } LOGI("Init success, singleton initialized"); intFlag_ = true; -- Gitee From b55ee29293aa72e30f22fc2372b4008fa0821c72 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Fri, 7 Jan 2022 15:48:57 +0800 Subject: [PATCH 082/110] modify startdiscovery --- .../include/devicestate/dm_device_state_manager.h | 2 +- .../devicemanagerservice/src/device_manager_service.cpp | 1 + .../src/devicestate/dm_device_state_manager.cpp | 7 ++++++- .../src/discovery/dm_discovery_manager.cpp | 4 ++-- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 10420a433..d777dd167 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -33,7 +33,7 @@ public: void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info); void OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info); static void OnProfileReady(const std::string deviceId); - + int32_t RegisterSoftbusStateCallback(); private: std::shared_ptr softbusConnector_; std::shared_ptr adapterMgr_; diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index e283de80a..2de301453 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -58,6 +58,7 @@ int32_t DeviceManagerService::Init() LOGE("Init failed, deviceStateMgr_ apply for failure"); return DM_MAKE_SHARED_FAIL; } + deviceStateMgr_->RegisterSoftbusStateCallback(); } if (discoveryMgr_ == nullptr) { discoveryMgr_ = std::make_shared(softbusConnector_, listener_); diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 3e4a1a994..efbbbac0d 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -26,7 +26,6 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmDeviceStateManager constructor"); - softbusConnector_->RegisterSoftbusStateCallback(DM_PKG_NAME, std::shared_ptr(this)); } DmDeviceStateManager::~DmDeviceStateManager() @@ -99,5 +98,11 @@ void DmDeviceStateManager::OnProfileReady(const std::string deviceId) m_self_->listener_->OnDeviceStateChange(pkgName, state, info); } } + +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 index 137bfda4c..970690125 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -63,7 +63,7 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con discoveryQueue_.push(pkgName); DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId}; discoveryContextMap_.emplace(pkgName, context); - softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(this)); + 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); @@ -77,8 +77,8 @@ int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint if (!discoveryContextMap_.empty()) { discoveryContextMap_.erase(pkgName); softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); + discoveryTimer_->Stop(SESSION_CANCEL_TIMEOUT); } - discoveryTimer_->Stop(SESSION_CANCEL_TIMEOUT); return softbusConnector_->StopDiscovery(subscribeId); } -- Gitee From c0db13877539cca74922b80e4c0273aa0b2c86b8 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Fri, 7 Jan 2022 16:14:46 +0800 Subject: [PATCH 083/110] =?UTF-8?q?add=20by=20weidong.liu@thundersoft.com?= =?UTF-8?q?=20change:=20dp=5Fconnector=20=E7=BC=96=E7=A0=81=E8=A7=84?= =?UTF-8?q?=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ext/profile/include/device_profile_adapter.h | 4 ++-- ext/profile/src/device_profile_adapter.cpp | 12 ++++++------ ext/profile/src/profile_connector.cpp | 4 ++-- .../include/adapter/profile_adapter.h | 4 ++-- .../include/devicestate/dm_device_state_manager.h | 2 +- .../src/devicestate/dm_device_state_manager.cpp | 6 ++---- 6 files changed, 15 insertions(+), 17 deletions(-) diff --git a/ext/profile/include/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h index 3ca004072..7c7000a4d 100644 --- a/ext/profile/include/device_profile_adapter.h +++ b/ext/profile/include/device_profile_adapter.h @@ -30,8 +30,8 @@ public: DeviceProfileAdapter(); ~DeviceProfileAdapter(); int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, DeviceProfileAdapterCallback callback); - int32_t UnRegisterProfileListener(); - int32_t OnProfileClientDeviceReady(const std::string &deviceId); + 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: diff --git a/ext/profile/src/device_profile_adapter.cpp b/ext/profile/src/device_profile_adapter.cpp index b3e0b6fff..40b99f52b 100644 --- a/ext/profile/src/device_profile_adapter.cpp +++ b/ext/profile/src/device_profile_adapter.cpp @@ -39,20 +39,20 @@ int32_t DeviceProfileAdapter::RegisterProfileListener(const std::string &pkgName return DM_OK; } -int32_t DeviceProfileAdapter::UnRegisterProfileListener() +int32_t DeviceProfileAdapter::UnRegisterProfileListener(const std::string &pkgName) { LOGI("DeviceProfileAdapter::RegisterProfileListener"); deviceProfileAdapterCallback_ = nullptr; - profileConnector_->UnRegisterProfileCallback(""); + profileConnector_->UnRegisterProfileCallback(pkgName); return DM_OK; } -int32_t DeviceProfileAdapter::OnProfileClientDeviceReady(const std::string &deviceId) +int32_t DeviceProfileAdapter::OnProfileClientDeviceReady(const std::string &pkgName, const std::string &deviceId) { LOGI("DeviceProfileAdapter::OnProfileClientDeviceReady"); if(nullptr != deviceProfileAdapterCallback_) { - deviceProfileAdapterCallback_(deviceId); + deviceProfileAdapterCallback_(pkgName, deviceId); } else { LOGI("deviceProfileAdapterCallback_ is nullptr"); @@ -62,12 +62,12 @@ int32_t DeviceProfileAdapter::OnProfileClientDeviceReady(const std::string &devi void DeviceProfileAdapter::OnProfileChanged(const std::string &pkgName, const std::string &deviceId) { - OnProfileClientDeviceReady(deviceId); + OnProfileClientDeviceReady(pkgName, deviceId); } void DeviceProfileAdapter::OnProfileComplete(const std::string &pkgName, const std::string &deviceId) { - OnProfileClientDeviceReady(deviceId); + OnProfileClientDeviceReady(pkgName, deviceId); } extern "C" IProfileAdapter* CreateDeviceProfileObject (void) { diff --git a/ext/profile/src/profile_connector.cpp b/ext/profile/src/profile_connector.cpp index 2407bd63c..410ed423f 100644 --- a/ext/profile/src/profile_connector.cpp +++ b/ext/profile/src/profile_connector.cpp @@ -99,7 +99,7 @@ void ProfileEventCallback::OnSyncCompleted(const SyncResult& syncResults) } LOGI("ProfileEventCallback::OnSyncCompleted, deviceId = %s", deviceId.c_str()); for (auto & iter : profileConnectorCallback_) { - iter.second->OnProfileComplete("", deviceId); + iter.second->OnProfileComplete(iter.first, deviceId); } } @@ -108,7 +108,7 @@ void ProfileEventCallback::OnProfileChanged(const ProfileChangeNotification& cha std::string deviceId = changeNotification.GetDeviceId(); LOGI("ProfileEventCallback::OnProfileChanged, deviceId = %s", deviceId.c_str()); for (auto & iter : profileConnectorCallback_) { - iter.second->OnProfileChanged("", deviceId); + iter.second->OnProfileChanged(iter.first, deviceId); } } diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index a3e8ca8d6..ac172e4cc 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -21,12 +21,12 @@ namespace OHOS { namespace DistributedHardware { -using DeviceProfileAdapterCallback = std::function; +using DeviceProfileAdapterCallback = std::function; class IProfileAdapter { public: virtual ~IProfileAdapter() = default; virtual int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, DeviceProfileAdapterCallback callback) = 0; - virtual int32_t UnRegisterProfileListener() = 0; + virtual int32_t UnRegisterProfileListener(const std::string &pkgName) = 0; }; using CreateIProfileAdapterFuncPtr = IProfileAdapter *(*)(void); diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index d777dd167..638759d41 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -28,11 +28,11 @@ public: DmDeviceStateManager(std::shared_ptr softbusConnector, std::shared_ptr listener); ~DmDeviceStateManager(); + static void OnProfileReady(const std::string &pkgName, const std::string deviceId); 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); - static void OnProfileReady(const std::string deviceId); int32_t RegisterSoftbusStateCallback(); private: std::shared_ptr softbusConnector_; diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index efbbbac0d..ef6b746cc 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -52,7 +52,6 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe } else { std::string deviceUdid = (char *)udid; LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener in, deviceId = %s", deviceUdid.c_str()); - //5CA4CA0ED9A14B680BBD566307B670E7DF4F9AE932C1145732B660538485307E profileAdapter->RegisterProfileListener(pkgName, deviceUdid, this->OnProfileReady); LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener out"); } @@ -71,7 +70,7 @@ void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmD if (profileAdapter == nullptr) { LOGE("OnDeviceOffline profile adapter is null"); } else { - profileAdapter->UnRegisterProfileListener(); + profileAdapter->UnRegisterProfileListener(pkgName); } DmDeviceState state = DEVICE_STATE_OFFLINE; deviceStateMap_[info.deviceId] = DEVICE_STATE_OFFLINE; @@ -88,10 +87,9 @@ void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDev deviceStateMap_[info.deviceId] = DEVICE_INFO_READY; } -void DmDeviceStateManager::OnProfileReady(const std::string deviceId) +void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std::string deviceId) { DmDeviceInfo info; - std::string pkgName = ""; strcpy(info.deviceId, deviceId.c_str()); DmDeviceState state = DEVICE_INFO_READY; if(nullptr != m_self_) { -- Gitee From 20b98e5a86f97de65a71f9746db238422f89922d Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Fri, 7 Jan 2022 17:29:48 +0800 Subject: [PATCH 084/110] =?UTF-8?q?bug-fix/=E6=B3=A8=E5=86=8C=E5=9B=9E?= =?UTF-8?q?=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/src/notify/device_manager_notify.cpp | 4 ---- 1 file changed, 4 deletions(-) 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 89c3193b8..fb70b2e01 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 @@ -117,10 +117,6 @@ void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::stri void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName,std::shared_ptr callback) { std::lock_guard autoLock(lock_); - if (dmFaCallback_.count(pkgName) == 0) { - LOGE("DeviceManager RegisterDeviceManagerFaCallback not register"); - return; - } dmFaCallback_[pkgName] = callback; } -- Gitee From 042612ffb1d48f57c37caca1b94213ed9b4db863 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Fri, 7 Jan 2022 18:11:45 +0800 Subject: [PATCH 085/110] TDD weibo --- test/unittest/BUILD.gn | 75 ++- test/unittest/UTTest_auth_request_state.cpp | 541 +++++++++++++++++++ test/unittest/UTTest_auth_request_state.h | 37 ++ test/unittest/UTTest_auth_response_state.cpp | 397 ++++++++++++++ test/unittest/UTTest_auth_response_state.h | 34 ++ test/unittest/auth_request_state.cpp | 196 +++++++ test/unittest/auth_request_state.h | 93 ++++ test/unittest/auth_response_state.cpp | 175 ++++++ test/unittest/auth_response_state.h | 82 +++ 9 files changed, 1603 insertions(+), 27 deletions(-) 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/auth_request_state.cpp create mode 100644 test/unittest/auth_request_state.h create mode 100644 test/unittest/auth_response_state.cpp create mode 100644 test/unittest/auth_response_state.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index e1f54a5a0..1dffdf547 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -27,6 +27,10 @@ group("unittest") { ":UTTest_dm_device_state_manager", ":UTTest_device_manager_service_listener", ":UTTest_dm_device_info_manager", + ":UTTest_device_message", + ":UTTest_auth_response_state", + ":UTTest_auth_request_state", + ":UTTest_dm_auth_manager", ] } @@ -62,10 +66,6 @@ ohos_unittest("UTTest_hichain_connector") { } ## UnitTest UTTest_hichain_connector }}} - - - - ## UnitTest UTTest_dm_device_info_manager {{{ ohos_unittest("UTTest_dm_device_info_manager") { module_out_path = module_out_path @@ -76,16 +76,6 @@ ohos_unittest("UTTest_dm_device_info_manager") { } ## UnitTest UTTest_dm_device_info_manager }}} - - - - - - - - - - ## UnitTest UTTest_softbus_connector {{{ ohos_unittest("UTTest_softbus_connector") { module_out_path = module_out_path @@ -111,18 +101,16 @@ ohos_unittest("UTTest_dm_device_state_manager") { module_out_path = module_out_path sources = [ "UTTest_dm_device_state_manager.cpp", - "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/discovery/dm_discovery_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/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/test/unittest/mock/parameter.cpp", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", - ] - - deps = [ ":device_manager_test_common" ] + deps = [ ":device_manager_test" ] } ## UnitTest UTTest_dm_device_state_manager }}} @@ -135,7 +123,6 @@ ohos_unittest("UTTest_device_manager_service_listener") { "UTTest_device_manager_service_listener.cpp", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", - ] deps = [ ":device_manager_test" ] @@ -143,15 +130,51 @@ ohos_unittest("UTTest_device_manager_service_listener") { ## UnitTest UTTest_device_manager_service_listener }}} +## UnitTest UTTest_device_message {{{ +ohos_unittest("UTTest_device_message") { + module_out_path = module_out_path + + sources = [ "UTTest_device_message.cpp" ] + + deps = [ ":device_manager_test_common" ] +} +## UTTest_device_message }}} + +## UnitTest UTTest_auth_response_state {{{ +ohos_unittest("UTTest_auth_response_state") { + module_out_path = module_out_path + + sources = [ "UTTest_auth_response_state.cpp" ] + + deps = [ ":device_manager_test_common" ] +} +## UTTest_auth_response_state }}} + +## UnitTest UTTest_auth_request_state {{{ +ohos_unittest("UTTest_auth_request_state") { + module_out_path = module_out_path + + sources = [ "UTTest_auth_request_state.cpp"] + + deps = [ ":device_manager_test_common" ] +} +## UTTest_auth_request_state }}} +## UnitTest UTTest_dm_auth_manager {{{ +ohos_unittest("UTTest_dm_auth_manager") { + module_out_path = module_out_path + sources = [ "UTTest_dm_auth_manager.cpp" ] + deps = [ ":device_manager_test_common" ] +} +## UTTest_dm_auth_manager }}} ## UnitTest UTTest_dm_discovery_manager {{{ ohos_unittest("UTTest_dm_discovery_manager") { module_out_path = module_out_path - sources = [ + sources = [ "UTTest_dm_discovery_manager.cpp", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp", "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", @@ -162,7 +185,7 @@ ohos_unittest("UTTest_dm_discovery_manager") { "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", ] - deps = [ ":device_manager_test" ] + deps = [ ":device_manager_test_common" ] } ## UnitTest UTTest_dm_discovery_manager }}} @@ -186,11 +209,9 @@ config("device_manager_test_common_public_config") { "${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", @@ -201,8 +222,10 @@ config("device_manager_test_common_public_config") { "//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", + "//base/security/deviceauth/interfaces/innerkits", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/dsoftbus/interfaces/kits/discovery", ] cflags = [ @@ -261,10 +284,8 @@ config("device_manager_test_common_public") { "${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", @@ -334,4 +355,4 @@ ohos_static_library("device_manager_test") { "samgr_standard:samgr_proxy", ] } -## Build device_manager_test.a }}} \ No newline at end of file +## 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..59faeccfa --- /dev/null +++ b/test/unittest/UTTest_auth_request_state.cpp @@ -0,0 +1,541 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "dm_constants.h" +#include "dm_auth_manager.h" +#include "UTTest_auth_request_state.h" + +namespace OHOS { +namespace DistributedHardware { +void AuthRequestStateTest::SetUp() +{ +} +void AuthRequestStateTest::TearDown() +{ +} +void AuthRequestStateTest::SetUpTestCase() +{ +} +void AuthRequestStateTest::TearDownTestCase() +{ +} + +namespace{ + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + +/** + * @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); +} + +/** + * @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); +} + +/** + * @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); +} + +/** + * @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()); + authRequestState->SetAuthManager(nullptr); + int32_t ret =authRequestState->Enter(); + ASSERT_EQ(ret,DM_FAILED); +} + +/** + * @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); +} + +/** + * @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); +} + +/** + * @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 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); +} + +/** + * @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 authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNegotiateState()); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr authMessageProcessor = std::make_shared(authManager); + authManager->authResponseContext_ = std::make_shared(); + authManager->authRequestContext_ = std::make_shared(); + authManager->authRequestState_ = std::shared_ptr(new AuthRequestNegotiateState()); + 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); +} + +/** + * @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); +} + +/** + * @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 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); +} + +/** + * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNegotiateDoneState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret =authRequestState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } + +/** + * @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); +} + +/** + * @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 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); +} + +// /** +// * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestReplyState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret =authRequestState->Enter(); +// ASSERT_EQ(ret,DM_OK); + +// } + +/** + * @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); +} + +/** + * @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 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); +} + +// /** +// * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInputState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret =authRequestState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } + +/** + * @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); +} + +/** + * @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 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); +} + +// /** +// * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestJoinState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret = authRequestState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } + +/** + * @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); +} + +/** + * @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 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); +} + +/** + * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNetworkState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret = authRequestState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } + +/** + * @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); +} + +/** + * @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 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); +} + +// /** +// * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestFinishState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret = authRequestState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } +} +} +} diff --git a/test/unittest/UTTest_auth_request_state.h b/test/unittest/UTTest_auth_request_state.h new file mode 100644 index 000000000..aa5626a4a --- /dev/null +++ b/test/unittest/UTTest_auth_request_state.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_AUTH_REQUEST_STATE_TEST_H +#define OHOS_DM_AUTH_REQUEST_STATE_TEST_H + +#include +#include +#include +#include +#include "dm_log.h" +#include "auth_request_state.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; +}; +} +} +#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..4cdbdbd90 --- /dev/null +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -0,0 +1,397 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_log.h" +#include "dm_constants.h" +#include "dm_auth_manager.h" +#include "UTTest_auth_response_state.h" + +namespace OHOS { +namespace DistributedHardware { +void AuthResponseStateTest::SetUp() +{ +} +void AuthResponseStateTest::TearDown() +{ +} +void AuthResponseStateTest::SetUpTestCase() +{ +} +void AuthResponseStateTest::TearDownTestCase() +{ +} + +namespace{ + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + +/** + * @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 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); +} + +/** + * @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); +} + +/** + * @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 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); +} + +/** + * @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); +// } + + +/** + * @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); +} + +/** + * @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); +} + +/** + * @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); +} + +/** + * @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 authManager = std::make_shared(softbusConnector, listener); + std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseNegotiateState()); + authResponseState->SetAuthManager(nullptr); + int32_t ret =authResponseState->Enter(); + ASSERT_EQ(ret,DM_FAILED); +} + +/** + * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseNegotiateState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// authResponseState->authManager_ = authManager; +// 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); +} + +/** + * @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 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); +} + +/** + * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseConfirmState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret =authResponseState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } + +/** + * @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); +} + +/** + * @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 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); +} + +/** + * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseGroupState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret =authResponseState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } + +/** + * @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); +} + +/** + * @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 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); +} + +/** + * @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 data = std::make_shared(softbusConnector, listener); +// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseShowState()); +// std::shared_ptr authManager = std::shared_ptr(data); +// int32_t ret =authResponseState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } + +/** + * @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); +} + +/** + * @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 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); +} + +/** + * @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 authManager = std::make_shared(softbusConnector, listener); +// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseFinishState()); +// int32_t ret =authResponseState->Enter(); +// ASSERT_EQ(ret,DM_OK); +// } +} +} +} diff --git a/test/unittest/UTTest_auth_response_state.h b/test/unittest/UTTest_auth_response_state.h new file mode 100644 index 000000000..938bc5319 --- /dev/null +++ b/test/unittest/UTTest_auth_response_state.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_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; +}; +} +} +#endif diff --git a/test/unittest/auth_request_state.cpp b/test/unittest/auth_request_state.cpp new file mode 100644 index 000000000..504e3c7b5 --- /dev/null +++ b/test/unittest/auth_request_state.cpp @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 { + +int32_t AuthRequestState::Leave() { + return DM_OK; +} + +int32_t AuthRequestState::SetAuthManager(std::shared_ptr authManager) { + authManager_ = std::move(authManager); + return DM_OK; +} + +// void AuthRequestState::SetLastState(std::shared_ptr state) { +// lastState_ = state; +// } + +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() { +// //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 + 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() { +// //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 DM_FAILED; + } + stateAuthManager->SendAuthRequest(context_->sessionId); + return DM_OK; +} + +int32_t AuthRequestReplyState::GetStateType() { + return AuthState::AUTH_REQUEST_REPLY; +} + +int32_t AuthRequestReplyState::Enter() { + //1. 收到请求响应,判断用户响应结果 + + //2. 用户授权同意 + + //3. 回调给认证实现模块,启动认证 + 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() { +// //1. 获取用户输入 +// +// //2. 验证认证信息 + 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() { + //1. 加入群组 + 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() { + //1. 进行组网 + 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() { + //1. 清理资源 + //2. 通知对端认证结束,并关闭认证通道 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->AuthenticateFinish(); + return DM_OK; +} +} +} diff --git a/test/unittest/auth_request_state.h b/test/unittest/auth_request_state.h new file mode 100644 index 000000000..539dde308 --- /dev/null +++ b/test/unittest/auth_request_state.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_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(); + }; + virtual int32_t GetStateType() = 0; + virtual int32_t Enter() = 0; + int32_t Leave(); + int32_t TransitionTo(std::shared_ptr state); + // void SetLastState(std::shared_ptr state); + int32_t SetAuthManager(std::shared_ptr authManager); + int32_t SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); +protected: + std::weak_ptr authManager_; + // std::shared_ptr lastState_; + std::shared_ptr context_; +}; + +class AuthRequestInitState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthRequestNegotiateState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; +class AuthRequestNegotiateDoneState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthRequestReplyState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthRequestInputState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthRequestJoinState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthRequestNetworkState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthRequestFinishState : public AuthRequestState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif //OHOS_DM_AUTH_REQUEST_STATE_H diff --git a/test/unittest/auth_response_state.cpp b/test/unittest/auth_response_state.cpp new file mode 100644 index 000000000..d8c2a30eb --- /dev/null +++ b/test/unittest/auth_response_state.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "auth_response_state.h" + +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t AuthResponseState::Leave() +{ + return DM_OK; +} + +int32_t AuthResponseState::SetAuthContext(std::shared_ptr context) { + context_ = std::move(context); + return DM_OK; +} + +std::shared_ptr AuthResponseState::GetAuthContext() { + return context_; +} + +int32_t AuthResponseState::SetAuthManager(std::shared_ptr authManager) +{ + authManager_ = std::move(authManager); + return DM_OK; +} + +// void AuthResponseState::SetLastState(std::shared_ptr state) +// { +// lastState_ = state; +// } + +int32_t AuthResponseState::TransitionTo(std::shared_ptr state) +{ + LOGI("AuthRequestState:: TransitionTo"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + state->SetAuthManager(stateAuthManager); + // state->SetLastState((std::shared_ptr)this); + // lastState_ = state; + stateAuthManager->SetAuthResponseState(state); + state->SetAuthContext(context_); + this->Leave(); + state->Enter(); + return DM_OK; +} + +int32_t AuthResponseInitState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_INIT; +} + +int32_t AuthResponseInitState::Enter() +{ + LOGI("AuthResponse:: AuthResponseInitState Enter"); + //1.认证通道建立后,进入该状态 + return DM_OK; +} + +int32_t AuthResponseNegotiateState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_NEGOTIATE; +} + +int32_t AuthResponseNegotiateState::Enter() +{ + //1.收到协商消息后进入 + + //2. 获取本地加解密模块信息,并回复消 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->RespNegotiate(context_->sessionId); + return DM_OK; +} + +int32_t AuthResponseConfirmState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_CONFIRM; +} + +int32_t AuthResponseConfirmState::Enter() +{ + //委托授权UI模块进行用户交互 + //如果交互成功 + // TransitionTo(new AuthResponseGroupState()); + LOGI("AuthResponse:: AuthResponseConfirmState Enter"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->ShowConfigDialog(); + return DM_OK; +} + +int32_t AuthResponseGroupState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_GROUP; +} + +int32_t AuthResponseGroupState::Enter() +{ +// //1.创建群组, +// authManagerPtr_->GetHiChainConnector()->CreateGroup(); + LOGI("AuthResponse:: AuthResponseGroupState Enter"); + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->CreateGroup(); + return DM_OK; +} + +int32_t AuthResponseShowState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_SHOW; +} + +int32_t AuthResponseShowState::Enter() +{ + //1.委托认证实现模块进行用户交互 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->ShowAuthInfoDialog(); + return DM_OK; +} + +int32_t AuthResponseFinishState::GetStateType() +{ + return AuthState::AUTH_RESPONSE_FINISH; +} + +int32_t AuthResponseFinishState::Enter() +{ + //1.结束UI显示 + + //2.清理资源,结束状态机 + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return DM_FAILED; + } + stateAuthManager->AuthenticateFinish(); + return DM_OK; + +} +} +} diff --git a/test/unittest/auth_response_state.h b/test/unittest/auth_response_state.h new file mode 100644 index 000000000..ecadd7c6c --- /dev/null +++ b/test/unittest/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 int32_t Enter() = 0; + int32_t Leave(); + int32_t TransitionTo(std::shared_ptr state); + // void SetLastState(std::shared_ptr state); + int32_t SetAuthManager(std::shared_ptr authManager); + int32_t SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); +protected: + std::weak_ptr authManager_; + // std::shared_ptr lastState_; + std::shared_ptr context_; +}; + +class AuthResponseInitState : public AuthResponseState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthResponseNegotiateState : public AuthResponseState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthResponseConfirmState : public AuthResponseState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthResponseGroupState : public AuthResponseState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthResponseShowState : public AuthResponseState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; + +class AuthResponseFinishState : public AuthResponseState { +public: + int32_t GetStateType() override; + int32_t Enter() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif //OHOS_DM_AUTH_RESPONSE_STATE_H -- Gitee From d78cc528b4d302bdf4412bfa2c28591717918e5a Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Sat, 8 Jan 2022 15:44:05 +0800 Subject: [PATCH 086/110] add by weidong.liu@thundersoft.com change : change dp_adapter callback param --- ext/profile/BUILD.gn | 18 +++++++++++++++++- ext/profile/include/device_profile_adapter.h | 5 +++-- ext/profile/src/device_profile_adapter.cpp | 6 ++++-- .../include/adapter/dm_adapter_manager.h | 1 + .../include/adapter/profile_adapter.h | 5 +++-- .../devicestate/dm_device_state_manager.h | 2 +- .../devicestate/dm_device_state_manager.cpp | 8 ++------ 7 files changed, 31 insertions(+), 14 deletions(-) diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn index 419c83df0..6c3ff6d4d 100644 --- a/ext/profile/BUILD.gn +++ b/ext/profile/BUILD.gn @@ -26,9 +26,24 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", "${ext_path}/profile/include", - "${utils_path}/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 = [ @@ -39,6 +54,7 @@ if (defined(ohos_lite)) { deps = [ "${utils_path}:devicemanagerutils", "//utils/native/base:utils", + "${services_path}:devicemanagerservice", ] external_deps = [ diff --git a/ext/profile/include/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h index 7c7000a4d..057e835d4 100644 --- a/ext/profile/include/device_profile_adapter.h +++ b/ext/profile/include/device_profile_adapter.h @@ -29,7 +29,8 @@ class DeviceProfileAdapter : public IProfileAdapter , public IProfileConnectorCa public: DeviceProfileAdapter(); ~DeviceProfileAdapter(); - int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, DeviceProfileAdapterCallback callback); + 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); @@ -39,7 +40,7 @@ private: public: private: - DeviceProfileAdapterCallback deviceProfileAdapterCallback_; + std::shared_ptr deviceProfileAdapterCallback_; static std::shared_ptr profileConnector_; }; } // namespace DistributedHardware diff --git a/ext/profile/src/device_profile_adapter.cpp b/ext/profile/src/device_profile_adapter.cpp index 40b99f52b..0e0c74eeb 100644 --- a/ext/profile/src/device_profile_adapter.cpp +++ b/ext/profile/src/device_profile_adapter.cpp @@ -16,6 +16,7 @@ #include "device_profile_adapter.h" #include "dm_log.h" #include "dm_constants.h" +#include "dm_device_state_manager.h" namespace OHOS { namespace DistributedHardware { @@ -31,7 +32,8 @@ DeviceProfileAdapter::~DeviceProfileAdapter() } -int32_t DeviceProfileAdapter::RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, DeviceProfileAdapterCallback callback) +int32_t DeviceProfileAdapter::RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback) { LOGI("DeviceProfileAdapter::RegisterProfileListener"); deviceProfileAdapterCallback_ = callback; @@ -52,7 +54,7 @@ int32_t DeviceProfileAdapter::OnProfileClientDeviceReady(const std::string &pkgN LOGI("DeviceProfileAdapter::OnProfileClientDeviceReady"); if(nullptr != deviceProfileAdapterCallback_) { - deviceProfileAdapterCallback_(pkgName, deviceId); + deviceProfileAdapterCallback_->OnProfileReady(pkgName, deviceId); } else { LOGI("deviceProfileAdapterCallback_ is nullptr"); diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index 0dbc8fee0..c134d19ab 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -25,6 +25,7 @@ namespace OHOS { namespace DistributedHardware { +class IProfileAdapter; class DmAdapterManager { DECLARE_SINGLE_INSTANCE(DmAdapterManager); diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index ac172e4cc..6e4693157 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -21,11 +21,12 @@ namespace OHOS { namespace DistributedHardware { -using DeviceProfileAdapterCallback = std::function; +class DmDeviceStateManager; class IProfileAdapter { public: virtual ~IProfileAdapter() = default; - virtual int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, DeviceProfileAdapterCallback callback) = 0; + 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; }; diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 638759d41..4e828f2a5 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -28,11 +28,11 @@ public: DmDeviceStateManager(std::shared_ptr softbusConnector, std::shared_ptr listener); ~DmDeviceStateManager(); - static void OnProfileReady(const std::string &pkgName, const std::string deviceId); 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_; diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index ef6b746cc..4e1429a0d 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -19,7 +19,6 @@ #include "dm_adapter_manager.h" namespace OHOS { namespace DistributedHardware { -std::shared_ptr m_self_; DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnector, std::shared_ptr listener) @@ -43,7 +42,6 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe if (profileAdapter == nullptr) { LOGE("OnDeviceOnline profile adapter is null"); } else { - m_self_ = std::shared_ptr(this); uint8_t udid[UDID_BUF_LEN] = {0}; int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(info.deviceId, NodeDeivceInfoKey::NODE_KEY_UDID, udid, sizeof(udid)); @@ -52,7 +50,7 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe } else { std::string deviceUdid = (char *)udid; LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener in, deviceId = %s", deviceUdid.c_str()); - profileAdapter->RegisterProfileListener(pkgName, deviceUdid, this->OnProfileReady); + profileAdapter->RegisterProfileListener(pkgName, deviceUdid, shared_from_this()); LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener out"); } } @@ -92,9 +90,7 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: DmDeviceInfo info; strcpy(info.deviceId, deviceId.c_str()); DmDeviceState state = DEVICE_INFO_READY; - if(nullptr != m_self_) { - m_self_->listener_->OnDeviceStateChange(pkgName, state, info); - } + listener_->OnDeviceStateChange(pkgName, state, info); } int32_t DmDeviceStateManager::RegisterSoftbusStateCallback() -- Gitee From 9e7dd833b7696ede92f7c3b35bad704198bd0f9b Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Sat, 8 Jan 2022 16:56:04 +0800 Subject: [PATCH 087/110] =?UTF-8?q?js=20=E5=B4=A9=E6=BA=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 2cba4c431..d7900854d 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -127,7 +127,7 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au authRequestContext_->appIcon = jsonObject[APP_ICON_KEY]; } } - authRequestContext_->token = GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN); + 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_); @@ -265,11 +265,11 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); } else { LOGE("Device manager auth state error"); - 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); - authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); + // 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); + // authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); } break; case MSG_TYPE_REQ_AUTH: @@ -278,11 +278,11 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseConfirmState())); } else { LOGE("Device manager auth state error"); - authResponseContext_->reply = AuthState::AUTH_RESPONSE_NEGOTIATE; - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); + // authResponseContext_->reply = AuthState::AUTH_RESPONSE_NEGOTIATE; + // authMessageProcessor_->SetResponseContext(authResponseContext_); + // std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + // softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + // authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); } break; case MSG_TYPE_RESP_AUTH: @@ -292,7 +292,7 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestReplyState())); } else { LOGE("Device manager auth state error"); - authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } break; case MSG_TYPE_RESP_NEGOTIATE: @@ -300,7 +300,7 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateDoneState())); } else { LOGE("Device manager auth state error"); - authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } break; case MSG_TYPE_REQ_AUTH_TERMINATE: -- Gitee From 207b7025dee26eefc84354324448b1dbed6b1fd0 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Sat, 8 Jan 2022 19:39:33 +0800 Subject: [PATCH 088/110] add timer --- .../src/authentication/dm_auth_manager.cpp | 47 ++++++++++--------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index d7900854d..66a404d49 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -35,6 +35,8 @@ 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; @@ -42,6 +44,8 @@ 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 @@ -211,6 +215,12 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI 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()); @@ -230,9 +240,6 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); } else { LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType()); - // authResponseContext_ = std::make_shared(); - // authResponseContext_->reply = AuthState::AUTH_REQUEST_INIT; - // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } } } @@ -262,37 +269,25 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId 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"); - // 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); - // authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); } break; case MSG_TYPE_REQ_AUTH: - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT || - authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { + 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"); - // authResponseContext_->reply = AuthState::AUTH_RESPONSE_NEGOTIATE; - // authMessageProcessor_->SetResponseContext(authResponseContext_); - // std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); - // softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - // authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); } break; case MSG_TYPE_RESP_AUTH: - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT || - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestReplyState())); } else { LOGE("Device manager auth state error"); - // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } break; case MSG_TYPE_RESP_NEGOTIATE: @@ -300,14 +295,13 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestNegotiateDoneState())); } else { LOGE("Device manager auth state error"); - // authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); } break; case MSG_TYPE_REQ_AUTH_TERMINATE: - if (authResponseState_ == nullptr && + if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseFinishState())); - } else if (authRequestState_ == nullptr && + } else if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { LOGE("Device manager auth state error"); } @@ -440,6 +434,9 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) 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) @@ -544,6 +541,12 @@ void DmAuthManager::AuthenticateFinish() if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW){ CancelDisplay(); } + if (!timerMap_.empty()) { + for (auto &iter : timerMap_) { + iter.second->Stop(SESSION_CANCEL_TIMEOUT); + } + timerMap_.clear(); + } authResponseContext_ = nullptr; authResponseState_ = nullptr; authMessageProcessor_ = nullptr; -- Gitee From 19abc7df5ac2852f42bbfaa8a7e4a5b5076507e1 Mon Sep 17 00:00:00 2001 From: "jia.li" Date: Sat, 8 Jan 2022 20:26:31 +0800 Subject: [PATCH 089/110] TDD lijia 1.8 --- test/unittest/BUILD.gn | 9 +- test/unittest/UTTest_auth_request_state.cpp | 307 ++++++--- test/unittest/UTTest_auth_response_state.cpp | 203 ++++-- test/unittest/UTTest_softbus_connector.cpp | 664 +++++++++++-------- test/unittest/UTTest_softbus_connector.h | 23 +- test/unittest/UTTest_softbus_session.cpp | 310 +++++---- test/unittest/UTTest_softbus_session.h | 29 +- test/unittest/auth_request_state.h | 93 --- test/unittest/auth_response_state.cpp | 175 ----- test/unittest/auth_response_state.h | 82 --- 10 files changed, 942 insertions(+), 953 deletions(-) delete mode 100644 test/unittest/auth_request_state.h delete mode 100644 test/unittest/auth_response_state.cpp delete mode 100644 test/unittest/auth_response_state.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 1dffdf547..e5d4257a8 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -102,12 +102,15 @@ ohos_unittest("UTTest_dm_device_state_manager") { sources = [ "UTTest_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/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/test/unittest/mock/parameter.cpp", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", + "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp", + "//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/test/unittest/mock/parameter.cpp", ] deps = [ ":device_manager_test" ] @@ -226,6 +229,7 @@ config("device_manager_test_common_public_config") { "//base/security/deviceauth/interfaces/innerkits", "//foundation/communication/dsoftbus/interfaces/kits/bus_center", "//foundation/communication/dsoftbus/interfaces/kits/discovery", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/config", ] cflags = [ @@ -298,6 +302,7 @@ config("device_manager_test_common_public") { "//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 = [ diff --git a/test/unittest/UTTest_auth_request_state.cpp b/test/unittest/UTTest_auth_request_state.cpp index 59faeccfa..63c61a475 100644 --- a/test/unittest/UTTest_auth_request_state.cpp +++ b/test/unittest/UTTest_auth_request_state.cpp @@ -36,8 +36,11 @@ void AuthRequestStateTest::TearDownTestCase() namespace{ - std::shared_ptr softbusConnector = std::make_shared(); - std::shared_ptr listener = std::make_shared(); + 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 @@ -94,6 +97,7 @@ HWTEST_F(AuthRequestStateTest, TransitionTo_001, testing::ext::TestSize.Level0) authRequestState->authManager_ = authManager; int32_t ret = authRequestState->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); ASSERT_EQ(ret, DM_FAILED); + sleep(15); } /** @@ -119,6 +123,7 @@ HWTEST_F(AuthRequestStateTest, TransitionTo_002, testing::ext::TestSize.Level0) authRequestState->SetAuthManager(authManager); int32_t ret = authRequestState->TransitionTo(std::shared_ptr(new AuthRequestNegotiateState())); ASSERT_EQ(ret, DM_OK); + sleep(20); } /** @@ -133,6 +138,7 @@ 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); } /** @@ -149,9 +155,11 @@ HWTEST_F(AuthRequestStateTest, Enter_001, testing::ext::TestSize.Level0) 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(nullptr); + authManager = nullptr; + authRequestState->SetAuthManager(authManager); int32_t ret =authRequestState->Enter(); ASSERT_EQ(ret,DM_FAILED); + sleep(15); } /** @@ -177,6 +185,7 @@ HWTEST_F(AuthRequestStateTest, Enter_002, testing::ext::TestSize.Level0) authRequestState->SetAuthContext(context); int32_t ret =authRequestState->Enter(); ASSERT_EQ(ret,DM_OK); + sleep(15); } /** @@ -191,6 +200,7 @@ 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); } /** @@ -203,11 +213,14 @@ HWTEST_F(AuthRequestStateTest,GetStateType_002, testing::ext::TestSize.Level0) */ 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); } /** @@ -220,13 +233,16 @@ HWTEST_F(AuthRequestStateTest, Enter_003, testing::ext::TestSize.Level0) */ 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(); - std::shared_ptr authMessageProcessor = std::make_shared(authManager); + 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"; @@ -234,6 +250,7 @@ HWTEST_F(AuthRequestStateTest, Enter_004, testing::ext::TestSize.Level0) authRequestState->SetAuthContext(context); int32_t ret =authRequestState->Enter(); ASSERT_EQ(ret,DM_OK); + sleep(15); } /** @@ -248,6 +265,7 @@ 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); } /** @@ -260,11 +278,14 @@ HWTEST_F(AuthRequestStateTest, GetStateType_003, testing::ext::TestSize.Level0) */ 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); } /** @@ -275,16 +296,27 @@ HWTEST_F(AuthRequestStateTest, Enter_005, testing::ext::TestSize.Level0) * @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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNegotiateDoneState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret =authRequestState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +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 @@ -298,6 +330,7 @@ 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); } /** @@ -310,32 +343,49 @@ HWTEST_F(AuthRequestStateTest, GetStateType_004, testing::ext::TestSize.Level0) */ 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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestReplyState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret =authRequestState->Enter(); -// ASSERT_EQ(ret,DM_OK); - -// } +/** + * @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 @@ -349,6 +399,7 @@ 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); } /** @@ -361,31 +412,35 @@ HWTEST_F(AuthRequestStateTest, GetStateType_005, testing::ext::TestSize.Level0) */ 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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInputState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret =authRequestState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +/** + * @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 @@ -399,6 +454,7 @@ 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); } /** @@ -411,31 +467,56 @@ HWTEST_F(AuthRequestStateTest, GetStateType_006, testing::ext::TestSize.Level0) */ 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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestJoinState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret = authRequestState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +/** + * @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 @@ -449,6 +530,7 @@ 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); } /** @@ -461,11 +543,14 @@ HWTEST_F(AuthRequestStateTest, GetStateType_007, testing::ext::TestSize.Level0) */ 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); } /** @@ -476,16 +561,24 @@ HWTEST_F(AuthRequestStateTest, Enter_013, testing::ext::TestSize.Level0) * @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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNetworkState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret = authRequestState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +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 @@ -499,6 +592,7 @@ 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); } /** @@ -511,31 +605,50 @@ HWTEST_F(AuthRequestStateTest, GetStateType_008, testing::ext::TestSize.Level0) */ 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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestFinishState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret = authRequestState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +/** + * @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); +} } } } diff --git a/test/unittest/UTTest_auth_response_state.cpp b/test/unittest/UTTest_auth_response_state.cpp index 4cdbdbd90..4a6bad2e4 100644 --- a/test/unittest/UTTest_auth_response_state.cpp +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -37,9 +37,6 @@ void AuthResponseStateTest::TearDownTestCase() namespace{ - std::shared_ptr softbusConnector = std::make_shared(); - std::shared_ptr listener = std::make_shared(); - /** * @tc.name: AuthResponseInitState::SetAuthManager_001 * @tc.desc: 1 set authManager not null @@ -50,11 +47,14 @@ namespace{ */ 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); + ASSERT_EQ(ret,1); + sleep(15); } /** @@ -71,6 +71,7 @@ HWTEST_F(AuthResponseStateTest, SetAuthManager_002, testing::ext::TestSize.Level authResponseState->SetAuthManager(nullptr); int32_t ret = authResponseState->authManager_.use_count(); ASSERT_EQ(ret, 0); + sleep(15); } /** @@ -83,12 +84,15 @@ HWTEST_F(AuthResponseStateTest, SetAuthManager_002, testing::ext::TestSize.Level */ 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); } /** @@ -99,23 +103,23 @@ HWTEST_F(AuthResponseStateTest, TransitionTo_001, testing::ext::TestSize.Level0) * @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); -// } - +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 @@ -129,6 +133,7 @@ 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); } /** @@ -143,6 +148,7 @@ 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); } /** @@ -157,6 +163,7 @@ 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); } /** @@ -169,11 +176,15 @@ HWTEST_F(AuthResponseStateTest,GetStateType_002, testing::ext::TestSize.Level0) */ 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()); - authResponseState->SetAuthManager(nullptr); + authManager = nullptr; + authResponseState->SetAuthManager(authManager); int32_t ret =authResponseState->Enter(); ASSERT_EQ(ret,DM_FAILED); + sleep(15); } /** @@ -184,17 +195,28 @@ HWTEST_F(AuthResponseStateTest, Enter_002, testing::ext::TestSize.Level0) * @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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseNegotiateState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// authResponseState->authManager_ = authManager; -// int32_t ret =authResponseState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +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 @@ -208,6 +230,7 @@ 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); } /** @@ -220,11 +243,14 @@ HWTEST_F(AuthResponseStateTest, GetStateType_003, testing::ext::TestSize.Level0) */ 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); } /** @@ -235,16 +261,17 @@ HWTEST_F(AuthResponseStateTest, Enter_004 , testing::ext::TestSize.Level0) * @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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseConfirmState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret =authResponseState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +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 @@ -258,6 +285,7 @@ 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); } /** @@ -270,11 +298,14 @@ HWTEST_F(AuthResponseStateTest, GetStateType_004, testing::ext::TestSize.Level0) */ 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); } /** @@ -285,16 +316,20 @@ HWTEST_F(AuthResponseStateTest, Enter_006, testing::ext::TestSize.Level0) * @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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseGroupState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret =authResponseState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +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 @@ -308,6 +343,7 @@ 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); } /** @@ -320,11 +356,14 @@ HWTEST_F(AuthResponseStateTest, GetStateType_005, testing::ext::TestSize.Level0) */ 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); } /** @@ -335,16 +374,17 @@ HWTEST_F(AuthResponseStateTest, Enter_008, testing::ext::TestSize.Level0) * @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 data = std::make_shared(softbusConnector, listener); -// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseShowState()); -// std::shared_ptr authManager = std::shared_ptr(data); -// int32_t ret =authResponseState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +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 @@ -358,6 +398,7 @@ 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); } /** @@ -370,11 +411,14 @@ HWTEST_F(AuthResponseStateTest, GetStateType_006, testing::ext::TestSize.Level0) */ 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); } /** @@ -385,13 +429,32 @@ HWTEST_F(AuthResponseStateTest, Enter_010, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -// HWTEST_F(AuthResponseStateTest, Enter_011, testing::ext::TestSize.Level0) -// { -// std::shared_ptr authManager = std::make_shared(softbusConnector, listener); -// std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseFinishState()); -// int32_t ret =authResponseState->Enter(); -// ASSERT_EQ(ret,DM_OK); -// } +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); +} } } } diff --git a/test/unittest/UTTest_softbus_connector.cpp b/test/unittest/UTTest_softbus_connector.cpp index af0c96239..bdd6fd115 100644 --- a/test/unittest/UTTest_softbus_connector.cpp +++ b/test/unittest/UTTest_softbus_connector.cpp @@ -1,5 +1,17 @@ -#include "softbus_connector.h" - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 @@ -7,351 +19,423 @@ #include "parameter.h" #include "system_ability_definition.h" - #include "dm_log.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_device_info.h" +#include "softbus_connector.h" #include "UTTest_softbus_connector.h" -namespace OHOS +namespace OHOS { -namespace DistributedHardware +namespace DistributedHardware { -void DeviceManagerImplTest::SetUp() +void SoftbusConnectorTest::SetUp() { - // DmDiscoveryManage *m_DmDiscoveryManage; } - -void DeviceManagerImplTest::TearDown() +void SoftbusConnectorTest::TearDown() { } - -void DeviceManagerImplTest::SetUpTestCase() +void SoftbusConnectorTest::SetUpTestCase() { } - -void DeviceManagerImplTest::TearDownTestCase() +void SoftbusConnectorTest::TearDownTestCase() { } -namespace -{ - +namespace { static std::shared_ptr softbusConnector = std::make_shared(); -HWTEST_F(DeviceManagerImplTest, Init1, testing::ext::TestSize.Level0) -{ - std::string DM_PKG_NAME = " "; - // char discoverStatus[10] = "not exist"; - int ret = softbusConnector->Init(); - EXPECT_FALSE (ret != DM_OK); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, Init2, testing::ext::TestSize.Level0) -{ - int ret = softbusConnector->Init(); - EXPECT_FALSE (ret = DM_OK); -} -HWTEST_F(DeviceManagerImplTest, Init3, testing::ext::TestSize.Level0) -{ - // char discoverStatus = '0'; - 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); } -HWTEST_F(DeviceManagerImplTest, RegisterSoftbusDiscoveryCallback1, 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(nullptr)); - 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); } -HWTEST_F(DeviceManagerImplTest, RegisterSoftbusDiscoveryCallback2, 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_)); - // softbusConnector->discoveryDeviceInfoMap_; - int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); - EXPECT_EQ(ret1, 1); - 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); } -HWTEST_F(DeviceManagerImplTest, RegisterSoftbusDiscoveryCallback3, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - 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_)); - // softbusConnector->discoveryDeviceInfoMap_; - int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); - EXPECT_EQ(ret1, 1); - 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); } -HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusDiscoveryCallback1, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - //std::shared_ptr listener_ = std::make_shared(); - //std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); - int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); - // softbusConnector->discoveryDeviceInfoMap_; - int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); - EXPECT_EQ(ret1, 0); - EXPECT_EQ(ret, DM_OK); - // softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(discoveryMgr_)); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusDiscoveryCallback2, 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_); - softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(nullptr)); - int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); - EXPECT_EQ(ret1, 1); - int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); - // softbusConnector->discoveryDeviceInfoMap_; - int ret2 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); - EXPECT_EQ(ret2, 0); - EXPECT_EQ(ret, DM_OK); - // softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(discoveryMgr_)); -} -HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusDiscoveryCallback3, 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_); - softbusConnector->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(discoveryMgr_)); - int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); - EXPECT_EQ(ret1, 1); - int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); - // softbusConnector->discoveryDeviceInfoMap_; - int ret2 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); - EXPECT_EQ(ret2, 0); - 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); } -// HWTEST_F(DeviceManagerImplTest, RegisterSoftbusStateCallback2, 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_); -// std::cout << "11111111111"; -// std::shared_ptr deviceState = std::make_shared(softbusConnector, listener); -// std::cout << "111111112222222222111"; -// int ret = softbusConnector->RegisterSoftbusStateCallback(pkgName, std::shared_ptr(deviceState)); -// std::cout << "1111111133333333333333111"; -// // softbusConnector->discoveryDeviceInfoMap_; -// int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); -// EXPECT_EQ(ret1, 1); -// EXPECT_EQ(ret, DM_OK); -// softbusConnector->UnRegisterSoftbusStateCallback(pkgName); -// } +/** + * @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); +} -// HWTEST_F(DeviceManagerImplTest, RegisterSoftbusStateCallback3, testing::ext::TestSize.Level0) -// { -// std::string pkgName = ""; -// std::shared_ptr listener = std::make_shared(); -// std::cout << "11111111444444111"; -// // std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); -// std::shared_ptr deviceState = std::make_shared(softbusConnector, listener); -// std::cout << "1111111777771111"; -// int ret = softbusConnector->RegisterSoftbusStateCallback(pkgName, std::shared_ptr(deviceState)); -// // softbusConnector->discoveryDeviceInfoMap_; -// std::cout << "111111111199999991"; -// int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); -// EXPECT_EQ(ret1, 1); -// EXPECT_EQ(ret, DM_OK); -// softbusConnector->UnRegisterSoftbusStateCallback(pkgName); -// } +/** + * @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); +} -HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusStateCallback1, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - //std::shared_ptr listener_ = std::make_shared(); - //std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); - int ret = softbusConnector->UnRegisterSoftbusStateCallback(pkgName); - // softbusConnector->discoveryDeviceInfoMap_; - int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); - EXPECT_EQ(ret1, 0); - EXPECT_EQ(ret, DM_OK); -} -HWTEST_F(DeviceManagerImplTest, UnRegisterSoftbusStateCallback2, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - //std::shared_ptr listener_ = std::make_shared(); - //std::shared_ptr discoveryMgr_ = std::make_shared( softbusConnector, listener_); - int ret = softbusConnector->UnRegisterSoftbusStateCallback(pkgName); - // softbusConnector->discoveryDeviceInfoMap_; - int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); - EXPECT_EQ(ret1, 0); - EXPECT_EQ(ret, DM_OK); -} -HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList1, testing::ext::TestSize.Level0) -{ - // std::string pkgName = "com.softbus.test"; - std::vector deviceInfoList; - std::string pkgName = ""; - int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); - std::cout << "ret = " << ret << std::endl; - EXPECT_EQ(ret, DM_OK); -} -HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList2, testing::ext::TestSize.Level0) -{ - std::vector deviceInfoList; - std::string pkgName = "com.softbus.test"; - int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); - std::cout << "ret = " << ret << std::endl; - EXPECT_EQ(ret, DM_OK); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList3, testing::ext::TestSize.Level0) -{ - std::vector deviceInfoList; - std::string pkgName = "com.softbus.test"; - std::string DM_PKG_NAME = " "; - int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); - std::cout << "ret= " << ret << std::endl; - EXPECT_EQ(ret, DM_OK); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo1, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - DmDeviceInfo deviceInfo; - int ret = softbusConnector->GetLocalDeviceInfo(deviceInfo); - std::cout << "ret= " << ret << std::endl; - EXPECT_EQ(ret, DM_OK); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo2, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.softbus.test"; - DmDeviceInfo deviceInfo; - int ret = softbusConnector->GetLocalDeviceInfo(deviceInfo); - std::cout << "ret = " << ret << std::endl; - EXPECT_EQ(ret, DM_OK); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo3, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.softbus.test"; - DmDeviceInfo deviceInfo; - std::string DM_PKG_NAME = " "; - int ret =softbusConnector->GetLocalDeviceInfo(deviceInfo); - EXPECT_EQ(ret, DM_OK); + +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, StartDiscovery1, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.softbus.test"; - std::string DM_PKG_NAME = ""; -// std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; - DmSubscribeInfo dmSubscribeInfo; - int ret = softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::cout << "ret = " << ret << std::endl; - EXPECT_EQ(ret, DM_DISCOVERY_FAILED); -} -HWTEST_F(DeviceManagerImplTest, StartDiscovery2, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; -// std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; - DmSubscribeInfo dmSubscribeInfo; - int ret = softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::cout << "ret = " << ret << std::endl; - EXPECT_EQ(ret, DM_DISCOVERY_FAILED); -} -HWTEST_F(DeviceManagerImplTest, StartDiscovery3, testing::ext::TestSize.Level0) -{ - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1; - dmSubscribeInfo.mode = DM_DISCOVER_MODE_PASSIVE; - /** Service subscription medium. For details, see {@link DmExchangeMedium}. */ - dmSubscribeInfo.medium = DM_COAP; - /** Service subscription frequency. For details, see {@link DmExchangeFreq}. */ - dmSubscribeInfo.freq = DM_MID; - /** only find the device with the same account */ - dmSubscribeInfo.isSameAccount = true; - /** find the sleeping devices */ - dmSubscribeInfo.isWakeRemote = false; - // std::string pkgName = ""; - // std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; - int ret = softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::cout << "ret = " << ret << std::endl; - EXPECT_EQ(ret, DM_DISCOVERY_FAILED); -} -HWTEST_F(DeviceManagerImplTest, StopDiscovery1, testing::ext::TestSize.Level0) -{ - std::string DM_PKG_NAME = ""; - uint16_t subscribeId = 1; - int ret = softbusConnector->StopDiscovery(subscribeId); - EXPECT_TRUE(ret != 0); + +/** + * @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); } -// HWTEST_F(DeviceManagerImplTest, StopDiscovery2, testing::ext::TestSize.Level0) -// { -// std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; -// uint16_t subscribeId = 1; -// -// int ret = softbusConnector->StopDiscovery(subscribeId); -// EXPECT_EQ(ret, DM_OK); -// } -HWTEST_F(DeviceManagerImplTest, StopDiscovery3, testing::ext::TestSize.Level0) -{ - uint16_t subscribeId = 1; - int ret = softbusConnector->StopDiscovery(subscribeId); - std::cout << "ret= "<GetConnectAddr(deviceId, connectAddr); + EXPECT_EQ(ret, nullptr); } -HWTEST_F(DeviceManagerImplTest, IsDeviceOnLine1, testing::ext::TestSize.Level0) -{ - std::string deviceId = "12333"; - std::string DM_PKG_NAME = ""; - bool ret = softbusConnector->IsDeviceOnLine(deviceId); - EXPECT_EQ(ret, false); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, IsDeviceOnLine2, testing::ext::TestSize.Level0) -{ - std::string deviceId = "145677"; - std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; - bool ret = softbusConnector->IsDeviceOnLine(deviceId); - EXPECT_EQ(ret, false); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, IsDeviceOnLine3, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; +/** + * @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); +} - if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { - deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; - } +/** + * @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); +} - bool ret = softbusConnector->IsDeviceOnLine(deviceId); - EXPECT_EQ(ret, false); +/** + * @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); +} } } } \ No newline at end of file diff --git a/test/unittest/UTTest_softbus_connector.h b/test/unittest/UTTest_softbus_connector.h index 09373e381..757b1b8c1 100644 --- a/test/unittest/UTTest_softbus_connector.h +++ b/test/unittest/UTTest_softbus_connector.h @@ -1,3 +1,17 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 @@ -22,10 +36,13 @@ #include "device_manager_service_listener.h" #include "dm_discovery_manager.h" #include "dm_device_state_manager.h" -namespace OHOS { -namespace DistributedHardware { +namespace OHOS +{ +namespace DistributedHardware +{ - class DeviceManagerImplTest : public testing::Test { + class SoftbusConnectorTest : public testing::Test +{ public: static void SetUpTestCase(); static void TearDownTestCase(); diff --git a/test/unittest/UTTest_softbus_session.cpp b/test/unittest/UTTest_softbus_session.cpp index 9d56f0733..b7c7db3a8 100644 --- a/test/unittest/UTTest_softbus_session.cpp +++ b/test/unittest/UTTest_softbus_session.cpp @@ -1,4 +1,17 @@ - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_constants.h" #include "dm_log.h" @@ -7,164 +20,191 @@ #include "UTTest_softbus_session.h" #include "softbus_session.h" - -namespace OHOS +namespace OHOS { -namespace DistributedHardware +namespace DistributedHardware { - -void DeviceManagerImplTest::SetUp() +void SoftbusSessionTest::SetUp() { } - -void DeviceManagerImplTest::TearDown() +void SoftbusSessionTest::TearDown() { } - -void DeviceManagerImplTest::SetUpTestCase() +void SoftbusSessionTest::SetUpTestCase() { } - -void DeviceManagerImplTest::TearDownTestCase() +void SoftbusSessionTest::TearDownTestCase() { } -namespace -{ - -std::shared_ptr softbusSession = std::make_shared(); -HWTEST_F(DeviceManagerImplTest, OpenAuthSession1, testing::ext::TestSize.Level0) -{ - std::string deviceId = ""; - int ret = softbusSession->OpenAuthSession(deviceId); - EXPECT_EQ(ret, -1); -} -HWTEST_F(DeviceManagerImplTest, OpenAuthSession2, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; - if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { - deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; - } +namespace { - // std::string deviceId = "SoftbusConnector::discoveryCallbackMap_[pkgName]"; - std::string DM_SESSION_NAME = ""; - int ret = softbusSession->OpenAuthSession(deviceId); - EXPECT_EQ(ret, -1); -} -HWTEST_F(DeviceManagerImplTest, OpenAuthSession3, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; +std::shared_ptr softbusSession = std::make_shared(); - if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { - deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; - } - - std::string DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; - int ret = softbusSession->OpenAuthSession(deviceId); - EXPECT_EQ(ret, -1); -} -HWTEST_F(DeviceManagerImplTest, SendData1, testing::ext::TestSize.Level0) -{ - std::string message = ""; - int32_t sessionId = -1; - int ret = softbusSession->SendData(sessionId, message); - EXPECT_EQ(ret, DM_FAILED); -} -HWTEST_F(DeviceManagerImplTest, SendData2, testing::ext::TestSize.Level0) -{ - nlohmann::json jsonObj; - jsonObj[TAG_VER] = DM_ITF_VER; - std::string msgType; - jsonObj[TAG_TYPE] = msgType; - std::string message = jsonObj.dump(); - int32_t sessionId = -1; - int ret = softbusSession->SendData(sessionId, message); - EXPECT_EQ(ret, DM_FAILED); -} -HWTEST_F(DeviceManagerImplTest, SendData3, testing::ext::TestSize.Level0) -{ - nlohmann::json jsonObj; - std::string msgType; - jsonObj[TAG_VER] = DM_ITF_VER; - jsonObj[TAG_TYPE] = msgType; - std::string message = jsonObj.dump(); - int32_t sessionId = 1; - int ret = softbusSession->SendData(sessionId, message); - EXPECT_EQ(ret, DM_FAILED); +/** + * @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); } - - - -HWTEST_F(DeviceManagerImplTest, OnSessionOpened1, testing::ext::TestSize.Level0) +/** + * @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) { - int result = 0; - int32_t sessionId = -1; - int ret = softbusSession->OnSessionOpened(sessionId, result); - - EXPECT_EQ(ret, DM_OK); + std::string deviceId = "123456"; + int ret = softbusSession->OpenAuthSession(deviceId); + EXPECT_EQ(ret, -1); } -HWTEST_F(DeviceManagerImplTest, OnSessionOpened2, testing::ext::TestSize.Level0) + +/** + * @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) { - int result = 0; + std::string message = ""; + int32_t sessionId = -1; + int ret = softbusSession->SendData(sessionId, message); + EXPECT_EQ(ret, DM_FAILED); +} - int32_t sessionId = 0; - int ret = softbusSession->OnSessionOpened(sessionId, result); - EXPECT_EQ(ret, DM_OK); +/** + * @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); } -HWTEST_F(DeviceManagerImplTest, OnSessionOpened3, testing::ext::TestSize.Level0) -{ - int result = 0; - std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; +/** + * @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); +} - if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { - deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; - } - int32_t sessionId = softbusSession->OpenAuthSession(deviceId); - 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); +} } } } diff --git a/test/unittest/UTTest_softbus_session.h b/test/unittest/UTTest_softbus_session.h index 77ada094a..987177018 100644 --- a/test/unittest/UTTest_softbus_session.h +++ b/test/unittest/UTTest_softbus_session.h @@ -1,8 +1,20 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "softbus_session.h" #include #include #include @@ -10,17 +22,22 @@ #include #include #include + #include "session.h" #include "inner_session.h" #include "softbus_session_callback.h" #include "device_manager_service_listener.h" #include "dm_discovery_manager.h" #include "dm_device_state_manager.h" +#include "softbus_session.h" -namespace OHOS { -namespace DistributedHardware { +namespace OHOS +{ +namespace DistributedHardware +{ - class DeviceManagerImplTest : public testing::Test { +class SoftbusSessionTest : public testing::Test +{ public: static void SetUpTestCase(); static void TearDownTestCase(); @@ -31,4 +48,4 @@ public: } #undef private #undef protected -#endif \ No newline at end of file +#endif \ No newline at end of file diff --git a/test/unittest/auth_request_state.h b/test/unittest/auth_request_state.h deleted file mode 100644 index 539dde308..000000000 --- a/test/unittest/auth_request_state.h +++ /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. - */ - -#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(); - }; - virtual int32_t GetStateType() = 0; - virtual int32_t Enter() = 0; - int32_t Leave(); - int32_t TransitionTo(std::shared_ptr state); - // void SetLastState(std::shared_ptr state); - int32_t SetAuthManager(std::shared_ptr authManager); - int32_t SetAuthContext(std::shared_ptr context); - std::shared_ptr GetAuthContext(); -protected: - std::weak_ptr authManager_; - // std::shared_ptr lastState_; - std::shared_ptr context_; -}; - -class AuthRequestInitState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestNegotiateState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; -class AuthRequestNegotiateDoneState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestReplyState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestInputState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestJoinState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestNetworkState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestFinishState : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif //OHOS_DM_AUTH_REQUEST_STATE_H diff --git a/test/unittest/auth_response_state.cpp b/test/unittest/auth_response_state.cpp deleted file mode 100644 index d8c2a30eb..000000000 --- a/test/unittest/auth_response_state.cpp +++ /dev/null @@ -1,175 +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_response_state.h" - -#include "dm_log.h" -#include "dm_constants.h" -#include "dm_auth_manager.h" - -namespace OHOS { -namespace DistributedHardware { - -int32_t AuthResponseState::Leave() -{ - return DM_OK; -} - -int32_t AuthResponseState::SetAuthContext(std::shared_ptr context) { - context_ = std::move(context); - return DM_OK; -} - -std::shared_ptr AuthResponseState::GetAuthContext() { - return context_; -} - -int32_t AuthResponseState::SetAuthManager(std::shared_ptr authManager) -{ - authManager_ = std::move(authManager); - return DM_OK; -} - -// void AuthResponseState::SetLastState(std::shared_ptr state) -// { -// lastState_ = state; -// } - -int32_t AuthResponseState::TransitionTo(std::shared_ptr state) -{ - LOGI("AuthRequestState:: TransitionTo"); - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return DM_FAILED; - } - state->SetAuthManager(stateAuthManager); - // state->SetLastState((std::shared_ptr)this); - // lastState_ = state; - stateAuthManager->SetAuthResponseState(state); - state->SetAuthContext(context_); - this->Leave(); - state->Enter(); - return DM_OK; -} - -int32_t AuthResponseInitState::GetStateType() -{ - return AuthState::AUTH_RESPONSE_INIT; -} - -int32_t AuthResponseInitState::Enter() -{ - LOGI("AuthResponse:: AuthResponseInitState Enter"); - //1.认证通道建立后,进入该状态 - return DM_OK; -} - -int32_t AuthResponseNegotiateState::GetStateType() -{ - return AuthState::AUTH_RESPONSE_NEGOTIATE; -} - -int32_t AuthResponseNegotiateState::Enter() -{ - //1.收到协商消息后进入 - - //2. 获取本地加解密模块信息,并回复消 - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return DM_FAILED; - } - stateAuthManager->RespNegotiate(context_->sessionId); - return DM_OK; -} - -int32_t AuthResponseConfirmState::GetStateType() -{ - return AuthState::AUTH_RESPONSE_CONFIRM; -} - -int32_t AuthResponseConfirmState::Enter() -{ - //委托授权UI模块进行用户交互 - //如果交互成功 - // TransitionTo(new AuthResponseGroupState()); - LOGI("AuthResponse:: AuthResponseConfirmState Enter"); - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return DM_FAILED; - } - stateAuthManager->ShowConfigDialog(); - return DM_OK; -} - -int32_t AuthResponseGroupState::GetStateType() -{ - return AuthState::AUTH_RESPONSE_GROUP; -} - -int32_t AuthResponseGroupState::Enter() -{ -// //1.创建群组, -// authManagerPtr_->GetHiChainConnector()->CreateGroup(); - LOGI("AuthResponse:: AuthResponseGroupState Enter"); - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return DM_FAILED; - } - stateAuthManager->CreateGroup(); - return DM_OK; -} - -int32_t AuthResponseShowState::GetStateType() -{ - return AuthState::AUTH_RESPONSE_SHOW; -} - -int32_t AuthResponseShowState::Enter() -{ - //1.委托认证实现模块进行用户交互 - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return DM_FAILED; - } - stateAuthManager->ShowAuthInfoDialog(); - return DM_OK; -} - -int32_t AuthResponseFinishState::GetStateType() -{ - return AuthState::AUTH_RESPONSE_FINISH; -} - -int32_t AuthResponseFinishState::Enter() -{ - //1.结束UI显示 - - //2.清理资源,结束状态机 - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return DM_FAILED; - } - stateAuthManager->AuthenticateFinish(); - return DM_OK; - -} -} -} diff --git a/test/unittest/auth_response_state.h b/test/unittest/auth_response_state.h deleted file mode 100644 index ecadd7c6c..000000000 --- a/test/unittest/auth_response_state.h +++ /dev/null @@ -1,82 +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_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 int32_t Enter() = 0; - int32_t Leave(); - int32_t TransitionTo(std::shared_ptr state); - // void SetLastState(std::shared_ptr state); - int32_t SetAuthManager(std::shared_ptr authManager); - int32_t SetAuthContext(std::shared_ptr context); - std::shared_ptr GetAuthContext(); -protected: - std::weak_ptr authManager_; - // std::shared_ptr lastState_; - std::shared_ptr context_; -}; - -class AuthResponseInitState : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthResponseNegotiateState : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthResponseConfirmState : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthResponseGroupState : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthResponseShowState : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthResponseFinishState : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif //OHOS_DM_AUTH_RESPONSE_STATE_H -- Gitee From 013d16b146891a40ce532baba360c9369dc3cfa2 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Sat, 8 Jan 2022 22:24:42 +0800 Subject: [PATCH 090/110] data mofdify --- .../src/authentication/dm_auth_manager.cpp | 3 ++- .../dependency/softbus/softbus_session.cpp | 22 ++++--------------- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 66a404d49..513863075 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -606,7 +606,7 @@ std::string DmAuthManager::GenerateGroupName() char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; - std::string groupName = authRequestContext_->targetPkgName + authRequestContext_->hostPkgName + + std::string groupName = authResponseContext_->targetPkgName + authResponseContext_->hostPkgName + sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); return groupName; } @@ -674,6 +674,7 @@ void DmAuthManager::ShowStartAuthDialog() int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) { + dmAbilityMgr_->StartAbilityDone(); AbilityRole role = dmAbilityMgr_->GetAbilityRole(); authParam.direction = (int32_t)role; // Currently, only Support PinCode, authType not save. diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 572d1d28f..b3ac1317c 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -111,12 +111,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) iter.second->GetIsCryptoSupport(isCryptoSupport); } if (isCryptoSupport) { - uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), (MSG_MAX_SIZE + ENCRYPT_TAG_LEN)); - if (buf == nullptr) { - LOGE("SendData: malloc memory failed"); - return DM_MALLOC_ERROR; - } - free(buf); + LOGI("SoftbusSession::SendData Start encryption"); } int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); if (ret != DM_OK) { @@ -154,19 +149,10 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 iter.second->GetIsCryptoSupport(isCryptoSupport); } if (isCryptoSupport) { - uint8_t *buf = (uint8_t *)calloc(sizeof(uint8_t), dataLen + 1); - if (buf == nullptr) { - LOGE("SendMsg: malloc memory failed"); - return; - } - std::string message = (char *)buf; - for (auto &iter : sessionCallbackMap_) { - iter.second->OnDataReceived(iter.first, sessionId, message); - } - free(buf); + LOGI("SoftbusSession::OnBytesReceived Start decryption"); } - char *dataChar = (char *)data; - std::string message = dataChar; + char* messageData = (char*)data; + std::string message = std::string(messageData, strlen(messageData)); for (auto &iter : sessionCallbackMap_) { iter.second->OnDataReceived(iter.first, sessionId, message); } -- Gitee From 36643b5764c38ef24e34c82fdc40d3e3e8a27b58 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Sun, 9 Jan 2022 18:11:19 +0800 Subject: [PATCH 091/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E5=87=A0?= =?UTF-8?q?=E5=A4=84=E4=BB=A3=E7=A0=81=E9=94=99=E8=AF=AFbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/auth_request_state.cpp | 18 +++++++++--------- .../src/authentication/auth_response_state.cpp | 12 ++++++------ .../src/authentication/dm_auth_manager.cpp | 2 +- .../src/dependency/softbus/softbus_session.cpp | 3 +-- test/unittest/auth_request_state.cpp | 18 +++++++++--------- 5 files changed, 26 insertions(+), 27 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/auth_request_state.cpp b/services/devicemanagerservice/src/authentication/auth_request_state.cpp index 2ceb10fa7..1323b4e6d 100644 --- a/services/devicemanagerservice/src/authentication/auth_request_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_request_state.cpp @@ -49,7 +49,7 @@ std::shared_ptr AuthRequestState::GetAuthContext() void AuthRequestState::TransitionTo(std::shared_ptr state) { LOGE("AuthRequestState::TransitionTo"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -68,7 +68,7 @@ int32_t AuthRequestInitState::GetStateType() void AuthRequestInitState::Enter() { - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -84,7 +84,7 @@ int32_t AuthRequestNegotiateState::GetStateType() void AuthRequestNegotiateState::Enter() { // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -105,7 +105,7 @@ void AuthRequestNegotiateDoneState::Enter() // authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH); // std::string message; // softbusSession_->SendData(context_.sessionId, message); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -125,7 +125,7 @@ void AuthRequestReplyState::Enter() // 2. 用户授权同意 // 3. 回调给认证实现模块,启动认证 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -144,7 +144,7 @@ void AuthRequestInputState::Enter() // // //2. 验证认证信息 LOGE("DmAuthManager::AuthRequestInputState"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -161,7 +161,7 @@ void AuthRequestJoinState::Enter() { // 1. 加入群组 LOGE("DmAuthManager::AuthRequestJoinState"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -177,7 +177,7 @@ int32_t AuthRequestNetworkState::GetStateType() void AuthRequestNetworkState::Enter() { // 1. 进行组网 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -194,7 +194,7 @@ void AuthRequestFinishState::Enter() { // 1. 清理资源 // 2. 通知对端认证结束,并关闭认证通道 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp index 1a530d834..219441448 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -44,7 +44,7 @@ void AuthResponseState::SetAuthManager(std::shared_ptr authManage void AuthResponseState::TransitionTo(std::shared_ptr state) { LOGI("AuthRequestState:: TransitionTo"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -77,7 +77,7 @@ void AuthResponseNegotiateState::Enter() // 1.收到协商消息后进入 // 2. 获取本地加解密模块信息,并回复消 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -96,7 +96,7 @@ void AuthResponseConfirmState::Enter() //如果交互成功 // TransitionTo(new AuthResponseGroupState()); LOGI("AuthResponse:: AuthResponseConfirmState Enter"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -114,7 +114,7 @@ void AuthResponseGroupState::Enter() // //1.创建群组, // authManagerPtr_->GetHiChainConnector()->CreateGroup(); LOGI("AuthResponse:: AuthResponseGroupState Enter"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -130,7 +130,7 @@ int32_t AuthResponseShowState::GetStateType() void AuthResponseShowState::Enter() { // 1.委托认证实现模块进行用户交互 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; @@ -148,7 +148,7 @@ void AuthResponseFinishState::Enter() // 1.结束UI显示 // 2.清理资源,结束状态机 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 513863075..ec6e83343 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -233,7 +233,7 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI } else { if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this()); - authRequestContext_ ->sessionId = sessionId; + authRequestContext_->sessionId = sessionId; authRequestState_->SetAuthContext(authRequestContext_); authMessageProcessor_->SetRequestContext(authRequestContext_); authResponseContext_ = std::make_shared(); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index b3ac1317c..89d1ba47e 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -151,8 +151,7 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 if (isCryptoSupport) { LOGI("SoftbusSession::OnBytesReceived Start decryption"); } - char* messageData = (char*)data; - std::string message = std::string(messageData, strlen(messageData)); + std::string message = std::string((const char*)data, dataLen); for (auto &iter : sessionCallbackMap_) { iter.second->OnDataReceived(iter.first, sessionId, message); } diff --git a/test/unittest/auth_request_state.cpp b/test/unittest/auth_request_state.cpp index 504e3c7b5..ea6fb9896 100644 --- a/test/unittest/auth_request_state.cpp +++ b/test/unittest/auth_request_state.cpp @@ -47,7 +47,7 @@ std::shared_ptr AuthRequestState::GetAuthContext() { int32_t AuthRequestState::TransitionTo(std::shared_ptr state) { LOGE("AuthRequestState::TransitionTo"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -65,7 +65,7 @@ int32_t AuthRequestInitState::GetStateType() { } int32_t AuthRequestInitState::Enter() { - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -80,7 +80,7 @@ int32_t AuthRequestNegotiateState::GetStateType() { int32_t AuthRequestNegotiateState::Enter() { // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -100,7 +100,7 @@ int32_t AuthRequestNegotiateDoneState::Enter() { // authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH); // std::string message; // softbusSession_->SendData(context_.sessionId, message); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -119,7 +119,7 @@ int32_t AuthRequestReplyState::Enter() { //2. 用户授权同意 //3. 回调给认证实现模块,启动认证 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -137,7 +137,7 @@ int32_t AuthRequestInputState::Enter() { // // //2. 验证认证信息 LOGE("DmAuthManager::AuthRequestInputState"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -153,7 +153,7 @@ int32_t AuthRequestJoinState::GetStateType() { int32_t AuthRequestJoinState::Enter() { //1. 加入群组 LOGE("DmAuthManager::AuthRequestJoinState"); - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -168,7 +168,7 @@ int32_t AuthRequestNetworkState::GetStateType() { int32_t AuthRequestNetworkState::Enter() { //1. 进行组网 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; @@ -184,7 +184,7 @@ int32_t AuthRequestFinishState::GetStateType() { int32_t AuthRequestFinishState::Enter() { //1. 清理资源 //2. 通知对端认证结束,并关闭认证通道 - std::shared_ptr stateAuthManager = authManager_.lock(); + std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; -- Gitee From cd981284c01078b77423d7c01df88a1b65ed8757 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Sun, 9 Jan 2022 18:29:32 +0800 Subject: [PATCH 092/110] add by weidong.liu@thundersoft.com change: fix auth bug --- ext/pin_auth/src/pin_auth.cpp | 8 +++----- .../src/authentication/dm_auth_manager.cpp | 4 ++-- .../src/dependency/hichain/hichain_connector.cpp | 6 +++--- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index d4bfa1c84..27497578d 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -52,15 +52,13 @@ int32_t PinAuth::VerifyAuthentication(std::string pinToken, int32_t code, const LOGE("DecodeRequestAuth jsonStr error"); return DM_FAILED; } - - if (!jsonObject.contains(PIN_CODE_KEY) && !jsonObject.contains(TAG_TOKEN)){ + 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]; - std::string inputPinToken = jsonObject[TAG_TOKEN]; - if (code == inputPinCode && pinToken == inputPinToken){ + 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; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 513863075..379d2e809 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -338,11 +338,11 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) { LOGI("DmAuthManager OnMemberJoin start"); CancelDisplay(); - timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + //timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); LOGE("DmAuthManager OnMemberJoin start"); if (authRequestState_ != nullptr) { - timerMap_[ADD_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + //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())); diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 0652bcb69..69ebb6822 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -196,9 +196,9 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectIn 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()); + //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; -- Gitee From ab0b87f9ae06ab50a396ca757fea5f86fcc4d2e2 Mon Sep 17 00:00:00 2001 From: puhui Date: Mon, 10 Jan 2022 09:52:08 +0800 Subject: [PATCH 093/110] =?UTF-8?q?=E7=BC=96=E7=A8=8B=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E6=89=AB=E6=8F=8F=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- .../ipc/model/ipc_authenticate_device_req.h | 3 +- .../include/ipc/model/ipc_get_dmfaparam_rsp.h | 3 +- .../ipc/model/ipc_get_info_by_network_req.h | 4 +- .../ipc/model/ipc_get_info_by_network_rsp.h | 4 +- .../ipc/model/ipc_get_local_device_info_rsp.h | 3 +- .../ipc/model/ipc_get_trustdevice_req.h | 2 +- .../ipc/model/ipc_get_trustdevice_rsp.h | 3 +- .../ipc/model/ipc_notify_auth_result_req.h | 2 +- .../ipc/model/ipc_notify_device_found_req.h | 3 +- .../ipc/model/ipc_notify_device_state_req.h | 3 +- .../model/ipc_notify_discover_result_req.h | 2 +- .../ipc/model/ipc_notify_dmfa_result_req.h | 2 +- .../model/ipc_notify_verify_auth_result_req.h | 2 +- .../ipc/model/ipc_register_listener_req.h | 2 +- common/include/ipc/model/ipc_req.h | 2 +- common/include/ipc/model/ipc_rsp.h | 2 +- .../ipc/model/ipc_set_useroperation_req.h | 3 +- .../ipc/model/ipc_start_discovery_req.h | 3 +- .../ipc/model/ipc_stop_discovery_req.h | 2 +- .../ipc/model/ipc_unauthenticate_device_req.h | 3 +- .../ipc/model/ipc_verify_authenticate_req.h | 2 +- ext/crypto/BUILD.gn | 69 ----- ext/ds/BUILD.gn | 68 ----- .../include/ability/dm_ability_manager.h | 5 +- ext/pin_auth/include/pin_auth.h | 1 + .../src/ability/lite/dm_ability_manager.cpp | 6 +- .../ability/standard/dm_ability_manager.cpp | 9 +- ext/pin_auth/src/pin_auth.cpp | 11 +- ext/profile/include/device_profile_adapter.h | 7 +- ext/profile/include/profile_connector.h | 22 +- ext/profile/src/device_profile_adapter.cpp | 18 +- ext/profile/src/profile_connector.cpp | 36 ++- .../native_cpp/include/device_manager.h | 6 +- .../native_cpp/include/device_manager_impl.h | 4 +- .../native_cpp/include/ipc/ipc_client.h | 4 +- .../native_cpp/include/ipc/ipc_client_proxy.h | 2 +- .../include/ipc/lite/ipc_client_manager.h | 4 +- .../ipc/lite/ipc_client_server_proxy.h | 5 +- .../include/ipc/lite/ipc_client_stub.h | 5 +- .../include/ipc/standard/ipc_client_manager.h | 5 +- .../ipc/standard/ipc_client_server_proxy.h | 2 +- .../include/ipc/standard/ipc_client_stub.h | 5 +- .../include/ipc/standard/ipc_remote_broker.h | 3 +- .../include/notify/device_manager_notify.h | 13 +- .../native_cpp/src/device_manager_impl.cpp | 33 +- .../native_cpp/src/ipc/ipc_client_proxy.cpp | 2 +- .../src/ipc/lite/ipc_client_manager.cpp | 1 - .../src/ipc/lite/ipc_client_server_proxy.cpp | 7 +- .../src/ipc/lite/ipc_client_stub.cpp | 5 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 21 +- .../src/ipc/standard/ipc_client_manager.cpp | 6 +- .../ipc/standard/ipc_client_server_proxy.cpp | 5 +- .../src/ipc/standard/ipc_client_stub.cpp | 8 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 30 +- .../src/notify/device_manager_notify.cpp | 7 +- interfaces/kits/js/include/dm_native_event.h | 1 + .../kits/js/include/native_devicemanager_js.h | 5 +- .../kits/js/src/native_devicemanager_js.cpp | 2 +- .../include/ability/dm_ability_manager.h | 5 +- .../include/adapter/dm_adapter_manager.h | 2 +- .../include/adapter/profile_adapter.h | 2 +- .../authentication/auth_message_processor.h | 3 +- .../authentication/auth_request_state.h | 3 +- .../include/authentication/dm_auth_manager.h | 12 +- .../include/config/config_manager.h | 6 +- .../include/config/json_config.h | 4 +- .../commonevent/event_manager_adapt.h | 6 +- .../dependency/hichain/hichain_connector.h | 8 +- .../dependency/softbus/softbus_connector.h | 10 +- .../dependency/softbus/softbus_session.h | 9 +- .../include/dependency/timer/dm_timer.h | 7 +- .../include/device_manager_service.h | 6 +- .../include/device_manager_service_listener.h | 4 +- .../deviceinfo/dm_device_info_manager.h | 2 +- .../devicestate/dm_device_state_manager.h | 5 +- .../include/discovery/dm_discovery_manager.h | 3 +- .../include/ipc/lite/ipc_server_listener.h | 3 +- .../include/ipc/lite/ipc_server_listenermgr.h | 4 +- .../include/ipc/standard/ipc_server_stub.h | 12 +- .../ability/standard/dm_ability_manager.cpp | 2 +- .../src/adapter/lite/dm_adapter_manager.cpp | 3 +- .../adapter/standard/dm_adapter_manager.cpp | 3 +- .../authentication/auth_message_processor.cpp | 4 +- .../authentication/auth_response_state.cpp | 4 +- .../src/authentication/auth_ui.cpp | 4 +- .../src/authentication/dm_auth_manager.cpp | 44 ++- .../src/config/config_manager.cpp | 2 +- .../dependency/hichain/hichain_connector.cpp | 18 +- .../dependency/softbus/softbus_connector.cpp | 18 +- .../dependency/softbus/softbus_session.cpp | 7 +- .../src/device_manager_service.cpp | 6 +- .../src/device_manager_service_listener.cpp | 11 +- .../src/deviceinfo/dm_device_info_manager.cpp | 2 +- .../devicestate/dm_device_state_manager.cpp | 12 +- .../src/discovery/dm_discovery_manager.cpp | 21 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 7 +- .../src/ipc/lite/ipc_server_listener.cpp | 3 +- .../src/ipc/lite/ipc_server_main.cpp | 8 +- .../src/ipc/lite/ipc_server_stub.cpp | 15 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 34 ++- .../ipc/standard/ipc_server_client_proxy.cpp | 7 +- .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 12 +- test/unittest/UTTest_auth_request_state.cpp | 155 +++++----- test/unittest/UTTest_auth_request_state.h | 12 +- test/unittest/UTTest_auth_response_state.cpp | 154 ++++++---- test/unittest/UTTest_auth_response_state.h | 6 +- .../UTTest_device_manager_service.cpp | 66 ++-- test/unittest/UTTest_device_manager_service.h | 15 +- ...UTTest_device_manager_service_listener.cpp | 44 +-- .../UTTest_device_manager_service_listener.h | 9 +- .../UTTest_dm_device_info_manager.cpp | 30 +- test/unittest/UTTest_dm_device_info_manager.h | 11 +- test/unittest/UTTest_hichain_connector.cpp | 286 +++++++++--------- test/unittest/UTTest_hichain_connector.h | 19 +- test/unittest/UTTest_softbus_connector.cpp | 128 ++++---- test/unittest/UTTest_softbus_connector.h | 36 ++- test/unittest/UTTest_softbus_session.cpp | 67 ++-- test/unittest/UTTest_softbus_session.h | 28 +- test/unittest/auth_request_state.cpp | 119 +++++--- test/unittest/device_manager_impl_test.cpp | 47 +-- test/unittest/device_manager_impl_test.h | 17 +- test/unittest/mock/ipc_server_listener.h | 4 +- utils/include/ipc/lite/ipc_cmd_register.h | 7 +- utils/include/ipc/standard/ipc_cmd_register.h | 9 +- utils/src/dm_random.cpp | 8 +- 126 files changed, 1032 insertions(+), 1108 deletions(-) delete mode 100644 ext/crypto/BUILD.gn delete mode 100644 ext/ds/BUILD.gn diff --git a/common/include/ipc/model/ipc_authenticate_device_req.h b/common/include/ipc/model/ipc_authenticate_device_req.h index 3d700ba6a..cb91c7743 100644 --- a/common/include/ipc/model/ipc_authenticate_device_req.h +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -17,13 +17,12 @@ #define OHOS_DM_IPC_AUTHENTICATE_DEVICE_REQ_H #include "dm_device_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 diff --git a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h index e9d1f2639..ed4b8958a 100644 --- a/common/include/ipc/model/ipc_get_dmfaparam_rsp.h +++ b/common/include/ipc/model/ipc_get_dmfaparam_rsp.h @@ -17,13 +17,12 @@ #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); + DECLARE_IPC_MODEL(IpcGetDmFaParamRsp); public: const DmAuthParam GetDmAuthParam() const diff --git a/common/include/ipc/model/ipc_get_info_by_network_req.h b/common/include/ipc/model/ipc_get_info_by_network_req.h index eaa0969b7..786b7d58f 100644 --- a/common/include/ipc/model/ipc_get_info_by_network_req.h +++ b/common/include/ipc/model/ipc_get_info_by_network_req.h @@ -21,7 +21,8 @@ namespace OHOS { namespace DistributedHardware { class IpcGetInfoByNetWorkReq : public IpcReq { -DECLARE_IPC_MODEL(IpcGetInfoByNetWorkReq); + DECLARE_IPC_MODEL(IpcGetInfoByNetWorkReq); + public: const std::string GetNetWorkId() const { @@ -32,6 +33,7 @@ public: { netWorkId_ = netWorkId; } + private: std::string netWorkId_; }; diff --git a/common/include/ipc/model/ipc_get_info_by_network_rsp.h b/common/include/ipc/model/ipc_get_info_by_network_rsp.h index 8557e371b..18dd12b4f 100644 --- a/common/include/ipc/model/ipc_get_info_by_network_rsp.h +++ b/common/include/ipc/model/ipc_get_info_by_network_rsp.h @@ -23,7 +23,8 @@ namespace OHOS { namespace DistributedHardware { class IpcGetInfoByNetWorkRsp : public IpcRsp { -DECLARE_IPC_MODEL(IpcGetInfoByNetWorkRsp); + DECLARE_IPC_MODEL(IpcGetInfoByNetWorkRsp); + public: const std::string GetUdid() const { @@ -43,6 +44,7 @@ public: { uuid_ = uuid; } + private: std::string udid_; std::string uuid_; 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 index a70facc86..7494da0fe 100644 --- a/common/include/ipc/model/ipc_get_local_device_info_rsp.h +++ b/common/include/ipc/model/ipc_get_local_device_info_rsp.h @@ -17,13 +17,12 @@ #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); + DECLARE_IPC_MODEL(IpcGetLocalDeviceInfoRsp); public: const DmDeviceInfo &GetLocalDeviceInfo() const diff --git a/common/include/ipc/model/ipc_get_trustdevice_req.h b/common/include/ipc/model/ipc_get_trustdevice_req.h index 56f31dadb..d4a0a85a5 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_req.h +++ b/common/include/ipc/model/ipc_get_trustdevice_req.h @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { class IpcGetTrustDeviceReq : public IpcReq { -DECLARE_IPC_MODEL(IpcGetTrustDeviceReq); + DECLARE_IPC_MODEL(IpcGetTrustDeviceReq); public: const std::string &GetExtra() const diff --git a/common/include/ipc/model/ipc_get_trustdevice_rsp.h b/common/include/ipc/model/ipc_get_trustdevice_rsp.h index ea26906c5..67260f38b 100644 --- a/common/include/ipc/model/ipc_get_trustdevice_rsp.h +++ b/common/include/ipc/model/ipc_get_trustdevice_rsp.h @@ -19,13 +19,12 @@ #include #include "dm_device_info.h" - #include "ipc_rsp.h" namespace OHOS { namespace DistributedHardware { class IpcGetTrustDeviceRsp : public IpcRsp { -DECLARE_IPC_MODEL(IpcGetTrustDeviceRsp); + DECLARE_IPC_MODEL(IpcGetTrustDeviceRsp); public: std::vector GetDeviceVec() const 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 a4e0badd7..7c9034b16 100644 --- a/common/include/ipc/model/ipc_notify_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_auth_result_req.h @@ -23,7 +23,7 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyAuthResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyAuthResultReq); + DECLARE_IPC_MODEL(IpcNotifyAuthResultReq); public: std::string GetDeviceId() const 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 954b70c6a..d52c13f93 100644 --- a/common/include/ipc/model/ipc_notify_device_found_req.h +++ b/common/include/ipc/model/ipc_notify_device_found_req.h @@ -17,13 +17,12 @@ #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 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 4703b8247..19cfb68da 100644 --- a/common/include/ipc/model/ipc_notify_device_state_req.h +++ b/common/include/ipc/model/ipc_notify_device_state_req.h @@ -17,13 +17,12 @@ #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 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 c48d12d2d..8c9588399 100644 --- a/common/include/ipc/model/ipc_notify_discover_result_req.h +++ b/common/include/ipc/model/ipc_notify_discover_result_req.h @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyDiscoverResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyDiscoverResultReq); + DECLARE_IPC_MODEL(IpcNotifyDiscoverResultReq); public: uint16_t GetSubscribeId() const 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 14744e692..006c0966e 100644 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyDMFAResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyDMFAResultReq); + DECLARE_IPC_MODEL(IpcNotifyDMFAResultReq); public: std::string GetJsonParam() const 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 index 0e6a4104c..df01942ff 100644 --- a/common/include/ipc/model/ipc_notify_verify_auth_result_req.h +++ b/common/include/ipc/model/ipc_notify_verify_auth_result_req.h @@ -23,7 +23,7 @@ namespace OHOS { namespace DistributedHardware { class IpcNotifyVerifyAuthResultReq : public IpcReq { -DECLARE_IPC_MODEL(IpcNotifyVerifyAuthResultReq); + DECLARE_IPC_MODEL(IpcNotifyVerifyAuthResultReq); public: std::string GetDeviceId() const diff --git a/common/include/ipc/model/ipc_register_listener_req.h b/common/include/ipc/model/ipc_register_listener_req.h index e7dc5a83d..539b0e58b 100644 --- a/common/include/ipc/model/ipc_register_listener_req.h +++ b/common/include/ipc/model/ipc_register_listener_req.h @@ -27,7 +27,7 @@ namespace OHOS { namespace DistributedHardware { class IpcRegisterListenerReq : public IpcReq { -DECLARE_IPC_MODEL(IpcRegisterListenerReq); + DECLARE_IPC_MODEL(IpcRegisterListenerReq); public: #ifdef LITE_DEVICE diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index 1583738ca..7ecadbf3c 100644 --- a/common/include/ipc/model/ipc_req.h +++ b/common/include/ipc/model/ipc_req.h @@ -23,7 +23,7 @@ namespace OHOS { namespace DistributedHardware { class IpcReq { -DECLARE_IPC_MODEL(IpcReq); + DECLARE_IPC_MODEL(IpcReq); public: const std::string &GetPkgName() const diff --git a/common/include/ipc/model/ipc_rsp.h b/common/include/ipc/model/ipc_rsp.h index 30a2bfd94..251d6097b 100644 --- a/common/include/ipc/model/ipc_rsp.h +++ b/common/include/ipc/model/ipc_rsp.h @@ -23,7 +23,7 @@ namespace OHOS { namespace DistributedHardware { class IpcRsp { -DECLARE_IPC_MODEL(IpcRsp); + DECLARE_IPC_MODEL(IpcRsp); public: int32_t GetErrCode() const diff --git a/common/include/ipc/model/ipc_set_useroperation_req.h b/common/include/ipc/model/ipc_set_useroperation_req.h index ec46f6896..9b6e85fe7 100644 --- a/common/include/ipc/model/ipc_set_useroperation_req.h +++ b/common/include/ipc/model/ipc_set_useroperation_req.h @@ -17,13 +17,12 @@ #define OHOS_DEVICE_MANAGER_IPC_GET_USER_OPERATION_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 diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h index c110f55d7..e145ac89d 100644 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ b/common/include/ipc/model/ipc_start_discovery_req.h @@ -17,13 +17,12 @@ #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 diff --git a/common/include/ipc/model/ipc_stop_discovery_req.h b/common/include/ipc/model/ipc_stop_discovery_req.h index fba136527..10c547e88 100644 --- a/common/include/ipc/model/ipc_stop_discovery_req.h +++ b/common/include/ipc/model/ipc_stop_discovery_req.h @@ -23,7 +23,7 @@ namespace OHOS { namespace DistributedHardware { class IpcStopDiscoveryReq : public IpcReq { -DECLARE_IPC_MODEL(IpcStopDiscoveryReq); + DECLARE_IPC_MODEL(IpcStopDiscoveryReq); public: uint16_t GetSubscribeId() const diff --git a/common/include/ipc/model/ipc_unauthenticate_device_req.h b/common/include/ipc/model/ipc_unauthenticate_device_req.h index c142d4a30..78244377a 100644 --- a/common/include/ipc/model/ipc_unauthenticate_device_req.h +++ b/common/include/ipc/model/ipc_unauthenticate_device_req.h @@ -17,13 +17,12 @@ #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); + DECLARE_IPC_MODEL(IpcUnAuthenticateDeviceReq); public: const DmDeviceInfo &GetDeviceInfo() const diff --git a/common/include/ipc/model/ipc_verify_authenticate_req.h b/common/include/ipc/model/ipc_verify_authenticate_req.h index 5c973498b..3c2df5547 100644 --- a/common/include/ipc/model/ipc_verify_authenticate_req.h +++ b/common/include/ipc/model/ipc_verify_authenticate_req.h @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { class IpcVerifyAuthenticateReq : public IpcReq { -DECLARE_IPC_MODEL(IpcVerifyAuthenticateReq); + DECLARE_IPC_MODEL(IpcVerifyAuthenticateReq); public: const std::string &GetAuthPara() const diff --git a/ext/crypto/BUILD.gn b/ext/crypto/BUILD.gn deleted file mode 100644 index 0d4468cdd..000000000 --- a/ext/crypto/BUILD.gn +++ /dev/null @@ -1,69 +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") - -shared_library("devicemanagerext") { - include_dirs = [ - "${common_path}/include", - "${services_path}/include/adapter/", - "crypto/include", - "ds/include", - ] - - include_dirs += [ - "//base/security/deviceauth/interfaces/innerkits", - "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", - "//utils/native/lite/include", - "//utils/system/safwk/native/include", - "//third_party/json/include", - "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", - "//third_party/bounds_checking_function/include", - "//foundation/communication/ipc_lite/interfaces/kits", - "//foundation/communication/dsoftbus/interfaces/kits/bus_center", - "//foundation/communication/dsoftbus/interfaces/kits/common", - "//foundation/communication/dsoftbus/interfaces/kits/discovery", - "//foundation/communication/dsoftbus/interfaces/kits/transport", - "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", - "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", - ] - - sources = [ - # "src/anonymous_string.cpp", - # "src/ipc/lite/ipc_cmd_register.cpp", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerext\"", - "LOG_DOMAIN=0xD004100", - ] - - 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", - ] -} - diff --git a/ext/ds/BUILD.gn b/ext/ds/BUILD.gn deleted file mode 100644 index 37658245e..000000000 --- a/ext/ds/BUILD.gn +++ /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. - -if (defined(ohos_lite)) { - import("//build/lite/config/component/lite_component.gni") -} else { - import("//build/ohos.gni") -} - -import("//foundation/distributedhardware/devicemanager/devicemanager.gni") - -shared_library("devicemanagerext") { - include_dirs = [ - "${common_path}/include", - "${services_path}/include/adapter/", - "crypto/include", - "ds/include", - ] - - include_dirs += [ - "//base/security/deviceauth/interfaces/innerkits", - "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", - "//utils/native/lite/include", - "//utils/system/safwk/native/include", - "//third_party/json/include", - "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", - "//third_party/bounds_checking_function/include", - "//foundation/communication/ipc_lite/interfaces/kits", - "//foundation/communication/dsoftbus/interfaces/kits/bus_center", - "//foundation/communication/dsoftbus/interfaces/kits/common", - "//foundation/communication/dsoftbus/interfaces/kits/discovery", - "//foundation/communication/dsoftbus/interfaces/kits/transport", - "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", - "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", - ] - - sources = [ - # "src/anonymous_string.cpp", - # "src/ipc/lite/ipc_cmd_register.cpp", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerext\"", - "LOG_DOMAIN=0xD004100", - ] - - 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", - "//utils/native/lite:utils", - ] -} - diff --git a/ext/pin_auth/include/ability/dm_ability_manager.h b/ext/pin_auth/include/ability/dm_ability_manager.h index d4f2c4863..225fefc62 100644 --- a/ext/pin_auth/include/ability/dm_ability_manager.h +++ b/ext/pin_auth/include/ability/dm_ability_manager.h @@ -16,10 +16,11 @@ #ifndef OHOS_DM_ABILITY_MANAGER_H #define OHOS_DM_ABILITY_MANAGER_H -#include -#include #include + +#include #include +#include namespace OHOS { namespace DistributedHardware { diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h index 83980296a..2129c94a1 100644 --- a/ext/pin_auth/include/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.h @@ -32,6 +32,7 @@ public: 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_; diff --git a/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp index 31870a284..451123305 100644 --- a/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/lite/dm_ability_manager.cpp @@ -15,10 +15,6 @@ #include "dm_ability_manager.h" -#include - -#include "dm_constants.h" - namespace OHOS { namespace DistributedHardware { AbilityRole DmAbilityManager::GetAbilityRole() @@ -28,7 +24,7 @@ AbilityRole DmAbilityManager::GetAbilityRole() AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) { - // not support for L1 yet, do nothing. jsut save status and role + // not support for L1 yet, do nothing. just save status and role mAbilityStatus_ = role; mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; return mStatus_; diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp index 585c75de9..e2b026f1c 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -15,14 +15,13 @@ #include "dm_ability_manager.h" -#include "parameter.h" -#include "semaphore.h" - #include "ability_manager_client.h" -#include "ability_record.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 { @@ -30,7 +29,7 @@ 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() { diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 27497578d..781a375fb 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -17,10 +17,9 @@ #include -#include "nlohmann/json.hpp" - #include "dm_constants.h" #include "dm_log.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { @@ -52,17 +51,17 @@ int32_t PinAuth::VerifyAuthentication(std::string pinToken, int32_t code, const LOGE("DecodeRequestAuth jsonStr error"); return DM_FAILED; } - if (!jsonObject.contains(PIN_CODE_KEY) && !jsonObject.contains(PIN_TOKEN)){ + 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){ + if (code == inputPinCode && stoi(pinToken) == inputPinToken) { return DM_OK; - }else if (code != inputPinCode && times_ < 3) { + } else if (code != inputPinCode && times_ < 3) { return DM_AUTH_INPUT_FAILED; - }else { + } else { return DM_FAILED; } } diff --git a/ext/profile/include/device_profile_adapter.h b/ext/profile/include/device_profile_adapter.h index 057e835d4..d27b71fd0 100644 --- a/ext/profile/include/device_profile_adapter.h +++ b/ext/profile/include/device_profile_adapter.h @@ -24,20 +24,17 @@ namespace OHOS { namespace DistributedHardware { -class DeviceProfileAdapter : public IProfileAdapter , public IProfileConnectorCallback{ +class DeviceProfileAdapter : public IProfileAdapter, public IProfileConnectorCallback { public: DeviceProfileAdapter(); ~DeviceProfileAdapter(); - int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, + 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: - -public: private: std::shared_ptr deviceProfileAdapterCallback_; diff --git a/ext/profile/include/profile_connector.h b/ext/profile/include/profile_connector.h index 7df8313b3..96ca50055 100644 --- a/ext/profile/include/profile_connector.h +++ b/ext/profile/include/profile_connector.h @@ -16,10 +16,10 @@ #ifndef OHOS_DM_PROFILE_CONNECTOR_H #define OHOS_DM_PROFILE_CONNECTOR_H -#include -#include #include #include +#include +#include #include #include "distributed_device_profile_client.h" @@ -32,26 +32,26 @@ using namespace OHOS::DeviceProfile; class ProfileEventCallback : public IProfileEventCallback { public: - void OnSyncCompleted(const SyncResult& syncResults); - void OnProfileChanged(const ProfileChangeNotification& changeNotification); + void OnSyncCompleted(const SyncResult &syncResults); + void OnProfileChanged(const ProfileChangeNotification &changeNotification); 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 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 SubscribeProfileEvents(const std::list &serviceIds, const std::string &deviceId); int32_t UnSubscribeProfileEvents(); -private: -public: - + private: static std::shared_ptr profileEventCallback_; }; -} //namespace DistributedHardware -} //namespace OHOS +} // namespace DistributedHardware +} // namespace OHOS #endif // OHOS_DM_PROFILE_CONNECTOR_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 index 0e0c74eeb..61d82e492 100644 --- a/ext/profile/src/device_profile_adapter.cpp +++ b/ext/profile/src/device_profile_adapter.cpp @@ -14,9 +14,10 @@ */ #include "device_profile_adapter.h" -#include "dm_log.h" + #include "dm_constants.h" #include "dm_device_state_manager.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { @@ -24,15 +25,13 @@ std::shared_ptr DeviceProfileAdapter::profileConnector_ = std: DeviceProfileAdapter::DeviceProfileAdapter() { - } DeviceProfileAdapter::~DeviceProfileAdapter() { - } -int32_t DeviceProfileAdapter::RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, +int32_t DeviceProfileAdapter::RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, std::shared_ptr callback) { LOGI("DeviceProfileAdapter::RegisterProfileListener"); @@ -52,11 +51,9 @@ int32_t DeviceProfileAdapter::UnRegisterProfileListener(const std::string &pkgNa int32_t DeviceProfileAdapter::OnProfileClientDeviceReady(const std::string &pkgName, const std::string &deviceId) { LOGI("DeviceProfileAdapter::OnProfileClientDeviceReady"); - if(nullptr != deviceProfileAdapterCallback_) - { + if (nullptr != deviceProfileAdapterCallback_) { deviceProfileAdapterCallback_->OnProfileReady(pkgName, deviceId); - } - else { + } else { LOGI("deviceProfileAdapterCallback_ is nullptr"); } return DM_OK; @@ -72,8 +69,9 @@ void DeviceProfileAdapter::OnProfileComplete(const std::string &pkgName, const s OnProfileClientDeviceReady(pkgName, deviceId); } -extern "C" IProfileAdapter* CreateDeviceProfileObject (void) { +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 index 410ed423f..370cbcf85 100644 --- a/ext/profile/src/profile_connector.cpp +++ b/ext/profile/src/profile_connector.cpp @@ -14,20 +14,24 @@ */ #include "profile_connector.h" -#include "dm_log.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(); +std::shared_ptr ProfileConnector::profileEventCallback_ = + std::make_shared(); -int32_t ProfileConnector::RegisterProfileCallback(const std::string &pkgName, const std::string &deviceId, std::shared_ptr callback) +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"}, "5CA4CA0ED9A14B680BBD566307B670E7DF4F9AE932C1145732B660538485307E"); + SubscribeProfileEvents({"system", "device", "fakeStorage", "fakeSystem"}, + "5CA4CA0ED9A14B680BBD566307B670E7DF4F9AE932C1145732B660538485307E"); return DM_OK; } @@ -38,7 +42,7 @@ int32_t ProfileConnector::UnRegisterProfileCallback(const std::string &pkgName) return DM_OK; } -int32_t ProfileConnector::SubscribeProfileEvents(const std::list& serviceIds, const std::string& deviceId) +int32_t ProfileConnector::SubscribeProfileEvents(const std::list &serviceIds, const std::string &deviceId) { ExtraInfo extraInfo; extraInfo["deviceId"] = deviceId; @@ -56,8 +60,8 @@ int32_t ProfileConnector::SubscribeProfileEvents(const std::list& s std::list failedEvents; u_int32_t errCode; - errCode= DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents( - subscribeInfos, profileEventCallback_, failedEvents); + errCode = DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents(subscribeInfos, + profileEventCallback_, failedEvents); LOGI("ProfileConnector::SubscribeProfileEvents result=%d", errCode); return DM_OK; } @@ -75,7 +79,8 @@ int32_t ProfileConnector::UnSubscribeProfileEvents() return DM_OK; } -int32_t ProfileEventCallback::RegisterProfileCallback(const std::string &pkgName, std::shared_ptr callback) +int32_t ProfileEventCallback::RegisterProfileCallback(const std::string &pkgName, + std::shared_ptr callback) { LOGI("ProfileEventCallback::RegisterProfileCallback"); profileConnectorCallback_.emplace(pkgName, callback); @@ -89,28 +94,27 @@ int32_t ProfileEventCallback::UnRegisterProfileCallback(const std::string &pkgNa return DM_OK; } -void ProfileEventCallback::OnSyncCompleted(const SyncResult& syncResults) +void ProfileEventCallback::OnSyncCompleted(const SyncResult &syncResults) { std::string deviceId; u_int32_t SyncStatus; - for (auto & iterResult : syncResults) { + for (auto &iterResult : syncResults) { deviceId = iterResult.first; SyncStatus = iterResult.second; } LOGI("ProfileEventCallback::OnSyncCompleted, deviceId = %s", deviceId.c_str()); - for (auto & iter : profileConnectorCallback_) { + for (auto &iter : profileConnectorCallback_) { iter.second->OnProfileComplete(iter.first, deviceId); } } -void ProfileEventCallback::OnProfileChanged(const ProfileChangeNotification& changeNotification) +void ProfileEventCallback::OnProfileChanged(const ProfileChangeNotification &changeNotification) { std::string deviceId = changeNotification.GetDeviceId(); LOGI("ProfileEventCallback::OnProfileChanged, deviceId = %s", deviceId.c_str()); - for (auto & iter : profileConnectorCallback_) { + for (auto &iter : profileConnectorCallback_) { iter.second->OnProfileChanged(iter.first, deviceId); } } - -} -} \ No newline at end of file +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index e950722e5..9e76a1361 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -16,13 +16,13 @@ #ifndef OHOS_DEVICE_MANAGER_H #define OHOS_DEVICE_MANAGER_H -#include -#include #include +#include +#include #include "device_manager_callback.h" -#include "dm_subscribe_info.h" #include "dm_device_info.h" +#include "dm_subscribe_info.h" namespace OHOS { namespace DistributedHardware { 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 6a051f9fe..46d8c3222 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -17,9 +17,8 @@ #define OHOS_DEVICE_MANAGER_IMPL_H #include "device_manager.h" - -#include "ipc_client_proxy.h" #include "ipc_client_manager.h" +#include "ipc_client_proxy.h" namespace OHOS { namespace DistributedHardware { @@ -56,6 +55,7 @@ public: 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; 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 b95fabadb..85ee63e9c 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h @@ -17,8 +17,8 @@ #define OHOS_DM_IPC_CLIENT_H #include -#include #include +#include #include "ipc_req.h" #include "ipc_rsp.h" @@ -26,7 +26,7 @@ namespace OHOS { namespace DistributedHardware { class IpcClient { -DECLARE_IPC_INTERFACE(IpcClient); + DECLARE_IPC_INTERFACE(IpcClient); public: virtual int32_t Init(const std::string &pkgName) = 0; 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 22e3fd4dc..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 @@ -26,7 +26,7 @@ namespace OHOS { namespace DistributedHardware { class IpcClientProxy : public IpcClient { -DECLARE_IPC_INTERFACE(IpcClientProxy); + DECLARE_IPC_INTERFACE(IpcClientProxy); public: IpcClientProxy(std::shared_ptr ipcClientManager) : ipcClientManager_(ipcClientManager){}; 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 0e4746b97..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 @@ -17,8 +17,8 @@ #define OHOS_DM_IPC_CLIENT_MANAGER_H #include -#include #include +#include #include "ipc_client.h" #include "ipc_client_server_proxy.h" @@ -26,7 +26,7 @@ namespace OHOS { namespace DistributedHardware { class IpcClientManager : public IpcClient { -DECLARE_IPC_INTERFACE(IpcClientManager); + DECLARE_IPC_INTERFACE(IpcClientManager); public: virtual int32_t Init(const std::string &pkgName) override; 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 23b369397..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 @@ -20,13 +20,12 @@ #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 { 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 76fb7167a..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 @@ -16,17 +16,16 @@ #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(); 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 22c61ab44..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 @@ -17,16 +17,15 @@ #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 { 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 bb27d1479..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 @@ -19,10 +19,10 @@ #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 { 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 f654f0db1..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 @@ -19,12 +19,11 @@ #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 { 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 9d88094cf..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 @@ -19,10 +19,9 @@ #include #include -#include "iremote_broker.h" - #include "ipc_req.h" #include "ipc_rsp.h" +#include "iremote_broker.h" namespace OHOS { namespace DistributedHardware { 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 34e7a4492..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 @@ -16,21 +16,21 @@ #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(const std::string &pkgName, std::shared_ptr dmInitCallback); @@ -47,8 +47,9 @@ public: 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 RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback); void UnRegisterDeviceManagerFaCallback(const std::string &pkgName); + public: void OnRemoteDied(); void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); 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 8694f6655..0f41646a5 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,29 +15,27 @@ #include "device_manager_impl.h" -#include "bundle_info.h" #include "bundle_constants.h" +#include "bundle_info.h" #include "bundle_mgr_client.h" - -#include "dm_log.h" -#include "dm_constants.h" #include "device_manager_notify.h" - -#include "ipc_rsp.h" -#include "ipc_req.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_authenticate_device_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_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_dmfaparam_rsp.h" -#include "ipc_authenticate_device_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" -#include "ipc_set_useroperation_req.h" -#include "ipc_skeleton.h" -#include "ipc_get_info_by_network_req.h" -#include "ipc_get_info_by_network_rsp.h" using namespace OHOS::AppExecFwk; using namespace OHOS::AppExecFwk::Constants; @@ -374,7 +372,8 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons return DM_OK; } -int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback) +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) { @@ -478,7 +477,8 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t return DM_OK; } -int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid) +int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) { if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); @@ -502,7 +502,8 @@ int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const return DM_OK; } -int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) +int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) { if (pkgName.empty()) { LOGE("VerifyAuthentication failed, pkgName is empty"); 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 af32e1f65..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 @@ -15,8 +15,8 @@ #include "ipc_client_proxy.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { 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 0fa638f85..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 @@ -17,7 +17,6 @@ #include "dm_constants.h" #include "dm_log.h" - #include "ipc_client_stub.h" #include "ipc_register_listener_req.h" 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 e492e5069..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 @@ -15,12 +15,11 @@ #include "ipc_client_server_proxy.h" -#include "dm_log.h" -#include "dm_constants.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 { 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 65865047c..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 @@ -15,12 +15,11 @@ #include "ipc_client_stub.h" +#include "device_manager_notify.h" #include "dm_constants.h" #include "dm_log.h" -#include "device_manager_notify.h" - -#include "ipc_def.h" #include "ipc_cmd_register.h" +#include "ipc_def.h" namespace OHOS { namespace DistributedHardware { 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 3e58881a1..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 @@ -13,25 +13,22 @@ * limitations under the License. */ -#include "ipc_cmd_register.h" -#include "ipc_def.h" - -#include "securec.h" -#include "dm_constants.h" -#include "dm_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_register_listener_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.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_authenticate_device_req.h" +#include "ipc_register_listener_req.h" +#include "ipc_start_discovery_req.h" +#include "ipc_stop_discovery_req.h" #include "ipc_verify_authenticate_req.h" +#include "securec.h" namespace OHOS { namespace DistributedHardware { 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 648f68388..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 @@ -18,11 +18,11 @@ #include "device_manager_notify.h" #include "dm_constants.h" #include "dm_log.h" -#include "iremote_object.h" -#include "iservice_registry.h" -#include "ipc_remote_broker.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" namespace OHOS { 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 dc0862783..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 @@ -15,12 +15,11 @@ #include "ipc_client_server_proxy.h" +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_cmd_register.h" #include "ipc_types.h" -#include "dm_log.h" -#include "dm_constants.h" - namespace OHOS { namespace DistributedHardware { int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr 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 2d0558e28..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 @@ -15,14 +15,12 @@ #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 "dm_log.h" -#include "dm_constants.h" - namespace OHOS { namespace DistributedHardware { int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) 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 611b24ffe..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 @@ -13,30 +13,28 @@ * limitations under the License. */ -#include "ipc_cmd_register.h" - -#include "securec.h" - +#include "device_manager_notify.h" #include "dm_constants.h" -#include "dm_log.h" #include "dm_device_info.h" -#include "device_manager_notify.h" +#include "dm_log.h" +#include "ipc_authenticate_device_req.h" +#include "ipc_cmd_register.h" #include "ipc_def.h" -#include "ipc_rsp.h" -#include "ipc_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_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_get_trustdevice_req.h" -#include "ipc_get_trustdevice_rsp.h" -#include "ipc_authenticate_device_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" -#include "ipc_get_local_device_info_rsp.h" -#include "ipc_get_dmfaparam_rsp.h" -#include "ipc_set_useroperation_req.h" -#include "ipc_get_info_by_network_req.h" -#include "ipc_get_info_by_network_rsp.h" +#include "securec.h" namespace OHOS { namespace DistributedHardware { 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 fb70b2e01..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 @@ -15,10 +15,10 @@ #include "device_manager_notify.h" -#include "dm_log.h" +#include "device_manager.h" #include "dm_constants.h" +#include "dm_log.h" #include "nlohmann/json.hpp" -#include "device_manager.h" namespace OHOS { namespace DistributedHardware { @@ -114,7 +114,8 @@ void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::stri verifyAuthCallback_.erase(pkgName); } -void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName,std::shared_ptr callback) +void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) { std::lock_guard autoLock(lock_); dmFaCallback_[pkgName] = callback; diff --git a/interfaces/kits/js/include/dm_native_event.h b/interfaces/kits/js/include/dm_native_event.h index 6d21ffb68..3d619bf99 100644 --- a/interfaces/kits/js/include/dm_native_event.h +++ b/interfaces/kits/js/include/dm_native_event.h @@ -19,6 +19,7 @@ #include #include #include + #include "napi/native_api.h" struct DmEventListener { diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index cef7739a9..ddf8e7473 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -20,11 +20,10 @@ #include #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 "dm_device_info.h" -#include "dm_app_image_info.h" #include "napi/native_api.h" #include "napi/native_node_api.h" #include "nlohmann/json.hpp" diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 1f3e83e1f..bdd76d794 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -18,9 +18,9 @@ #include #include "device_manager.h" -#include "dm_log.h" #include "dm_constants.h" #include "dm_device_info.h" +#include "dm_log.h" #include "nlohmann/json.hpp" using namespace OHOS::DistributedHardware; diff --git a/services/devicemanagerservice/include/ability/dm_ability_manager.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h index 0b7e6604d..64c27a5e5 100644 --- a/services/devicemanagerservice/include/ability/dm_ability_manager.h +++ b/services/devicemanagerservice/include/ability/dm_ability_manager.h @@ -16,10 +16,11 @@ #ifndef OHOS_DM_ABILITY_MANAGER_H #define OHOS_DM_ABILITY_MANAGER_H -#include -#include #include + +#include #include +#include #include "single_instance.h" diff --git a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h index c134d19ab..b290e8367 100644 --- a/services/devicemanagerservice/include/adapter/dm_adapter_manager.h +++ b/services/devicemanagerservice/include/adapter/dm_adapter_manager.h @@ -27,7 +27,7 @@ namespace OHOS { namespace DistributedHardware { class IProfileAdapter; class DmAdapterManager { -DECLARE_SINGLE_INSTANCE(DmAdapterManager); + DECLARE_SINGLE_INSTANCE(DmAdapterManager); public: std::shared_ptr GetDecisionAdapter(const std::string &soName); diff --git a/services/devicemanagerservice/include/adapter/profile_adapter.h b/services/devicemanagerservice/include/adapter/profile_adapter.h index 6e4693157..39f5a3de7 100644 --- a/services/devicemanagerservice/include/adapter/profile_adapter.h +++ b/services/devicemanagerservice/include/adapter/profile_adapter.h @@ -25,7 +25,7 @@ class DmDeviceStateManager; class IProfileAdapter { public: virtual ~IProfileAdapter() = default; - virtual int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId, + 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; }; diff --git a/services/devicemanagerservice/include/authentication/auth_message_processor.h b/services/devicemanagerservice/include/authentication/auth_message_processor.h index 3e985d499..73226f7a8 100644 --- a/services/devicemanagerservice/include/authentication/auth_message_processor.h +++ b/services/devicemanagerservice/include/authentication/auth_message_processor.h @@ -18,9 +18,10 @@ #include #include -#include "nlohmann/json.hpp" + #include "crypto_adapter.h" #include "dm_auth_manager.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/authentication/auth_request_state.h b/services/devicemanagerservice/include/authentication/auth_request_state.h index d0cdc0635..a1a3343e8 100644 --- a/services/devicemanagerservice/include/authentication/auth_request_state.h +++ b/services/devicemanagerservice/include/authentication/auth_request_state.h @@ -15,9 +15,10 @@ #ifndef OHOS_DM_AUTH_REQUEST_STATE_H #define OHOS_DM_AUTH_REQUEST_STATE_H -#include #include #include +#include + #include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 3a75aeb89..2f10abff9 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -19,17 +19,17 @@ #include #include -#include "authentication.h" -#include "auth_ui.h" #include "auth_message_processor.h" #include "auth_request_state.h" #include "auth_response_state.h" -#include "dm_ability_manager.h" -#include "dm_device_info.h" -#include "dm_timer.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" @@ -173,7 +173,7 @@ private: std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; std::map> timerMap_; - std::shared_ptr dmAbilityMgr_ ; + std::shared_ptr dmAbilityMgr_; bool isCryptoSupport_ = false; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/config/config_manager.h b/services/devicemanagerservice/include/config/config_manager.h index 6395ad71d..4a410a1e7 100644 --- a/services/devicemanagerservice/include/config/config_manager.h +++ b/services/devicemanagerservice/include/config/config_manager.h @@ -18,16 +18,16 @@ #include #include -#include #include +#include #include #include #include +#include "authentication.h" +#include "crypto_adapter.h" #include "decision_adapter.h" #include "profile_adapter.h" -#include "crypto_adapter.h" -#include "authentication.h" #include "single_instance.h" namespace OHOS { diff --git a/services/devicemanagerservice/include/config/json_config.h b/services/devicemanagerservice/include/config/json_config.h index 42d7153eb..a1c495cc0 100644 --- a/services/devicemanagerservice/include/config/json_config.h +++ b/services/devicemanagerservice/include/config/json_config.h @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { const std::string adapterJsonConfigString = -R"({ + R"({ "devicemanager_adapter_components": [ { "name": "crypto_adapter", @@ -43,7 +43,7 @@ R"({ })"; const std::string authJsonConfigString = -R"({ + R"({ "devicemanager_auth_components": [ { "name": "pin_auth", diff --git a/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h b/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h index 047eadd72..be733f983 100644 --- a/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h +++ b/services/devicemanagerservice/include/dependency/commonevent/event_manager_adapt.h @@ -19,13 +19,13 @@ #include #include -#include "dm_log.h" #include "common_event.h" -#include "matching_skills.h" #include "common_event_data.h" #include "common_event_manager.h" -#include "common_event_subscriber.h" #include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "dm_log.h" +#include "matching_skills.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 94115d60d..895441bf4 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -16,16 +16,16 @@ #ifndef OHOS_HICHAIN_CONNECTOR_H #define OHOS_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 "nlohmann/json.hpp" +#include "single_instance.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index 6916d0280..6e9dd9374 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -16,18 +16,19 @@ #ifndef OHOS_DM_SOFTBUS_CONNECTOR_H #define OHOS_DM_SOFTBUS_CONNECTOR_H -#include -#include #include #include +#include +#include #include -#include "softbus_bus_center.h" + #include "discovery_service.h" #include "dm_device_info.h" #include "dm_subscribe_info.h" -#include "softbus_state_callback.h" +#include "softbus_bus_center.h" #include "softbus_discovery_callback.h" #include "softbus_session.h" +#include "softbus_state_callback.h" namespace OHOS { namespace DistributedHardware { @@ -49,6 +50,7 @@ public: 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(); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 4862c7d0c..084df4817 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -16,13 +16,14 @@ #ifndef OHOS_DM_SOFTBUS_SESSION_H #define OHOS_DM_SOFTBUS_SESSION_H +#include +#include #include -#include #include -#include -#include -#include "session.h" +#include + #include "inner_session.h" +#include "session.h" #include "softbus_session_callback.h" namespace OHOS { diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h index 788b0b5e9..66a0adbf3 100644 --- a/services/devicemanagerservice/include/dependency/timer/dm_timer.h +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -15,14 +15,15 @@ #ifndef TIMER_H #define TIMER_H -#include #include -#include #include #include -#include +#include #include + #include +#include +#include #include "dm_log.h" diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index 6b66232e4..53e33b1d6 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -19,14 +19,14 @@ #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 "dm_device_info.h" -#include "dm_ability_manager.h" -#include "softbus_connector.h" #include "single_instance.h" +#include "softbus_connector.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index ade397cdc..b59965b7d 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -16,12 +16,12 @@ #ifndef OHOS_DM_SERVICE_LISTENER_H #define OHOS_DM_SERVICE_LISTENER_H -#include #include +#include #include "dm_device_info.h" -#include "ipc_server_listener.h" #include "ipc_notify_dmfa_result_req.h" +#include "ipc_server_listener.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h index 8d67069bb..9dfe5b159 100644 --- a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h @@ -19,9 +19,9 @@ #include #include +#include "dm_adapter_manager.h" #include "dm_device_info.h" #include "softbus_connector.h" -#include "dm_adapter_manager.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 4e828f2a5..637e44788 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -16,9 +16,9 @@ #ifndef OHOS_DM_DEVICE_STATE_MANAGER_H #define OHOS_DM_DEVICE_STATE_MANAGER_H -#include "softbus_connector.h" -#include "dm_adapter_manager.h" #include "device_manager_service_listener.h" +#include "dm_adapter_manager.h" +#include "softbus_connector.h" namespace OHOS { namespace DistributedHardware { @@ -34,6 +34,7 @@ public: 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_; diff --git a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h index b775453ba..20c30ec8b 100644 --- a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h @@ -17,9 +17,10 @@ #define OHOS_DM_DISCOVERY_MANAGER_H #include -#include "softbus_connector.h" + #include "device_manager_service_listener.h" #include "dm_timer.h" +#include "softbus_connector.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h index a11a79137..4cf1b62ce 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h @@ -20,7 +20,6 @@ #include "ipc_req.h" #include "ipc_rsp.h" - #include "ipc_server_listenermgr.h" namespace OHOS { @@ -29,9 +28,11 @@ 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); diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h index 19b8e4838..2d0ed61c4 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h @@ -17,9 +17,9 @@ #define OHOS_DM_IPC_SERVER_LISTENER_MGR_H #include -#include #include #include +#include #include "liteipc_adapter.h" #include "single_instance.h" @@ -35,7 +35,7 @@ typedef struct CommonSvcId { } CommonSvcId; class IpcServerListenermgr { -DECLARE_SINGLE_INSTANCE(IpcServerListenermgr); + DECLARE_SINGLE_INSTANCE(IpcServerListenermgr); public: int32_t RegisterListener(std::string &pkgName, const CommonSvcId *svcId); diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h index f27806218..93d0f7878 100644 --- a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h @@ -16,21 +16,19 @@ #ifndef OHOS_DM_IPC_SERVER_STUB_H #define OHOS_DM_IPC_SERVER_STUB_H +#include #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" -#include "iremote_stub.h" -#include "ipc_remote_broker.h" - -#include "single_instance.h" -#include "hichain_connector.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp index 1d1cc65d4..ce077df93 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -16,8 +16,8 @@ #include "dm_ability_manager.h" #include "ability_manager_client.h" -#include "ability_record.h" #include "ability_manager_service.h" +#include "ability_record.h" #include "dm_constants.h" #include "dm_log.h" #include "parameter.h" diff --git a/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp index 4d67265d1..219002770 100644 --- a/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/lite/dm_adapter_manager.cpp @@ -14,8 +14,9 @@ */ #include "dm_adapter_manager.h" -#include "dm_log.h" + #include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp index 977d9999f..693656d50 100644 --- a/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp +++ b/services/devicemanagerservice/src/adapter/standard/dm_adapter_manager.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ +#include "dm_adapter_manager.h" + #include #include "config_manager.h" -#include "dm_adapter_manager.h" #include "dm_constants.h" #include "dm_log.h" diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index 3574da71f..dc47ad2bd 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -15,9 +15,9 @@ #include "auth_message_processor.h" -#include "dm_log.h" -#include "dm_constants.h" #include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/authentication/auth_response_state.cpp b/services/devicemanagerservice/src/authentication/auth_response_state.cpp index 219441448..10c4c17f1 100644 --- a/services/devicemanagerservice/src/authentication/auth_response_state.cpp +++ b/services/devicemanagerservice/src/authentication/auth_response_state.cpp @@ -15,9 +15,9 @@ #include "auth_response_state.h" -#include "dm_log.h" -#include "dm_constants.h" #include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/authentication/auth_ui.cpp b/services/devicemanagerservice/src/authentication/auth_ui.cpp index c3b12a1c8..b3afce453 100644 --- a/services/devicemanagerservice/src/authentication/auth_ui.cpp +++ b/services/devicemanagerservice/src/authentication/auth_ui.cpp @@ -45,5 +45,5 @@ int32_t AuthUi::StartFaService() } 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 index 4417738b8..d425159dd 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -15,8 +15,6 @@ #include "dm_auth_manager.h" -#include "nlohmann/json.hpp" - #include "auth_message_processor.h" #include "auth_ui.h" #include "config_manager.h" @@ -24,6 +22,7 @@ #include "dm_constants.h" #include "dm_log.h" #include "dm_random.h" +#include "nlohmann/json.hpp" #include "parameter.h" namespace OHOS { @@ -66,9 +65,9 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmAuthManager constructor"); - //TODO: load library so for different auth type + // TODO: load library so for different auth type hiChainConnector_ = std::make_shared(); - + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); dmConfigManager.GetAuthAdapter(authenticationMap_); } @@ -98,11 +97,11 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au LOGE("DmAuthManager::AuthenticateDevice is response authentication."); return DM_AUTH_BUSINESS_BUSY; } - if (extra.empty()){ + if (extra.empty()) { LOGE("AuthenticateDevice failed, extra is empty"); return DM_INPUT_PARA_EMPTY; } - if (authType !=AUTH_TYPE_PIN && authType != AUTH_TYPE_SCAN && authType != AUTH_TYPE_TOUCH) { + if (authType != AUTH_TYPE_PIN && authType != AUTH_TYPE_SCAN && authType != AUTH_TYPE_TOUCH) { LOGE("AuthenticateDevice failed, authType is not support"); return DM_INPUT_PARA_EMPTY; } @@ -194,8 +193,8 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); break; case DM_AUTH_INPUT_FAILED: - //todo Prompt for input pin code error - //break; + // todo Prompt for input pin code error + // break; default: CancelDisplay(); } @@ -222,7 +221,7 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI timerMap_[AUTHENTICATE_TIMEOUT_TASK] = authenticateStartTimer; authenticateStartTimer->Start(AUTHENTICATE_TIMEOUT, TimeOut, this); } else { - std::shared_ptr authMessageProcessor = + std::shared_ptr authMessageProcessor = std::make_shared(shared_from_this()); std::shared_ptr authResponseContext = std::make_shared(); authResponseContext->reply = AuthState::AUTH_RESPONSE_INIT; @@ -231,7 +230,7 @@ void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionI softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } } else { - if(authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this()); authRequestContext_->sessionId = sessionId; authRequestState_->SetAuthContext(authRequestContext_); @@ -298,11 +297,11 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId } break; case MSG_TYPE_REQ_AUTH_TERMINATE: - if (authResponseState_ != nullptr && + 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) { + } else if (authRequestState_ != nullptr && + authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { LOGE("Device manager auth state error"); } break; @@ -338,11 +337,11 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) { LOGI("DmAuthManager OnMemberJoin start"); CancelDisplay(); - //timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + // timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); LOGE("DmAuthManager OnMemberJoin start"); if (authRequestState_ != nullptr) { - //timerMap_[ADD_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + // 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())); @@ -393,7 +392,7 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) softbusConnector_->GetLocalDeviceInfo(localDevice); authRequestContext_->localDeviceId = localDevice.deviceId; bool ret = hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); - if (ret != true){ + if (ret != true) { LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE; authRequestContext_->reason = DM_AUTH_DEVICE_AUTHED; @@ -411,7 +410,7 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); - if (ret != true){ + if (ret != true) { LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = DM_AUTH_PEER_REJECT; return; @@ -537,8 +536,8 @@ void DmAuthManager::JoinNetwork() void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); - if (authRequestState_ == nullptr){ - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW){ + if (authRequestState_ == nullptr) { + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { CancelDisplay(); } if (!timerMap_.empty()) { @@ -557,7 +556,7 @@ void DmAuthManager::AuthenticateFinish() std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } - if (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN){ + if (authResponseContext_->reply == AuthState::AUTH_REQUEST_JOIN) { listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, DM_AUTH_INPUT_FAILED, flag); } @@ -607,7 +606,7 @@ std::string DmAuthManager::GenerateGroupName() GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; std::string groupName = authResponseContext_->targetPkgName + authResponseContext_->hostPkgName + - sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); + sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); return groupName; } @@ -665,8 +664,7 @@ void DmAuthManager::ShowStartAuthDialog() { dmAbilityMgr_ = std::make_shared(); std::shared_ptr ptr; - if (authenticationMap_.find(1) != authenticationMap_.end()) - { + if (authenticationMap_.find(1) != authenticationMap_.end()) { ptr = authenticationMap_[1]; } ptr->StartAuth(dmAbilityMgr_); diff --git a/services/devicemanagerservice/src/config/config_manager.cpp b/services/devicemanagerservice/src/config/config_manager.cpp index cd4d1e76b..76b77a308 100644 --- a/services/devicemanagerservice/src/config/config_manager.cpp +++ b/services/devicemanagerservice/src/config/config_manager.cpp @@ -16,9 +16,9 @@ #include +#include "dm_constants.h" #include "dm_log.h" #include "json_config.h" -#include "dm_constants.h" #include "nlohmann/json.hpp" namespace OHOS { diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 69ebb6822..551872517 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -15,19 +15,19 @@ #include "hichain_connector.h" +#include + #include #include #include -#include - -#include "nlohmann/json.hpp" -#include "parameter.h" -#include "hichain_connector_callback.h" #include "dm_anonymous.h" -#include "dm_log.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 { @@ -196,9 +196,9 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectIn 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()); + // 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; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 0be1b9fcc..1f78a2c18 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -15,19 +15,19 @@ #include "softbus_connector.h" -#include -#include -#include #include +#include -#include "parameter.h" -#include "system_ability_definition.h" +#include +#include -#include "dm_log.h" #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 { @@ -234,7 +234,8 @@ int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string { 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)); + 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; @@ -248,7 +249,8 @@ int32_t SoftbusConnector::GetUuidByNetworkId(const char *networkId, std::string { 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)); + 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; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 89d1ba47e..7e31b7a3e 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -14,11 +14,12 @@ */ #include "softbus_session.h" -#include "softbus_connector.h" + +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" -#include "dm_anonymous.h" #include "nlohmann/json.hpp" +#include "softbus_connector.h" namespace OHOS { namespace DistributedHardware { @@ -151,7 +152,7 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 if (isCryptoSupport) { LOGI("SoftbusSession::OnBytesReceived Start decryption"); } - std::string message = std::string((const char*)data, dataLen); + std::string message = std::string((const char *)data, dataLen); for (auto &iter : sessionCallbackMap_) { iter.second->OnDataReceived(iter.first, sessionId, message); } diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 2de301453..87bee5800 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -103,7 +103,8 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) return deviceInfoMgr_->GetLocalDeviceInfo(info); } -int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid) +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"); @@ -118,7 +119,8 @@ int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, con return DM_OK; } -int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) +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"); diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index eae398c93..5e6223671 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -17,15 +17,14 @@ #include +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" -#include "dm_anonymous.h" - #include "ipc_notify_auth_result_req.h" -#include "ipc_notify_verify_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 { @@ -41,7 +40,7 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam pReq->SetDeviceState(state); pReq->SetDeviceInfo(info); - if(state == DEVICE_INFO_CHANGED) { + if (state == DEVICE_INFO_CHANGED) { auto iter = remoteDeviceInfos_.find(info.deviceId); if (iter == remoteDeviceInfos_.end()) { LOGE("DeviceManagerServiceListener::OnDeviceStateChange complete not find deviceID"); @@ -49,10 +48,10 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam saveInfo = iter->second; pReq->SetDeviceInfo(saveInfo); } - } else if(state == DEVICE_STATE_ONLINE) { + } else if (state == DEVICE_STATE_ONLINE) { DmDeviceInfo saveInfo = info; remoteDeviceInfos_[info.deviceId] = saveInfo; - } else if(state == DEVICE_STATE_OFFLINE) { + } else if (state == DEVICE_STATE_OFFLINE) { auto iter = remoteDeviceInfos_.find(info.deviceId); if (iter == remoteDeviceInfos_.end()) { } else { diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index b56c7ff7a..dcf240abf 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -15,8 +15,8 @@ #include "dm_device_info_manager.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 4e1429a0d..37a03d933 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -14,9 +14,10 @@ */ #include "dm_device_state_manager.h" -#include "dm_log.h" -#include "dm_constants.h" + #include "dm_adapter_manager.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { @@ -44,7 +45,7 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe } else { uint8_t udid[UDID_BUF_LEN] = {0}; int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(info.deviceId, NodeDeivceInfoKey::NODE_KEY_UDID, udid, - sizeof(udid)); + sizeof(udid)); if (ret != DM_OK) { LOGE("DmDeviceStateManager::OnDeviceOnline GetNodeKeyInfo failed"); } else { @@ -60,7 +61,7 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe LOGI("DmDeviceStateManager::OnDeviceOnline out"); } -void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) +void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) { std::string soName; DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); @@ -95,7 +96,8 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: int32_t DmDeviceStateManager::RegisterSoftbusStateCallback() { - softbusConnector_->RegisterSoftbusStateCallback(DM_PKG_NAME, std::shared_ptr(shared_from_this())); + softbusConnector_->RegisterSoftbusStateCallback(DM_PKG_NAME, + std::shared_ptr(shared_from_this())); return DM_OK; } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index 970690125..cb4c8f8d5 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -14,18 +14,20 @@ */ #include "dm_discovery_manager.h" -#include "dm_log.h" -#include "dm_constants.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; -} -static void TimeOut(void *data){ +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) { @@ -63,7 +65,8 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con discoveryQueue_.push(pkgName); DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId}; discoveryContextMap_.emplace(pkgName, context); - softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(shared_from_this())); + 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); diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index c70fbda0b..6e14961b3 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -13,17 +13,16 @@ * limitations under the License. */ -#include "ipc_cmd_register.h" - +#include "device_manager_service.h" #include "dm_constants.h" #include "dm_log.h" -#include "device_manager_service.h" +#include "ipc_cmd_register.h" #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" -#include "ipc_notify_verify_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 { diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp index 0dbc01b96..6436427d6 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -15,9 +15,8 @@ #include "ipc_server_listener.h" -#include "dm_log.h" #include "dm_constants.h" - +#include "dm_log.h" #include "ipc_cmd_register.h" #include "ipc_def.h" #include "ipc_server_listenermgr.h" diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp index db8dff1e4..03dd6c3ac 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp @@ -13,14 +13,14 @@ * limitations under the License. */ -#include #include -#include "dm_log.h" -#include "dm_constants.h" +#include -#include "ipc_server_stub.h" #include "device_manager_service.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "ipc_server_stub.h" using namespace OHOS::DistributedHardware; diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp index 87e61ac79..b6af2d8c8 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -15,20 +15,17 @@ #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 "dm_log.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; diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index e7271010a..2a61266b5 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -13,21 +13,20 @@ * limitations under the License. */ -#include "ipc_cmd_register.h" - #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 "dm_device_info.h" -#include "device_manager_service.h" +#include "ipc_cmd_register.h" #include "ipc_def.h" #include "ipc_notify_auth_result_req.h" -#include "ipc_notify_verify_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 { @@ -352,28 +351,30 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply) return DM_OK; } -ON_IPC_CMD(GET_UDID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) { - std::string pkgName = data.ReadString(); +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); + 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; + 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) { +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); + int32_t result = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); if (!reply.WriteInt32(result)) { LOGE("write result failed"); @@ -386,7 +387,8 @@ ON_IPC_CMD(GET_UUID_BY_NETWORK, MessageParcel &data, MessageParcel &reply) { return DM_OK; } -ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) { +ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) +{ std::string packName = data.ReadString(); DmAuthParam authParam; int32_t ret = DM_OK; diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp index a7989564e..28dbc5a5f 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp @@ -15,12 +15,11 @@ #include "ipc_server_client_proxy.h" -#include "ipc_types.h" - +#include "dm_constants.h" +#include "dm_log.h" #include "ipc_cmd_register.h" #include "ipc_def.h" -#include "dm_log.h" -#include "dm_constants.h" +#include "ipc_types.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp index 9176b9291..a77e3dbbb 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp @@ -14,10 +14,10 @@ */ #include "ipc_server_listener.h" -#include "ipc_server_stub.h" #include "dm_constants.h" #include "dm_log.h" +#include "ipc_server_stub.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp index 6d1abdabb..3d3268212 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -18,20 +18,18 @@ #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" -#include "dm_constants.h" -#include "dm_log.h" -#include "device_manager_service.h" - -#include "ipc_cmd_register.h" -#include "device_manager_impl.h" - namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(IpcServerStub); diff --git a/test/unittest/UTTest_auth_request_state.cpp b/test/unittest/UTTest_auth_request_state.cpp index 63c61a475..67dd87599 100644 --- a/test/unittest/UTTest_auth_request_state.cpp +++ b/test/unittest/UTTest_auth_request_state.cpp @@ -13,11 +13,12 @@ * limitations under the License. */ +#include "UTTest_auth_request_state.h" + #include -#include "dm_constants.h" #include "dm_auth_manager.h" -#include "UTTest_auth_request_state.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { @@ -34,13 +35,13 @@ void AuthRequestStateTest::TearDownTestCase() { } -namespace{ +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"; +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 @@ -59,7 +60,7 @@ HWTEST_F(AuthRequestStateTest, SetAuthManager_001, testing::ext::TestSize.Level0 authRequestState->SetAuthManager(authManager); int32_t ret = authRequestState->authManager_.use_count(); authRequestState->authManager_.reset(); - ASSERT_EQ(ret,1); + ASSERT_EQ(ret, 1); } /** @@ -76,7 +77,7 @@ HWTEST_F(AuthRequestStateTest, SetAuthManager_002, testing::ext::TestSize.Level0 authRequestState->SetAuthManager(nullptr); int32_t ret = authRequestState->authManager_.use_count(); authRequestState->authManager_.reset(); - ASSERT_EQ(ret,0); + ASSERT_EQ(ret, 0); } /** @@ -137,7 +138,7 @@ 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); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_INIT); sleep(15); } @@ -157,8 +158,8 @@ HWTEST_F(AuthRequestStateTest, Enter_001, testing::ext::TestSize.Level0) std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestInitState()); authManager = nullptr; authRequestState->SetAuthManager(authManager); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -183,8 +184,8 @@ HWTEST_F(AuthRequestStateTest, Enter_002, testing::ext::TestSize.Level0) std::shared_ptr context = std::make_shared(); context->deviceId = "123456"; authRequestState->SetAuthContext(context); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_OK); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -195,11 +196,12 @@ HWTEST_F(AuthRequestStateTest, Enter_002, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(AuthRequestStateTest,GetStateType_002, testing::ext::TestSize.Level0) +HWTEST_F(AuthRequestStateTest, GetStateType_002, testing::ext::TestSize.Level0) { - std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNegotiateState()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateState()); int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_REQUEST_NEGOTIATE); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_NEGOTIATE); sleep(15); } @@ -216,10 +218,11 @@ 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()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateState()); authRequestState->SetAuthManager(nullptr); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -236,20 +239,21 @@ 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 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"; + 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); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -262,9 +266,10 @@ HWTEST_F(AuthRequestStateTest, Enter_004, testing::ext::TestSize.Level0) */ HWTEST_F(AuthRequestStateTest, GetStateType_003, testing::ext::TestSize.Level0) { - std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNegotiateDoneState()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateDoneState()); int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_REQUEST_NEGOTIATE_DONE); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_NEGOTIATE_DONE); sleep(15); } @@ -281,10 +286,11 @@ 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()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNegotiateDoneState()); authRequestState->SetAuthManager(nullptr); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -301,7 +307,8 @@ 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 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; @@ -313,8 +320,8 @@ HWTEST_F(AuthRequestStateTest, Enter_006, testing::ext::TestSize.Level0) std::shared_ptr context = std::make_shared(); context->sessionId = 333333; authRequestState->SetAuthContext(context); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_OK); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -329,7 +336,7 @@ 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); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_REPLY); sleep(15); } @@ -348,8 +355,8 @@ HWTEST_F(AuthRequestStateTest, Enter_007, testing::ext::TestSize.Level0) 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); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -382,8 +389,8 @@ HWTEST_F(AuthRequestStateTest, Enter_008, testing::ext::TestSize.Level0) std::shared_ptr context = std::make_shared(); context->sessionId = 333333; authRequestState->SetAuthContext(context); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_OK); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -398,7 +405,7 @@ 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); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_INPUT); sleep(15); } @@ -417,8 +424,8 @@ HWTEST_F(AuthRequestStateTest, Enter_009, testing::ext::TestSize.Level0) 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); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -437,8 +444,8 @@ HWTEST_F(AuthRequestStateTest, Enter_010, testing::ext::TestSize.Level0) 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); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -453,7 +460,7 @@ 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); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_JOIN); sleep(15); } @@ -472,8 +479,8 @@ HWTEST_F(AuthRequestStateTest, Enter_011, testing::ext::TestSize.Level0) 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); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -498,11 +505,11 @@ HWTEST_F(AuthRequestStateTest, Enter_012, testing::ext::TestSize.Level0) 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"; + 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; @@ -513,8 +520,8 @@ HWTEST_F(AuthRequestStateTest, Enter_012, testing::ext::TestSize.Level0) context->deviceId = "44444"; context->sessionId = 55555; authRequestState->SetAuthContext(context); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_OK); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -527,9 +534,10 @@ HWTEST_F(AuthRequestStateTest, Enter_012, testing::ext::TestSize.Level0) */ HWTEST_F(AuthRequestStateTest, GetStateType_007, testing::ext::TestSize.Level0) { - std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestNetworkState()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNetworkState()); int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_REQUEST_NETWORK); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_NETWORK); sleep(15); } @@ -546,10 +554,11 @@ 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()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestNetworkState()); authRequestState->SetAuthManager(nullptr); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -566,7 +575,8 @@ 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 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); @@ -576,7 +586,7 @@ HWTEST_F(AuthRequestStateTest, Enter_014, testing::ext::TestSize.Level0) authManager->SetAuthRequestState(authRequestState); authRequestState->SetAuthManager(authManager); int32_t ret = authRequestState->Enter(); - ASSERT_EQ(ret,DM_OK); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -589,9 +599,10 @@ HWTEST_F(AuthRequestStateTest, Enter_014, testing::ext::TestSize.Level0) */ HWTEST_F(AuthRequestStateTest, GetStateType_008, testing::ext::TestSize.Level0) { - std::shared_ptr authRequestState = std::shared_ptr(new AuthRequestFinishState()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestFinishState()); int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_REQUEST_FINISH); + ASSERT_EQ(ret, AuthState::AUTH_REQUEST_FINISH); sleep(15); } @@ -608,10 +619,11 @@ 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()); + std::shared_ptr authRequestState = + std::shared_ptr(new AuthRequestFinishState()); authRequestState->SetAuthManager(nullptr); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authRequestState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -628,7 +640,8 @@ 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 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; @@ -645,10 +658,10 @@ HWTEST_F(AuthRequestStateTest, Enter_016, testing::ext::TestSize.Level0) std::shared_ptr context = std::make_shared(); context->sessionId = 333333; authRequestState->SetAuthContext(context); - int32_t ret =authRequestState->Enter(); - ASSERT_EQ(ret,DM_OK); + 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 index aa5626a4a..118963122 100644 --- a/test/unittest/UTTest_auth_request_state.h +++ b/test/unittest/UTTest_auth_request_state.h @@ -17,21 +17,23 @@ #define OHOS_DM_AUTH_REQUEST_STATE_TEST_H #include -#include + #include #include -#include "dm_log.h" +#include + #include "auth_request_state.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { -class AuthRequestStateTest : public testing::Test { +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 index 4a6bad2e4..48e886fe9 100644 --- a/test/unittest/UTTest_auth_response_state.cpp +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -13,12 +13,12 @@ * limitations under the License. */ -#include "auth_response_state.h" +#include "UTTest_auth_response_state.h" -#include "dm_log.h" -#include "dm_constants.h" +#include "auth_response_state.h" #include "dm_auth_manager.h" -#include "UTTest_auth_response_state.h" +#include "dm_constants.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { @@ -35,7 +35,7 @@ void AuthResponseStateTest::TearDownTestCase() { } -namespace{ +namespace { /** * @tc.name: AuthResponseInitState::SetAuthManager_001 @@ -50,10 +50,11 @@ HWTEST_F(AuthResponseStateTest, SetAuthManager_001, testing::ext::TestSize.Level 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 authResponseState = + std::shared_ptr(new AuthResponseInitState()); authResponseState->SetAuthManager(authManager); int32_t ret = authResponseState->authManager_.use_count(); - ASSERT_EQ(ret,1); + ASSERT_EQ(ret, 1); sleep(15); } @@ -67,7 +68,8 @@ HWTEST_F(AuthResponseStateTest, SetAuthManager_001, testing::ext::TestSize.Level */ HWTEST_F(AuthResponseStateTest, SetAuthManager_002, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseInitState()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); authResponseState->SetAuthManager(nullptr); int32_t ret = authResponseState->authManager_.use_count(); ASSERT_EQ(ret, 0); @@ -87,7 +89,8 @@ 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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); authManager = nullptr; authResponseState->authManager_ = authManager; int32_t ret = authResponseState->TransitionTo(std::shared_ptr(new AuthResponseNegotiateState())); @@ -130,9 +133,10 @@ HWTEST_F(AuthResponseStateTest, TransitionTo_002, testing::ext::TestSize.Level0) */ HWTEST_F(AuthResponseStateTest, GetStateType_001, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseInitState()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_RESPONSE_INIT); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_INIT); sleep(15); } @@ -145,9 +149,10 @@ HWTEST_F(AuthResponseStateTest, GetStateType_001, testing::ext::TestSize.Level0) */ 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); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseInitState()); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -158,11 +163,12 @@ HWTEST_F(AuthResponseStateTest, Enter_001, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(AuthResponseStateTest,GetStateType_002, testing::ext::TestSize.Level0) +HWTEST_F(AuthResponseStateTest, GetStateType_002, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseNegotiateState()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseNegotiateState()); int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_RESPONSE_NEGOTIATE); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_NEGOTIATE); sleep(15); } @@ -179,11 +185,12 @@ 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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseNegotiateState()); authManager = nullptr; authResponseState->SetAuthManager(authManager); - int32_t ret =authResponseState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -200,22 +207,23 @@ 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 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"; + 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); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); } /** @@ -227,9 +235,10 @@ HWTEST_F(AuthResponseStateTest, Enter_003, testing::ext::TestSize.Level0) */ HWTEST_F(AuthResponseStateTest, GetStateType_003, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseConfirmState()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseConfirmState()); int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_RESPONSE_CONFIRM); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_CONFIRM); sleep(15); } @@ -241,15 +250,16 @@ HWTEST_F(AuthResponseStateTest, GetStateType_003, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(AuthResponseStateTest, Enter_004 , testing::ext::TestSize.Level0) +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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseConfirmState()); authResponseState->SetAuthManager(nullptr); - int32_t ret =authResponseState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -266,10 +276,11 @@ 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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseConfirmState()); authResponseState->SetAuthManager(authManager); - int32_t ret =authResponseState->Enter(); - ASSERT_EQ(ret,DM_OK); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -282,9 +293,10 @@ HWTEST_F(AuthResponseStateTest, Enter_005, testing::ext::TestSize.Level0) */ HWTEST_F(AuthResponseStateTest, GetStateType_004, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseGroupState()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseGroupState()); int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_RESPONSE_GROUP); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_GROUP); sleep(15); } @@ -301,10 +313,11 @@ 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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseGroupState()); authResponseState->SetAuthManager(nullptr); - int32_t ret =authResponseState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -321,13 +334,14 @@ 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 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); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -340,9 +354,10 @@ HWTEST_F(AuthResponseStateTest, Enter_007, testing::ext::TestSize.Level0) */ HWTEST_F(AuthResponseStateTest, GetStateType_005, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseShowState()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseShowState()); int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_RESPONSE_SHOW); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_SHOW); sleep(15); } @@ -359,10 +374,11 @@ 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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseShowState()); authResponseState->SetAuthManager(nullptr); - int32_t ret =authResponseState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -379,10 +395,11 @@ 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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseShowState()); authResponseState->SetAuthManager(authManager); - int32_t ret =authResponseState->Enter(); - ASSERT_EQ(ret,DM_OK); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_OK); sleep(15); } @@ -395,9 +412,10 @@ HWTEST_F(AuthResponseStateTest, Enter_009, testing::ext::TestSize.Level0) */ HWTEST_F(AuthResponseStateTest, GetStateType_006, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::shared_ptr(new AuthResponseFinishState()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseFinishState()); int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret,AuthState::AUTH_RESPONSE_FINISH); + ASSERT_EQ(ret, AuthState::AUTH_RESPONSE_FINISH); sleep(15); } @@ -414,10 +432,11 @@ 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()); + std::shared_ptr authResponseState = + std::shared_ptr(new AuthResponseFinishState()); authResponseState->SetAuthManager(nullptr); - int32_t ret =authResponseState->Enter(); - ASSERT_EQ(ret,DM_FAILED); + int32_t ret = authResponseState->Enter(); + ASSERT_EQ(ret, DM_FAILED); sleep(15); } @@ -434,27 +453,28 @@ 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()); + 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->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); + 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 index 938bc5319..270e5caff 100644 --- a/test/unittest/UTTest_auth_response_state.h +++ b/test/unittest/UTTest_auth_response_state.h @@ -17,7 +17,9 @@ #define OHOS_AUTH_RESPONSE_STATE_TEST_H #include + #include + #include "auth_response_state.h" namespace OHOS { @@ -29,6 +31,6 @@ public: 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 index effdf8c11..585cea342 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -13,29 +13,30 @@ * limitations under the License. */ -#include "dm_log.h" +#include "UTTest_device_manager_service.h" + #include "dm_constants.h" #include "dm_device_info.h" -#include "UTTest_device_manager_service.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); -void DeviceManagerServiceTest::SetUp() +void DeviceManagerServiceTest::SetUp() { } -void DeviceManagerServiceTest::TearDown() +void DeviceManagerServiceTest::TearDown() { } -void DeviceManagerServiceTest::SetUpTestCase() +void DeviceManagerServiceTest::SetUpTestCase() { } -void DeviceManagerServiceTest::TearDownTestCase() +void DeviceManagerServiceTest::TearDownTestCase() { } namespace { @@ -55,7 +56,7 @@ HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_001, testing::ext::TestS DmSubscribeInfo subscribeInfo; std::string extra = "test"; int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret,DM_NOT_INIT); + EXPECT_EQ(ret, DM_NOT_INIT); } /** @@ -64,7 +65,7 @@ HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_001, testing::ext::TestS * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_002, testing::ext::TestSize.Level0) { std::string pkgName; DmSubscribeInfo subscribeInfo; @@ -76,7 +77,8 @@ HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_002, testing::ext::TestS /** * @tc.name: StartDeviceDiscovery_003 - * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return DM_DISCOVERY_REPEATED + * @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 */ @@ -97,7 +99,7 @@ HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_003, testing::ext::TestS * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSize.Level0) { DeviceManagerService::GetInstance().intFlag_ = false; std::string pkgName = "com.ohos.test"; @@ -112,7 +114,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSi * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSize.Level0) { std::string pkgName; uint16_t subscribeId = 1; @@ -127,7 +129,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSi * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) { DeviceManagerService::GetInstance().intFlag_ = false; DmDeviceInfo info; @@ -141,7 +143,7 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSiz * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSize.Level0) { DmDeviceInfo info; DeviceManagerService::GetInstance().Init(); @@ -172,7 +174,7 @@ HWTEST_F(DeviceManagerServiceTest, Init_002, testing::ext::TestSize.Level0) { DeviceManagerService::GetInstance().intFlag_ = false; std::shared_ptr softbusConnector_ = nullptr; - int ret = DeviceManagerService::GetInstance().Init(); + int ret = DeviceManagerService::GetInstance().Init(); EXPECT_EQ(ret, DM_OK); } @@ -189,7 +191,7 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_001, testing::ext::TestS std::string pkgName = "com.ohos.test"; std::string extra = "jdddd"; std::vector deviceList; - int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, DM_NOT_INIT); } @@ -199,13 +201,13 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_001, testing::ext::TestS * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_002, testing::ext::TestSize.Level0) +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); + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); } @@ -222,7 +224,7 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_001, testing::ext::TestSiz std::string extra = "jdddd"; int32_t authType = 0; std::string deviceId = " 2345"; - int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, DM_NOT_INIT); } @@ -235,11 +237,11 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_001, testing::ext::TestSiz HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_002, testing::ext::TestSize.Level0) { DeviceManagerService::GetInstance().intFlag_ = true; - std::string pkgName ; + std::string pkgName; std::string extra = "jdddd"; int32_t authType = 0; std::string deviceId = " 2345"; - int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, DM_INPUT_PARA_EMPTY); } @@ -256,7 +258,7 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_003, testing::ext::TestSiz std::string extra = "jdddd"; int32_t authType = 0; std::string deviceId = "123456"; - int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + int ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, DM_OK); } @@ -271,7 +273,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_001, testing::ext::TestS DeviceManagerService::GetInstance().intFlag_ = false; std::string pkgName = "com.ohos.test"; std::string deviceId = "12345"; - int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); EXPECT_EQ(ret, DM_NOT_INIT); } @@ -292,7 +294,8 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_002, testing::ext::TestS /** * @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.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 */ @@ -307,16 +310,17 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_003, testing::ext::TestS /** * @tc.name: VerifyAuthentication_001 - * @tc.desc: Set intFlag for VerifyAuthentication to false and set authParam = "jdjjjj",The return value is DM_NOT_INIT + * @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; + DeviceManagerService::GetInstance().intFlag_ = false; std::string authParam = "jdjjjj"; int ret = DeviceManagerService::GetInstance().VerifyAuthentication(authParam); - EXPECT_EQ(ret, DM_NOT_INIT); + EXPECT_EQ(ret, DM_NOT_INIT); } /** @@ -329,14 +333,14 @@ HWTEST_F(DeviceManagerServiceTest, VerifyAuthentication_002, testing::ext::TestS { DeviceManagerService::GetInstance().intFlag_ = true; std::string authParam = "jdjjjj"; - std::shared_ptr softbusConnector = std::make_shared(); + 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); -} -} -} + 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 index 787bd7331..30693e87d 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -15,19 +15,20 @@ #ifndef OHOS_UTTEST_DM_SERVICE_H #define OHOS_UTTEST_DM_SERVICE_H -#include -#include #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 "softbus_connector.h" #include "single_instance.h" -#include "device_manager_service.h" -#include "device_manager_service_listener.h" +#include "softbus_connector.h" namespace OHOS { namespace DistributedHardware { @@ -39,8 +40,8 @@ public: 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 index 63904c473..3d63e1f0c 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -13,27 +13,28 @@ * 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 "dm_anonymous.h" #include "ipc_notify_auth_result_req.h" -#include "ipc_notify_verify_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 "UTTest_device_manager_service_listener.h" +#include "ipc_notify_verify_auth_result_req.h" namespace OHOS { namespace DistributedHardware { void DeviceManagerServiceListenerTest::SetUp() - { - } +{ +} void DeviceManagerServiceListenerTest::TearDown() { } -void DeviceManagerServiceListenerTest::SetUpTestCase() +void DeviceManagerServiceListenerTest::SetUpTestCase() { } void DeviceManagerServiceListenerTest::TearDownTestCase() @@ -43,11 +44,12 @@ namespace { /** * @tc.name: OnDeviceStateChange_001 - * @tc.desc: OnDeviceStateChange, construct a dummy listener, pass in pkgName, use the constructed listener to get deviceTypeId + * @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) +HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; @@ -58,7 +60,8 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext .deviceTypeId = 1, }; listener_->OnDeviceStateChange(pkgName, state, info); - std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); + std::shared_ptr pReq = + std::static_pointer_cast(listener_->ipcServerListener_.req_); int32_t dmState = pReq->GetDeviceState(); EXPECT_EQ(1, dmState); } @@ -69,7 +72,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; @@ -78,14 +81,16 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestS 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::shared_ptr pReq = + std::static_pointer_cast(listener_->ipcServerListener_.req_); std ::string ret = pReq->GetPkgName(); - EXPECT_EQ (ret, pkgName); + 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.desc: OnVerifyAuthResult,construct a dummy listener, pass in pkgName, use the constructed listener to get + * deviceId * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -96,11 +101,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnVerifyAuthResult_001, testing::ext: 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_); + 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); -} -} + EXPECT_EQ(ret, deviceId); } -} \ No newline at end of file +} // 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 index 5b9d3b155..2c07604ca 100644 --- a/test/unittest/UTTest_device_manager_service_listener.h +++ b/test/unittest/UTTest_device_manager_service_listener.h @@ -18,13 +18,14 @@ #define private public #define protected public -#include #include #include +#include + +#include "device_manager_service_listener.h" #include "dm_device_info.h" #include "ipc_server_listener.h" -#include "device_manager_service_listener.h" namespace OHOS { namespace DistributedHardware { @@ -36,8 +37,8 @@ public: 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_info_manager.cpp b/test/unittest/UTTest_dm_device_info_manager.cpp index a49de8334..992f5a011 100644 --- a/test/unittest/UTTest_dm_device_info_manager.cpp +++ b/test/unittest/UTTest_dm_device_info_manager.cpp @@ -15,18 +15,16 @@ #include "UTTest_dm_device_info_manager.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_log.h" -namespace OHOS -{ -namespace DistributedHardware -{ -void DeviceManagerImplTest::SetUp() +namespace OHOS { +namespace DistributedHardware { +void DeviceManagerImplTest::SetUp() { } -void DeviceManagerImplTest::TearDown() +void DeviceManagerImplTest::TearDown() { } @@ -34,15 +32,16 @@ void DeviceManagerImplTest::SetUpTestCase() { } -void DeviceManagerImplTest::TearDownTestCase() +void DeviceManagerImplTest::TearDownTestCase() { } namespace { -std::shared_ptr softbusConnector = std::make_shared(); +std::shared_ptr softbusConnector = std::make_shared(); std::shared_ptr listener_ = std::make_shared(); -std::shared_ptr dmDeviceStateManager = std::shared_ptr(new DmDeviceInfoManager(softbusConnector)); +std::shared_ptr dmDeviceStateManager = + std::shared_ptr(new DmDeviceInfoManager(softbusConnector)); /** * @tc.name: DmDeviceInfoManager_001 @@ -52,11 +51,12 @@ std::shared_ptr dmDeviceStateManager = std::shared_ptr p = std::shared_ptr(new DmDeviceInfoManager(softbusConnector)); + std::shared_ptr p = + std::shared_ptr(new DmDeviceInfoManager(softbusConnector)); ASSERT_NE(p, nullptr); } -} -} -} \ No newline at end of file +} // 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 index 0c2e054ee..565d7a8f7 100644 --- a/test/unittest/UTTest_dm_device_info_manager.h +++ b/test/unittest/UTTest_dm_device_info_manager.h @@ -17,14 +17,15 @@ #include #include + #include #include -#include "dm_device_info_manager.h" +#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 "dm_adapter_manager.h" -#include "device_manager_service_listener.h" #include "softbus_session_callback.h" namespace OHOS { @@ -37,8 +38,8 @@ public: 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_hichain_connector.cpp b/test/unittest/UTTest_hichain_connector.cpp index ffe00dbf7..81d163510 100644 --- a/test/unittest/UTTest_hichain_connector.cpp +++ b/test/unittest/UTTest_hichain_connector.cpp @@ -1,26 +1,24 @@ -#include "hichain_connector.h" +#include "UTTest_hichain_connector.h" + +#include #include #include #include -#include -#include "nlohmann/json.hpp" -#include "parameter.h" - -#include "hichain_connector_callback.h" #include "dm_anonymous.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_log.h" #include "dm_random.h" -#include "UTTest_hichain_connector.h" -namespace OHOS -{ -namespace DistributedHardware -{ +#include "hichain_connector.h" +#include "hichain_connector_callback.h" +#include "nlohmann/json.hpp" +#include "parameter.h" +namespace OHOS { +namespace DistributedHardware { void DeviceManagerImplTest::SetUp() { - // DmDiscoveryManage *m_DmDiscoveryManage; + // DmDiscoveryManage *m_DmDiscoveryManage; } void DeviceManagerImplTest::TearDown() @@ -34,192 +32,186 @@ void DeviceManagerImplTest::SetUpTestCase() void DeviceManagerImplTest::TearDownTestCase() { } -namespace -{ +namespace { HWTEST_F(DeviceManagerImplTest, CreateGroup1, testing::ext::TestSize.Level0) { - int64_t requestId = 123456; - std::string groupName = "lijia"; - std::shared_ptr hichainConnector = std::make_shared(); - hichainConnector-> deviceGroupManager_ = nullptr; - int ret = hichainConnector->CreateGroup(requestId, groupName); - EXPECT_EQ(ret, DM_INVALID_VALUE); + int64_t requestId = 123456; + std::string groupName = "lijia"; + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->deviceGroupManager_ = nullptr; + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_INVALID_VALUE); } - HWTEST_F(DeviceManagerImplTest, CreateGroup2, testing::ext::TestSize.Level0) { - int64_t requestId = 233444; - std::string groupName; - std::string DM_PKG_NAME = " "; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->CreateGroup(requestId, groupName); - EXPECT_EQ(ret, DM_OK); + int64_t requestId = 233444; + std::string groupName; + std::string DM_PKG_NAME = " "; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerImplTest, CreateGroup3, testing::ext::TestSize.Level0) { - int64_t requestId = 123456; - std::string groupName = "lijia"; - // std::string DM_PKG_NAME = " "; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->CreateGroup(requestId, groupName); - EXPECT_EQ(ret, DM_OK); + int64_t requestId = 123456; + std::string groupName = "lijia"; + // std::string DM_PKG_NAME = " "; + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->CreateGroup(requestId, groupName); + EXPECT_EQ(ret, DM_OK); } - HWTEST_F(DeviceManagerImplTest, GetGroupInfo1, 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); + 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); } HWTEST_F(DeviceManagerImplTest, GetGroupInfo2, testing::ext::TestSize.Level0) { - std::shared_ptr hichainConnector = std::make_shared(); - std::string groupName = " "; - 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); + std::shared_ptr hichainConnector = std::make_shared(); + std::string groupName = " "; + 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); } HWTEST_F(DeviceManagerImplTest, GetGroupInfo3, 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); - std::cout << "ret= " << ret << std ::endl; - EXPECT_EQ(ret, 0); + 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); + std::cout << "ret= " << ret << std ::endl; + EXPECT_EQ(ret, 0); } HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid1, testing::ext::TestSize.Level0) { - GroupInfo group; - group.groupName = "dkdkkdkdk"; - group.groupId = 1; - group.groupOwner = "ohos.disware.devicemanagersdsdss"; - group.groupType = 1; - group.groupVisibility = -1; - std::shared_ptr hichainConnector = std::make_shared(); - bool ret = hichainConnector->IsGroupInfoInvalid(group); - EXPECT_EQ(ret, true); + GroupInfo group; + group.groupName = "dkdkkdkdk"; + group.groupId = 1; + group.groupOwner = "ohos.disware.devicemanagersdsdss"; + group.groupType = 1; + group.groupVisibility = -1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, true); } HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid2, testing::ext::TestSize.Level0) { - GroupInfo group; - group.groupName = "lijia"; - group.groupId = 1; - group.groupOwner = "ohos.disware.devicemanagersdsdss"; - group.groupType = 1; - group.groupVisibility = 1; - std::shared_ptr hichainConnector = std::make_shared(); - bool ret = hichainConnector->IsGroupInfoInvalid(group); - EXPECT_EQ(ret, true); + GroupInfo group; + group.groupName = "lijia"; + group.groupId = 1; + group.groupOwner = "ohos.disware.devicemanagersdsdss"; + group.groupType = 1; + group.groupVisibility = 1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, true); } HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid3, testing::ext::TestSize.Level0) { - GroupInfo group; - group.groupName = "lijia"; - group.groupId = -1; - group.groupName = "ohos.distributedhardware.devicemanager"; - group.groupType = 0; - group.groupVisibility = -1; - std::shared_ptr hichainConnector = std::make_shared(); - bool ret = hichainConnector->IsGroupInfoInvalid(group); - EXPECT_EQ(ret, true); + GroupInfo group; + group.groupName = "lijia"; + group.groupId = -1; + group.groupName = "ohos.distributedhardware.devicemanager"; + group.groupType = 0; + group.groupVisibility = -1; + std::shared_ptr hichainConnector = std::make_shared(); + bool ret = hichainConnector->IsGroupInfoInvalid(group); + EXPECT_EQ(ret, true); } - HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup1, testing::ext::TestSize.Level0) { - std::string groupId = "1746"; - std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - // dmSubscribeInfo.capability = -1290002262 ; - std::shared_ptr hichainConnector = std::make_shared(); - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; - - if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { - deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; - } - int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); - EXPECT_EQ(ret, DM_OK); + std::string groupId = "1746"; + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + // dmSubscribeInfo.capability = -1290002262 ; + std::shared_ptr hichainConnector = std::make_shared(); + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + + if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { + deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; + } + int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup2, 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); + 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); } HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup3, testing::ext::TestSize.Level0) { - std::string groupId = "123445"; - std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - // dmSubscribeInfo.capability = -1290002262 ; - std::shared_ptr hichainConnector = std::make_shared(); - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; - int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); - EXPECT_EQ(ret, 0); + std::string groupId = "123445"; + std::string pkgName = "com.softbus.test"; + int32_t freq = 2; + int32_t mode = 170; + int32_t medium = 0; + DmSubscribeInfo dmSubscribeInfo; + dmSubscribeInfo.subscribeId = 1737; + dmSubscribeInfo.mode = (DmDiscoverMode)mode; + dmSubscribeInfo.medium = (DmExchangeMedium)medium; + dmSubscribeInfo.freq = (DmExchangeFreq)freq; + dmSubscribeInfo.isSameAccount = 0; + dmSubscribeInfo.isWakeRemote = 1; + // dmSubscribeInfo.capability = -1290002262 ; + std::shared_ptr hichainConnector = std::make_shared(); + static std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); + std::string deviceId = ""; + int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); + EXPECT_EQ(ret, 0); } HWTEST_F(DeviceManagerImplTest, GenRequestId1, testing::ext::TestSize.Level0) { - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->GenRequestId(); - std::cout << "ret= " << ret << std ::endl; - EXPECT_TRUE (ret != 0); + std::shared_ptr hichainConnector = std::make_shared(); + int ret = hichainConnector->GenRequestId(); + std::cout << "ret= " << ret << std ::endl; + EXPECT_TRUE(ret != 0); } +} // namespace - -} - -} -} \ No newline at end of file +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_hichain_connector.h b/test/unittest/UTTest_hichain_connector.h index 4e926ee08..b6aff2d17 100644 --- a/test/unittest/UTTest_hichain_connector.h +++ b/test/unittest/UTTest_hichain_connector.h @@ -1,22 +1,22 @@ #ifndef OHOS_UTTEST_HICHAIN_CONNECTOR_H #define OHOS_UTTEST_HICHAIN_CONNECTOR_H - #include #include -#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_discovery_manager.h" #include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "hichain_connector_callback.h" +#include "nlohmann/json.hpp" +#include "single_instance.h" namespace OHOS { namespace DistributedHardware { @@ -28,9 +28,8 @@ public: virtual void TearDown() override; }; - -} -} +} // namespace DistributedHardware +} // namespace OHOS #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 index bdd6fd115..df6a4f61a 100644 --- a/test/unittest/UTTest_softbus_connector.cpp +++ b/test/unittest/UTTest_softbus_connector.cpp @@ -12,46 +12,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "UTTest_softbus_connector.h" + +#include +#include + #include #include -#include -#include -#include "parameter.h" -#include "system_ability_definition.h" -#include "dm_log.h" #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 "UTTest_softbus_connector.h" +#include "system_ability_definition.h" -namespace OHOS -{ -namespace DistributedHardware -{ -void SoftbusConnectorTest::SetUp() +namespace OHOS { +namespace DistributedHardware { +void SoftbusConnectorTest::SetUp() { } -void SoftbusConnectorTest::TearDown() +void SoftbusConnectorTest::TearDown() { } -void SoftbusConnectorTest::SetUpTestCase() +void SoftbusConnectorTest::SetUpTestCase() { } -void SoftbusConnectorTest::TearDownTestCase() +void SoftbusConnectorTest::TearDownTestCase() { } namespace { -static std::shared_ptr softbusConnector = std::make_shared(); +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) +HWTEST_F(SoftbusConnectorTest, Init_001, testing::ext::TestSize.Level0) { int ret = softbusConnector->Init(); EXPECT_EQ(ret, DM_OK); @@ -63,12 +63,14 @@ HWTEST_F(SoftbusConnectorTest, Init_001, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, RegisterSoftbusDiscoveryCallback_001, testing::ext::TestSize.Level0) +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_)); + 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); @@ -76,14 +78,15 @@ HWTEST_F(SoftbusConnectorTest, RegisterSoftbusDiscoveryCallback_001, testing::ex /** * @tc.name: UnRegisterSoftbusDiscoveryCallback_001 - * @tc.desc: set pkgName = "com.ohos.helloworld";call UnRegisterSoftbusDiscoveryCallback function to corrort ,return DM_OK + * @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) +HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusDiscoveryCallback_001, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.helloworld"; - int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); + int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); EXPECT_EQ(ret1, 0); EXPECT_EQ(ret, DM_OK); @@ -95,10 +98,10 @@ HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusDiscoveryCallback_001, testing:: * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusStateCallback_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusStateCallback_001, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.helloworld"; - int ret = softbusConnector->UnRegisterSoftbusStateCallback(pkgName); + int ret = softbusConnector->UnRegisterSoftbusStateCallback(pkgName); int ret1 = SoftbusConnector::stateCallbackMap_.count(pkgName); EXPECT_EQ(ret1, 0); EXPECT_EQ(ret, DM_OK); @@ -110,7 +113,7 @@ HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusStateCallback_001, testing::ext: * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetTrustedDeviceList_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetTrustedDeviceList_001, testing::ext::TestSize.Level0) { std::vector deviceInfoList; int ret = softbusConnector->GetTrustedDeviceList(deviceInfoList); @@ -123,11 +126,11 @@ HWTEST_F(SoftbusConnectorTest, GetTrustedDeviceList_001, testing::ext::TestSize. * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) { std::string pkgName = "com.softbus.test"; DmDeviceInfo deviceInfo; - int ret = softbusConnector->GetLocalDeviceInfo(deviceInfo); + int ret = softbusConnector->GetLocalDeviceInfo(deviceInfo); EXPECT_EQ(ret, DM_OK); } @@ -137,10 +140,10 @@ HWTEST_F(SoftbusConnectorTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Le * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0) { DmSubscribeInfo dmSubscribeInfo; - int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); + int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); EXPECT_EQ(ret, DM_DISCOVERY_FAILED); } @@ -150,9 +153,10 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_001, testing::ext::TestSize.Level0) { +HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_001, testing::ext::TestSize.Level0) +{ std::string deviceId = "12333"; - bool ret = softbusConnector->IsDeviceOnLine(deviceId); + bool ret = softbusConnector->IsDeviceOnLine(deviceId); EXPECT_EQ(ret, false); } @@ -162,11 +166,11 @@ HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_001, testing::ext::TestSize.Level0 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_002, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_002, testing::ext::TestSize.Level0) { std::string deviceId = "145677"; NodeBasicInfo Info; - strncpy (Info.networkId, "145677", sizeof(Info.networkId)); + strncpy(Info.networkId, "145677", sizeof(Info.networkId)); bool ret = softbusConnector->IsDeviceOnLine(deviceId); EXPECT_EQ(ret, false); } @@ -177,7 +181,7 @@ HWTEST_F(SoftbusConnectorTest, IsDeviceOnLine_002, testing::ext::TestSize.Level0 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, SoftbusConnector_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SoftbusConnector_001, testing::ext::TestSize.Level0) { std::shared_ptr m_SoftbusConnector = std::make_shared(); ASSERT_NE(m_SoftbusConnector, nullptr); @@ -189,7 +193,7 @@ HWTEST_F(SoftbusConnectorTest, SoftbusConnector_001, testing::ext::TestSize.Leve * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, SoftbusConnector_002, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SoftbusConnector_002, testing::ext::TestSize.Level0) { std::shared_ptr m_SoftbusConnector = std::make_shared(); m_SoftbusConnector.reset(); @@ -202,12 +206,12 @@ HWTEST_F(SoftbusConnectorTest, SoftbusConnector_002, testing::ext::TestSize.Leve * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_001, testing::ext::TestSize.Level0) +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); + EXPECT_EQ(ret, DM_FAILED); } /** @@ -216,11 +220,12 @@ HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_001, testing::ext::TestSiz * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_002, testing::ext::TestSize.Level0) { +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); + int ret = softbusConnector->GetConnectionIpAddress(deviceId, ipAddress); + EXPECT_EQ(ret, DM_FAILED); } /** * @tc.name: GetConnectionIpAddress_003 @@ -228,14 +233,14 @@ HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_002, testing::ext::TestSiz * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_003, testing::ext::TestSize.Level0) +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); + EXPECT_EQ(ret, DM_FAILED); } /** @@ -243,13 +248,13 @@ HWTEST_F(SoftbusConnectorTest, GetConnectionIpAddress_003, testing::ext::TestSiz * @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) +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); + EXPECT_EQ(p, ret); } /** @@ -258,9 +263,9 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddrByType_001, testing::ext::TestSize. * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetConnectAddrByType_002, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetConnectAddrByType_002, testing::ext::TestSize.Level0) { - DeviceInfo deviceInfo ; + DeviceInfo deviceInfo; deviceInfo.addrNum = 1; ConnectionAddrType type; type = CONNECTION_ADDR_BR; @@ -275,7 +280,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddrByType_002, testing::ext::TestSize. * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetConnectAddr_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetConnectAddr_001, testing::ext::TestSize.Level0) { std::string deviceId; std::string connectAddr; @@ -289,7 +294,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_001, testing::ext::TestSize.Level0 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, GetConnectAddr_002, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetConnectAddr_002, testing::ext::TestSize.Level0) { std::string deviceId = "123345"; std::string connectAddr; @@ -305,7 +310,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_002, testing::ext::TestSize.Level0 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, CovertNodeBasicInfoToDmDevice_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, CovertNodeBasicInfoToDmDevice_001, testing::ext::TestSize.Level0) { NodeBasicInfo nodeBasicInfo; DmDeviceInfo dmDeviceInfo; @@ -319,7 +324,7 @@ HWTEST_F(SoftbusConnectorTest, CovertNodeBasicInfoToDmDevice_001, testing::ext:: * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnPublishSuccess_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, OnPublishSuccess_001, testing::ext::TestSize.Level0) { int32_t publishId = 0; int ret = softbusConnector->OnPublishSuccess(publishId); @@ -332,7 +337,7 @@ HWTEST_F(SoftbusConnectorTest, OnPublishSuccess_001, testing::ext::TestSize.Leve * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnPublishFail1, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, OnPublishFail1, testing::ext::TestSize.Level0) { int32_t publishId = 0; PublishFailReason reason; @@ -347,7 +352,7 @@ HWTEST_F(SoftbusConnectorTest, OnPublishFail1, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnSoftBusDeviceOnline_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, OnSoftBusDeviceOnline_001, testing::ext::TestSize.Level0) { NodeBasicInfo info; int ret = softbusConnector->OnSoftBusDeviceOnline(&info); @@ -360,7 +365,7 @@ HWTEST_F(SoftbusConnectorTest, OnSoftBusDeviceOnline_001, testing::ext::TestSize * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceOffline_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceOffline_001, testing::ext::TestSize.Level0) { NodeBasicInfo info; int ret = softbusConnector->OnSoftbusDeviceOffline(&info); @@ -373,7 +378,7 @@ HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceOffline_001, testing::ext::TestSiz * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceInfoChanged_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceInfoChanged_001, testing::ext::TestSize.Level0) { NodeBasicInfo info; NodeBasicInfoType type; @@ -388,7 +393,7 @@ HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceInfoChanged_001, testing::ext::Tes * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceFound_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceFound_001, testing::ext::TestSize.Level0) { DeviceInfo device; int ret = softbusConnector->OnSoftbusDeviceFound(&device); @@ -401,11 +406,11 @@ HWTEST_F(SoftbusConnectorTest, OnSoftbusDeviceFound_001, testing::ext::TestSize. * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnSoftbusDiscoveryFailed_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, OnSoftbusDiscoveryFailed_001, testing::ext::TestSize.Level0) { int32_t subscribeId = 0; DiscoveryFailReason failReason; - failReason = DISCOVERY_FAIL_REASON_NOT_SUPPORT_MEDIUM ; + failReason = DISCOVERY_FAIL_REASON_NOT_SUPPORT_MEDIUM; int ret = softbusConnector->OnSoftbusDiscoveryFailed(subscribeId, failReason); EXPECT_EQ(ret, DM_OK); } @@ -429,13 +434,14 @@ HWTEST_F(SoftbusConnectorTest, OnSoftbusDiscoverySuccess_001, testing::ext::Test * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusConnectorTest, OnParameterChgCallback_001, testing::ext::TestSize.Level0) { +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); } -} -} -} \ No newline at end of file +} // 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 index 757b1b8c1..03857486c 100644 --- a/test/unittest/UTTest_softbus_connector.h +++ b/test/unittest/UTTest_softbus_connector.h @@ -15,43 +15,41 @@ #ifndef OHOS_UTTest_DM_SOFTBUS_CONNECTOR_H #define OHOS_UTTest_DM_SOFTBUS_CONNECTOR_H -#define private public // hack complier +#define private public // hack complier #define protected public #include #include -#include -#include + #include #include +#include +#include #include -#include "softbus_bus_center.h" + +#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_state_callback.h" +#include "softbus_bus_center.h" +#include "softbus_connector.h" #include "softbus_discovery_callback.h" #include "softbus_session.h" -#include "softbus_connector.h" -#include "device_manager_service_listener.h" -#include "dm_discovery_manager.h" -#include "dm_device_state_manager.h" -namespace OHOS -{ -namespace DistributedHardware -{ +#include "softbus_state_callback.h" +namespace OHOS { +namespace DistributedHardware { - class SoftbusConnectorTest : public testing::Test -{ +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 - +#endif diff --git a/test/unittest/UTTest_softbus_session.cpp b/test/unittest/UTTest_softbus_session.cpp index b7c7db3a8..0be9cf6d1 100644 --- a/test/unittest/UTTest_softbus_session.cpp +++ b/test/unittest/UTTest_softbus_session.cpp @@ -12,28 +12,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "softbus_connector.h" +#include "UTTest_softbus_session.h" + +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" -#include "dm_anonymous.h" #include "nlohmann/json.hpp" -#include "UTTest_softbus_session.h" +#include "softbus_connector.h" #include "softbus_session.h" -namespace OHOS -{ -namespace DistributedHardware -{ -void SoftbusSessionTest::SetUp() +namespace OHOS { +namespace DistributedHardware { +void SoftbusSessionTest::SetUp() { } -void SoftbusSessionTest::TearDown() +void SoftbusSessionTest::TearDown() { } -void SoftbusSessionTest::SetUpTestCase() +void SoftbusSessionTest::SetUpTestCase() { } -void SoftbusSessionTest::TearDownTestCase() +void SoftbusSessionTest::TearDownTestCase() { } @@ -47,7 +46,7 @@ std::shared_ptr softbusSession = std::make_sharedOpenAuthSession(deviceId); @@ -60,7 +59,7 @@ HWTEST_F(SoftbusSessionTest, OpenAuthSession_001, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, OpenAuthSession_002, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, OpenAuthSession_002, testing::ext::TestSize.Level0) { std::string deviceId = "123456"; int ret = softbusSession->OpenAuthSession(deviceId); @@ -73,7 +72,7 @@ HWTEST_F(SoftbusSessionTest, OpenAuthSession_002, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, SendData_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, SendData_001, testing::ext::TestSize.Level0) { std::string message = ""; int32_t sessionId = -1; @@ -87,7 +86,7 @@ HWTEST_F(SoftbusSessionTest, SendData_001, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) { int32_t msgType = 2; nlohmann::json jsonObj; @@ -105,7 +104,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level0) { int result = 0; int32_t sessionId = -1; @@ -119,7 +118,7 @@ HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, SoftbusSession_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, SoftbusSession_001, testing::ext::TestSize.Level0) { std::shared_ptr m_SoftbusSession = std::make_shared(); ASSERT_NE(m_SoftbusSession, nullptr); @@ -127,11 +126,11 @@ HWTEST_F(SoftbusSessionTest, SoftbusSession_001, testing::ext::TestSize.Level0) /** * @tc.name: SoftbusSession_002 - * @tc.desc: set SoftbusSession to make a new pointer , it not nullptr and delete it + * @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) +HWTEST_F(SoftbusSessionTest, SoftbusSession_002, testing::ext::TestSize.Level0) { std::shared_ptr m_SoftbusSession = std::make_shared(); m_SoftbusSession.reset(); @@ -144,7 +143,7 @@ HWTEST_F(SoftbusSessionTest, SoftbusSession_002, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, OnSessionClosed_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, OnSessionClosed_001, testing::ext::TestSize.Level0) { int32_t sessionId = 3; int ret = softbusSession->OnSessionClosed(sessionId); @@ -157,12 +156,12 @@ HWTEST_F(SoftbusSessionTest, OnSessionClosed_001, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, OnBytesReceived_002, testing::ext::TestSize.Level0) +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); + int ret = softbusSession->OnBytesReceived(sessionId, data, dataLen); EXPECT_EQ(ret, DM_OK); } @@ -172,7 +171,7 @@ HWTEST_F(SoftbusSessionTest, OnBytesReceived_002, testing::ext::TestSize.Level0) * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, CloseAuthSession_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, CloseAuthSession_001, testing::ext::TestSize.Level0) { int32_t sessionId = 3; int ret = softbusSession->CloseAuthSession(sessionId); @@ -185,26 +184,26 @@ HWTEST_F(SoftbusSessionTest, CloseAuthSession_001, testing::ext::TestSize.Level0 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(SoftbusSessionTest, GetPeerDeviceId_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusSessionTest, GetPeerDeviceId_001, testing::ext::TestSize.Level0) { int32_t sessionId = 3; - std::string peerDevId ; + 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) + * @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 index 987177018..41998d6f6 100644 --- a/test/unittest/UTTest_softbus_session.h +++ b/test/unittest/UTTest_softbus_session.h @@ -17,35 +17,33 @@ #include #include + +#include +#include #include -#include #include -#include -#include +#include -#include "session.h" -#include "inner_session.h" -#include "softbus_session_callback.h" #include "device_manager_service_listener.h" -#include "dm_discovery_manager.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 -{ +namespace OHOS { +namespace DistributedHardware { -class SoftbusSessionTest : public testing::Test -{ +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 index ea6fb9896..78d7581b7 100644 --- a/test/unittest/auth_request_state.cpp +++ b/test/unittest/auth_request_state.cpp @@ -23,11 +23,13 @@ namespace OHOS { namespace DistributedHardware { -int32_t AuthRequestState::Leave() { +int32_t AuthRequestState::Leave() +{ return DM_OK; } -int32_t AuthRequestState::SetAuthManager(std::shared_ptr authManager) { +int32_t AuthRequestState::SetAuthManager(std::shared_ptr authManager) +{ authManager_ = std::move(authManager); return DM_OK; } @@ -36,19 +38,22 @@ int32_t AuthRequestState::SetAuthManager(std::shared_ptr authMana // lastState_ = state; // } -int32_t AuthRequestState::SetAuthContext(std::shared_ptr context) { +int32_t AuthRequestState::SetAuthContext(std::shared_ptr context) +{ context_ = std::move(context); return DM_OK; } -std::shared_ptr AuthRequestState::GetAuthContext() { +std::shared_ptr AuthRequestState::GetAuthContext() +{ return context_; } -int32_t AuthRequestState::TransitionTo(std::shared_ptr state) { +int32_t AuthRequestState::TransitionTo(std::shared_ptr state) +{ LOGE("AuthRequestState::TransitionTo"); std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -60,13 +65,15 @@ int32_t AuthRequestState::TransitionTo(std::shared_ptr state) return DM_OK; } -int32_t AuthRequestInitState::GetStateType() { +int32_t AuthRequestInitState::GetStateType() +{ return AuthState::AUTH_REQUEST_INIT; } -int32_t AuthRequestInitState::Enter() { +int32_t AuthRequestInitState::Enter() +{ std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -74,14 +81,16 @@ int32_t AuthRequestInitState::Enter() { return DM_OK; } -int32_t AuthRequestNegotiateState::GetStateType() { +int32_t AuthRequestNegotiateState::GetStateType() +{ return AuthState::AUTH_REQUEST_NEGOTIATE; } -int32_t AuthRequestNegotiateState::Enter() { -// //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 +int32_t AuthRequestNegotiateState::Enter() +{ + // //1. 检查加解密模块是否存在并获取加解密的名称和版本信息 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -89,19 +98,21 @@ int32_t AuthRequestNegotiateState::Enter() { return DM_OK; } -int32_t AuthRequestNegotiateDoneState::GetStateType() { +int32_t AuthRequestNegotiateDoneState::GetStateType() +{ return AuthState::AUTH_REQUEST_NEGOTIATE_DONE; } -int32_t AuthRequestNegotiateDoneState::Enter() { -// //1. 获取对端加解密信息,并对比两端状态 -// -// //2. 保存加解密状态,发送认证请求 -// authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH); -// std::string message; -// softbusSession_->SendData(context_.sessionId, message); +int32_t 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) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -109,18 +120,20 @@ int32_t AuthRequestNegotiateDoneState::Enter() { return DM_OK; } -int32_t AuthRequestReplyState::GetStateType() { +int32_t AuthRequestReplyState::GetStateType() +{ return AuthState::AUTH_REQUEST_REPLY; } -int32_t AuthRequestReplyState::Enter() { - //1. 收到请求响应,判断用户响应结果 +int32_t AuthRequestReplyState::Enter() +{ + // 1. 收到请求响应,判断用户响应结果 - //2. 用户授权同意 + // 2. 用户授权同意 - //3. 回调给认证实现模块,启动认证 + // 3. 回调给认证实现模块,启动认证 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -128,17 +141,19 @@ int32_t AuthRequestReplyState::Enter() { return DM_OK; } -int32_t AuthRequestInputState::GetStateType() { +int32_t AuthRequestInputState::GetStateType() +{ return AuthState::AUTH_REQUEST_INPUT; } -int32_t AuthRequestInputState::Enter() { -// //1. 获取用户输入 -// -// //2. 验证认证信息 +int32_t AuthRequestInputState::Enter() +{ + // //1. 获取用户输入 + // + // //2. 验证认证信息 LOGE("DmAuthManager::AuthRequestInputState"); std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -146,15 +161,17 @@ int32_t AuthRequestInputState::Enter() { return DM_OK; } -int32_t AuthRequestJoinState::GetStateType() { +int32_t AuthRequestJoinState::GetStateType() +{ return AuthState::AUTH_REQUEST_JOIN; } -int32_t AuthRequestJoinState::Enter() { - //1. 加入群组 +int32_t AuthRequestJoinState::Enter() +{ + // 1. 加入群组 LOGE("DmAuthManager::AuthRequestJoinState"); std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -162,14 +179,16 @@ int32_t AuthRequestJoinState::Enter() { return DM_OK; } -int32_t AuthRequestNetworkState::GetStateType() { +int32_t AuthRequestNetworkState::GetStateType() +{ return AuthState::AUTH_REQUEST_NETWORK; } -int32_t AuthRequestNetworkState::Enter() { - //1. 进行组网 +int32_t AuthRequestNetworkState::Enter() +{ + // 1. 进行组网 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + if (stateAuthManager == nullptr) { LOGE("AuthRequestState::authManager_ null"); return DM_FAILED; } @@ -177,20 +196,22 @@ int32_t AuthRequestNetworkState::Enter() { return DM_OK; } -int32_t AuthRequestFinishState::GetStateType() { +int32_t AuthRequestFinishState::GetStateType() +{ return AuthState::AUTH_REQUEST_FINISH; } -int32_t AuthRequestFinishState::Enter() { - //1. 清理资源 - //2. 通知对端认证结束,并关闭认证通道 +int32_t AuthRequestFinishState::Enter() +{ + // 1. 清理资源 + // 2. 通知对端认证结束,并关闭认证通道 std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { + 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 index b8c0fd08c..e44c6bb6c 100644 --- a/test/unittest/device_manager_impl_test.cpp +++ b/test/unittest/device_manager_impl_test.cpp @@ -14,11 +14,12 @@ */ #include "device_manager_impl_test.h" -#include "dm_constants.h" -#include "dm_device_info.h" #include +#include "dm_constants.h" +#include "dm_device_info.h" + namespace OHOS { namespace DistributedHardware { void DeviceManagerImplTest::SetUp() @@ -41,7 +42,7 @@ namespace { HWTEST_F(DeviceManagerImplTest, InitDeviceManager, testing::ext::TestSize.Level0) { std::string packName = ""; - int32_t ret= DeviceManager::GetInstance().InitDeviceManager(packName, nullptr); + int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, nullptr); ASSERT_EQ(ret, DM_INVALID_VALUE); } @@ -50,10 +51,10 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice1, testing::ext::TestSize.Leve std::string packName = ""; DmDeviceInfo dmDeviceInfo; DmAppImageInfo dmAppImageInfo; - std::string extra= ""; + std::string extra = ""; std::shared_ptr callback = nullptr; - int32_t ret= DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, - dmAppImageInfo, extra, callback); + int32_t ret = + DeviceManager::GetInstance().AuthenticateDevice(packName, dmDeviceInfo, dmAppImageInfo, extra, callback); ASSERT_EQ(ret, DM_INVALID_VALUE); } @@ -67,9 +68,10 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice2, testing::ext::TestSize.Leve 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); + .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; } @@ -84,9 +86,10 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice3, testing::ext::TestSize.Leve 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); + .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; } @@ -108,8 +111,9 @@ HWTEST_F(DeviceManagerImplTest, CheckAuthentication2, testing::ext::TestSize.Lev 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); + .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; } @@ -122,8 +126,9 @@ HWTEST_F(DeviceManagerImplTest, CheckAuthentication3, testing::ext::TestSize.Lev 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); + .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; } @@ -145,7 +150,8 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery2, testing::ext::TestSize.Le 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)); + .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; @@ -159,9 +165,10 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery3, testing::ext::TestSize.Le 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)); + .Times(1) + .WillOnce(testing::Return(DM_FAILED)); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, test_callback_); - ASSERT_EQ(ret, DM_IPC_FAILED); + ASSERT_EQ(ret, DM_IPC_FAILED); DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; } } // namespace @@ -181,5 +188,5 @@ void DeviceDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDevice { (void)subscribeId; } -} // namespace Vsync +} // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/device_manager_impl_test.h b/test/unittest/device_manager_impl_test.h index 4bfd6b28a..ffcb70e32 100644 --- a/test/unittest/device_manager_impl_test.h +++ b/test/unittest/device_manager_impl_test.h @@ -19,10 +19,10 @@ #include #include -#include "mock/mock_ipc_client_proxy.h" -#include "device_manager_impl.h" -#include "device_manager_callback.h" #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 { @@ -32,19 +32,24 @@ public: 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 {} + 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 Vsync +} // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_IMPL_TEST_H diff --git a/test/unittest/mock/ipc_server_listener.h b/test/unittest/mock/ipc_server_listener.h index 20462face..e0f072ac8 100644 --- a/test/unittest/mock/ipc_server_listener.h +++ b/test/unittest/mock/ipc_server_listener.h @@ -16,8 +16,9 @@ #ifndef OHOS_DM_IPC_SERVER_LISTENER_H #define OHOS_DM_IPC_SERVER_LISTENER_H -#include #include +#include + #include "ipc_req.h" #include "ipc_rsp.h" @@ -27,6 +28,7 @@ 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); diff --git a/utils/include/ipc/lite/ipc_cmd_register.h b/utils/include/ipc/lite/ipc_cmd_register.h index 6f95e3a30..f3d6ac3d7 100644 --- a/utils/include/ipc/lite/ipc_cmd_register.h +++ b/utils/include/ipc/lite/ipc_cmd_register.h @@ -17,14 +17,13 @@ #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 { diff --git a/utils/include/ipc/standard/ipc_cmd_register.h b/utils/include/ipc/standard/ipc_cmd_register.h index c1f0b02db..167f4ec50 100644 --- a/utils/include/ipc/standard/ipc_cmd_register.h +++ b/utils/include/ipc/standard/ipc_cmd_register.h @@ -17,15 +17,14 @@ #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 { diff --git a/utils/src/dm_random.cpp b/utils/src/dm_random.cpp index 9e550212f..129b0792e 100644 --- a/utils/src/dm_random.cpp +++ b/utils/src/dm_random.cpp @@ -17,14 +17,12 @@ #include +#include "dm_constants.h" #include "mbedtls/base64.h" -#include "mbedtls/gcm.h" -#include "mbedtls/md.h" - #include "mbedtls/ctr_drbg.h" #include "mbedtls/entropy.h" - -#include "dm_constants.h" +#include "mbedtls/gcm.h" +#include "mbedtls/md.h" namespace OHOS { namespace DistributedHardware { -- Gitee From 95c52ca282f66711bd735f5e0bc10ef11dbe0474 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Mon, 10 Jan 2022 13:18:49 +0800 Subject: [PATCH 094/110] add by weidong.liu@thundersoft.com change: fix getTrustDeviceListSync bug --- interfaces/kits/js/src/native_devicemanager_js.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index bdd76d794..fe95d2f2c 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1070,6 +1070,12 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba 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 == 1, "Wrong number of arguments"); -- Gitee From 4c39846f9ca398f93a0a2481efe89c9cb10ef03d Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Mon, 10 Jan 2022 14:56:08 +0800 Subject: [PATCH 095/110] =?UTF-8?q?DM=E4=B8=BB=E6=8E=A7=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E5=85=B3=E9=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index d425159dd..3712be61e 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -196,7 +196,10 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) // todo Prompt for input pin code error // break; default: + //修改状态关闭页面 CancelDisplay(); + authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); + } LOGI("DmAuthManager::VerifyAuthentication complete"); @@ -513,6 +516,11 @@ void DmAuthManager::AddMember(const std::string &deviceId) if (ret != 0) { return; } + //加入群组成功,关闭页面 + if (authRequestContext_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) { + LOGI("DmAuthManager::authRequestContext CancelDisplay start"); + CancelDisplay(); + } } std::string DmAuthManager::GetConnectAddr(std::string deviceId) @@ -588,6 +596,7 @@ void DmAuthManager::AuthenticateFinish() void DmAuthManager::CancelDisplay() { + LOGI("DmAuthManager::CancelDisplay start"); nlohmann::json jsonObj; jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PICODE_DISPLAY; std::string paramJson = jsonObj.dump(); -- Gitee From e4f5284e27301060cd967a8bb81d8fd72148eec7 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Mon, 10 Jan 2022 15:45:03 +0800 Subject: [PATCH 096/110] add by weidong.liu@thundersoft.com change : change onProfile deviceInfo save position --- ext/profile/src/profile_connector.cpp | 3 +- .../include/device_manager_service_listener.h | 1 - .../devicestate/dm_device_state_manager.h | 1 + .../src/device_manager_service_listener.cpp | 21 -------------- .../devicestate/dm_device_state_manager.cpp | 28 +++++++++++++++---- 5 files changed, 25 insertions(+), 29 deletions(-) diff --git a/ext/profile/src/profile_connector.cpp b/ext/profile/src/profile_connector.cpp index 370cbcf85..832422a91 100644 --- a/ext/profile/src/profile_connector.cpp +++ b/ext/profile/src/profile_connector.cpp @@ -30,8 +30,7 @@ int32_t ProfileConnector::RegisterProfileCallback(const std::string &pkgName, co { LOGI("ProfileConnector::RegisterProfileCallback"); profileEventCallback_->RegisterProfileCallback(pkgName, callback); - SubscribeProfileEvents({"system", "device", "fakeStorage", "fakeSystem"}, - "5CA4CA0ED9A14B680BBD566307B670E7DF4F9AE932C1145732B660538485307E"); + SubscribeProfileEvents({"system", "device", "fakeStorage", "fakeSystem"}, deviceId); return DM_OK; } diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index b59965b7d..4ad17f9f8 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -39,7 +39,6 @@ public: private: IpcServerListener ipcServerListener_; - std::map remoteDeviceInfos_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 637e44788..0acae5723 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -40,6 +40,7 @@ private: std::shared_ptr adapterMgr_; std::shared_ptr listener_; std::map deviceStateMap_; + std::map remoteDeviceInfos_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 5e6223671..c0b3f9929 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -35,30 +35,9 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam LOGI("OnDeviceStateChange, state=%d", state); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - DmDeviceInfo saveInfo; pReq->SetDeviceState(state); pReq->SetDeviceInfo(info); - - if (state == DEVICE_INFO_CHANGED) { - auto iter = remoteDeviceInfos_.find(info.deviceId); - if (iter == remoteDeviceInfos_.end()) { - LOGE("DeviceManagerServiceListener::OnDeviceStateChange complete not find deviceID"); - } else { - saveInfo = iter->second; - pReq->SetDeviceInfo(saveInfo); - } - } else if (state == DEVICE_STATE_ONLINE) { - DmDeviceInfo saveInfo = info; - remoteDeviceInfos_[info.deviceId] = saveInfo; - } else if (state == DEVICE_STATE_OFFLINE) { - auto iter = remoteDeviceInfos_.find(info.deviceId); - if (iter == remoteDeviceInfos_.end()) { - } else { - remoteDeviceInfos_.erase(info.deviceId); - } - } - ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 37a03d933..c96d03fe1 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -50,9 +50,14 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe LOGE("DmDeviceStateManager::OnDeviceOnline GetNodeKeyInfo failed"); } else { std::string deviceUdid = (char *)udid; - LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener in, deviceId = %s", deviceUdid.c_str()); + LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s", info.deviceId, deviceUdid.c_str()); + DmDeviceInfo saveInfo = info; + std::string uuid; + SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid); + remoteDeviceInfos_[uuid] = saveInfo; + //set networkId or udid; profileAdapter->RegisterProfileListener(pkgName, deviceUdid, shared_from_this()); - LOGI("DmDeviceStateManager::OnDeviceOnline RegisterProfileListener out"); + LOGI("RegisterProfileListener out"); } } DmDeviceState state = DEVICE_STATE_ONLINE; @@ -70,6 +75,13 @@ void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmD 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; @@ -88,10 +100,16 @@ void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDev void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std::string deviceId) { - DmDeviceInfo info; - strcpy(info.deviceId, deviceId.c_str()); + //deviceId is uuid; + DmDeviceInfo saveInfo; + auto iter = remoteDeviceInfos_.find(deviceId); + if (iter == remoteDeviceInfos_.end()) { + LOGE("DmDeviceStateManager::OnProfileReady complete not find deviceID"); + } else { + saveInfo = iter->second; + } DmDeviceState state = DEVICE_INFO_READY; - listener_->OnDeviceStateChange(pkgName, state, info); + listener_->OnDeviceStateChange(pkgName, state, saveInfo); } int32_t DmDeviceStateManager::RegisterSoftbusStateCallback() -- Gitee From eb1c91a7bce42ab51e02d694fee5111bbd30a9a5 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Mon, 10 Jan 2022 16:19:22 +0800 Subject: [PATCH 097/110] add by weidong.liu@thundersoft.com change: remove onProfileChanged function --- ext/profile/include/profile_connector.h | 1 - ext/profile/src/profile_connector.cpp | 13 ------------- .../src/devicestate/dm_device_state_manager.cpp | 5 +++-- 3 files changed, 3 insertions(+), 16 deletions(-) diff --git a/ext/profile/include/profile_connector.h b/ext/profile/include/profile_connector.h index 96ca50055..d83f90749 100644 --- a/ext/profile/include/profile_connector.h +++ b/ext/profile/include/profile_connector.h @@ -33,7 +33,6 @@ using namespace OHOS::DeviceProfile; class ProfileEventCallback : public IProfileEventCallback { public: void OnSyncCompleted(const SyncResult &syncResults); - void OnProfileChanged(const ProfileChangeNotification &changeNotification); int32_t RegisterProfileCallback(const std::string &pkgName, std::shared_ptr callback); int32_t UnRegisterProfileCallback(const std::string &pkgName); diff --git a/ext/profile/src/profile_connector.cpp b/ext/profile/src/profile_connector.cpp index 832422a91..a1a271064 100644 --- a/ext/profile/src/profile_connector.cpp +++ b/ext/profile/src/profile_connector.cpp @@ -48,10 +48,6 @@ int32_t ProfileConnector::SubscribeProfileEvents(const std::list &s extraInfo["serviceIds"] = serviceIds; std::list subscribeInfos; - SubscribeInfo eventChange; - eventChange.profileEvent = ProfileEvent::EVENT_PROFILE_CHANGED; - eventChange.extraInfo = std::move(extraInfo); - subscribeInfos.emplace_back(eventChange); SubscribeInfo eventSync; eventSync.profileEvent = ProfileEvent::EVENT_SYNC_COMPLETED; @@ -106,14 +102,5 @@ void ProfileEventCallback::OnSyncCompleted(const SyncResult &syncResults) iter.second->OnProfileComplete(iter.first, deviceId); } } - -void ProfileEventCallback::OnProfileChanged(const ProfileChangeNotification &changeNotification) -{ - std::string deviceId = changeNotification.GetDeviceId(); - LOGI("ProfileEventCallback::OnProfileChanged, deviceId = %s", deviceId.c_str()); - for (auto &iter : profileConnectorCallback_) { - iter.second->OnProfileChanged(iter.first, deviceId); - } -} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index c96d03fe1..7d7b6db79 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -50,11 +50,12 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe LOGE("DmDeviceStateManager::OnDeviceOnline GetNodeKeyInfo failed"); } else { std::string deviceUdid = (char *)udid; - LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s", info.deviceId, deviceUdid.c_str()); 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"); @@ -104,7 +105,7 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: DmDeviceInfo saveInfo; auto iter = remoteDeviceInfos_.find(deviceId); if (iter == remoteDeviceInfos_.end()) { - LOGE("DmDeviceStateManager::OnProfileReady complete not find deviceID"); + LOGE("DmDeviceStateManager::OnProfileReady complete not find deviceID = %s", deviceId.c_str()); } else { saveInfo = iter->second; } -- Gitee From 79f658ed01ac142fa8d74a05bfd7d9c5ef1d0d96 Mon Sep 17 00:00:00 2001 From: caochao <2930650069@qq.com> Date: Mon, 10 Jan 2022 17:47:20 +0800 Subject: [PATCH 098/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E6=9D=83=E9=99=90=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- interfaces/inner_kits/native_cpp/BUILD.gn | 1 + .../native_cpp/src/device_manager_impl.cpp | 36 ++++++++++--------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 339abe9fe..227c2d711 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -100,6 +100,7 @@ if (defined(ohos_lite)) { deps = [ "${utils_path}:devicemanagerutils", "//utils/native/base:utils", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", ] defines = [ 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 0f41646a5..2bca8dc45 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -18,6 +18,11 @@ #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" @@ -42,32 +47,31 @@ using namespace OHOS::AppExecFwk::Constants; namespace OHOS { namespace DistributedHardware { - bool DeviceManagerImpl::isSystemAppCalling(void) { int32_t uid = IPCSkeleton::GetCallingUid(); - if (uid >= ROOT_UID && uid < BASE_SYS_UID) { - LOGE("check permission true for system uid %d", uid); - return true; + if (uid < 0) { + LOGI("app caller uid is: %d,", uid); + return false; } - - std::string bundleName; - BundleMgrClient bundleMgrClient; - bool ret = bundleMgrClient.GetBundleNameForUid(uid, bundleName); - if (!ret) { - LOGE("get bundle name failed"); + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + LOGE("failed to get system ability mgr."); return false; } - BundleInfo bundleInfo; - ret = bundleMgrClient.GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - if (!ret) { - LOGE("get bundle info failed"); + sptr remoteObject = + systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + LOGE("failed to get bundle manager proxy."); return false; } - LOGI("app caller uid is: %d, bundleInfo is: %s", uid, bundleName.c_str()); - return bundleInfo.applicationInfo.isSystemApp; + LOGI("get bundle manager proxy success."); + sptr iBundleMgr = iface_cast(remoteObject); + return iBundleMgr->CheckIsSystemAppByUid(uid); } DeviceManagerImpl &DeviceManagerImpl::GetInstance() -- Gitee From 567bcebd0fece82d7c80dce3b172d3c30787b282 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Tue, 11 Jan 2022 10:19:52 +0800 Subject: [PATCH 099/110] modify --- common/include/dm_constants.h | 1 + .../include/authentication/dm_auth_manager.h | 1 + .../authentication/auth_message_processor.cpp | 8 +-- .../src/authentication/dm_auth_manager.cpp | 63 +++++++++++++------ .../src/device_manager_service.cpp | 2 +- 5 files changed, 52 insertions(+), 23 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 46fbe0683..cd7403f41 100644 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -80,6 +80,7 @@ enum { 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, diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 2f10abff9..5bf2d4a04 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -160,6 +160,7 @@ public: void ShowStartAuthDialog(); int32_t GetAuthenticationParam(DmAuthParam &authParam); int32_t RegisterSessionCallback(); + int32_t OnUserOperation(int32_t action); private: std::shared_ptr softbusConnector_; diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index dc47ad2bd..1b547a60f 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -112,8 +112,9 @@ void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) json[TAG_CRYPTO_NAME] = cryptoAdapter_->GetName(); json[TAG_CRYPTO_VERSION] = cryptoAdapter_->GetVersion(); json[TAG_DEVICE_ID] = authRequestContext_->deviceId; - json[TAG_LOCAL_DEVICE_ID] = authRequestContext_->localDeviceId; } + json[TAG_REPLY] = authResponseContext_->reply; + json[TAG_LOCAL_DEVICE_ID] = authResponseContext_->localDeviceId; } void AuthMessageProcessor::CreateSyncGroupMessage(nlohmann::json &json) @@ -263,9 +264,8 @@ void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) if (json.contains(TAG_DEVICE_ID)) { authResponseContext_->deviceId = json[TAG_DEVICE_ID]; } - if (json.contains(TAG_LOCAL_DEVICE_ID)) { - authResponseContext_->localDeviceId = json[TAG_LOCAL_DEVICE_ID]; - } + authResponseContext_->localDeviceId = json[TAG_LOCAL_DEVICE_ID]; + authResponseContext_->reply = json[TAG_REPLY]; } void AuthMessageProcessor::SetRequestContext(std::shared_ptr authRequestContext) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index d425159dd..c444c29f0 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -324,6 +324,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + return; } authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseShowState())); authResponseContext_->groupId = groupId; @@ -337,11 +338,10 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) { LOGI("DmAuthManager OnMemberJoin start"); CancelDisplay(); - // timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); LOGE("DmAuthManager OnMemberJoin start"); if (authRequestState_ != nullptr) { - // timerMap_[ADD_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); + 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())); @@ -388,17 +388,11 @@ void DmAuthManager::EstablishAuthChannel(const std::string &deviceId) void DmAuthManager::StartNegotiate(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); - DmDeviceInfo localDevice; - softbusConnector_->GetLocalDeviceInfo(localDevice); - authRequestContext_->localDeviceId = localDevice.deviceId; - bool ret = hiChainConnector_->IsDevicesInGroup(authRequestContext_->localDeviceId, authRequestContext_->deviceId); - if (ret != true) { - LOGE("DmAuthManager::EstablishAuthChannel device is in group"); - authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE; - authRequestContext_->reason = DM_AUTH_DEVICE_AUTHED; - authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestFinishState())); - return; - } + 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); @@ -409,11 +403,14 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) void DmAuthManager::RespNegotiate(const int32_t &sessionId) { LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId); - bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, authResponseContext_->deviceId); - if (ret != true) { + 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; - return; + } else { + authResponseContext_->reply = DM_AUTH_NOT_AUTH; } std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); @@ -445,6 +442,12 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) 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); @@ -461,7 +464,7 @@ void DmAuthManager::StartAuthProcess(const int32_t &action) // 3. 回调给认证实现模块,启动认证 LOGI("DmAuthManager:: StartAuthProcess"); authResponseContext_->reply = action; - if (authResponseContext_->reply == DM_OK && + if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH && authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseGroupState())); } else { @@ -475,7 +478,7 @@ void DmAuthManager::StartRespAuthProcess() { LOGI("DmAuthManager::StartRespAuthProcess StartRespAuthProcess", authResponseContext_->sessionId); timerMap_[CONFIRM_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - if (authResponseContext_->reply == 0) { + 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); @@ -699,5 +702,29 @@ int32_t DmAuthManager::RegisterSessionCallback() 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/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index 87bee5800..dd013d4e6 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -222,7 +222,7 @@ int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t act LOGE("SetUserOperation failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - authMgr_->StartAuthProcess(action); + authMgr_->OnUserOperation(action); return DM_OK; } } // namespace DistributedHardware -- Gitee From 0ca3d8e719f9d2d4ccd819663d03cc2809c88232 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Tue, 11 Jan 2022 15:26:42 +0800 Subject: [PATCH 100/110] add by weidong.liu@thundersoft.com change: change profile soName position for UTtest --- .../include/devicestate/dm_device_state_manager.h | 1 + .../src/devicestate/dm_device_state_manager.cpp | 7 +++---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 0acae5723..a54ef47ef 100644 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -41,6 +41,7 @@ private: std::shared_ptr listener_; std::map deviceStateMap_; std::map remoteDeviceInfos_; + std::string profileSoName_; }; } // 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 index 7d7b6db79..788e75678 100644 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -26,6 +26,7 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof : softbusConnector_(softbusConnector), listener_(listener) { LOGI("DmDeviceStateManager constructor"); + profileSoName_ = "libdevicemanagerext_profile.z.so"; } DmDeviceStateManager::~DmDeviceStateManager() @@ -37,9 +38,8 @@ DmDeviceStateManager::~DmDeviceStateManager() void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) { LOGI("DmDeviceStateManager::OnDeviceOnline in"); - std::string soName = "libdevicemanagerext_profile.z.so"; DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); - std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_); if (profileAdapter == nullptr) { LOGE("OnDeviceOnline profile adapter is null"); } else { @@ -69,9 +69,8 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) { - std::string soName; DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); - std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(soName); + std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_); if (profileAdapter == nullptr) { LOGE("OnDeviceOffline profile adapter is null"); } else { -- Gitee From f69a139029e41099d1874f9b63e6a5d3bd89fffc Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Tue, 11 Jan 2022 15:54:41 +0800 Subject: [PATCH 101/110] =?UTF-8?q?PIN=E7=A0=81=E9=94=99=E8=AF=AF=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/src/device_manager_impl.cpp | 3 ++- .../src/authentication/dm_auth_manager.cpp | 25 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) 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 0f41646a5..28457a965 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -409,6 +409,8 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons LOGE("VerifyAuthentication error: Invalid para"); return DM_INVALID_VALUE; } + + DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -426,7 +428,6 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons return ret; } - DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); LOGI("VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); return DM_OK; } diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 3712be61e..3e93e590c 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -190,16 +190,22 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) int32_t ret = ptr->VerifyAuthentication(authRequestContext_->token, authResponseContext_->code, authParam); switch (ret) { case DM_OK: + { authRequestState_->TransitionTo(std::shared_ptr(new AuthRequestJoinState())); - break; + } + break; case DM_AUTH_INPUT_FAILED: - // todo Prompt for input pin code error - // break; + { + 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"); @@ -516,11 +522,8 @@ void DmAuthManager::AddMember(const std::string &deviceId) if (ret != 0) { return; } - //加入群组成功,关闭页面 - if (authRequestContext_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) { - LOGI("DmAuthManager::authRequestContext CancelDisplay start"); - CancelDisplay(); - } + LOGI("DmAuthManager::authRequestContext CancelDisplay start"); + CancelDisplay(); } std::string DmAuthManager::GetConnectAddr(std::string deviceId) @@ -545,7 +548,7 @@ void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); if (authRequestState_ == nullptr) { - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { CancelDisplay(); } if (!timerMap_.empty()) { -- Gitee From 799e762de22a7d7f55d3c02b8d76de40680339fc Mon Sep 17 00:00:00 2001 From: lichen <123456> Date: Tue, 11 Jan 2022 18:52:04 +0800 Subject: [PATCH 102/110] =?UTF-8?q?=E5=88=A4=E6=96=AD=E9=80=BB=E8=BE=91?= =?UTF-8?q?=E4=BF=AE=E6=94=B9/=E6=97=A5=E5=BF=97=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 428e621c0..f90418f25 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -183,9 +183,11 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); std::shared_ptr ptr; - if (authenticationMap_.find(1) != authenticationMap_.end()) { - ptr = authenticationMap_[1]; - } + 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) { @@ -677,11 +679,14 @@ void DmAuthManager::ShowAuthInfoDialog() void DmAuthManager::ShowStartAuthDialog() { + LOGI("DmAuthManager::ShowStartAuthDialog start"); dmAbilityMgr_ = std::make_shared(); std::shared_ptr ptr; - if (authenticationMap_.find(1) != authenticationMap_.end()) { - ptr = authenticationMap_[1]; - } + if (authenticationMap_.find(1) == authenticationMap_.end()) { + LOGE("DmAuthManager::authenticationMap_ is null"); + return; + } + ptr = authenticationMap_[1]; ptr->StartAuth(dmAbilityMgr_); } -- Gitee From 03d098dadbc3886a598d6b364fe9fa4c3c8c9c3d Mon Sep 17 00:00:00 2001 From: "jia.li" Date: Tue, 11 Jan 2022 20:30:58 +0800 Subject: [PATCH 103/110] TDD lijia --- test/unittest/BUILD.gn | 78 +-- .../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 | 519 +++++++++++++----- test/unittest/UTTest_hichain_connector.h | 42 +- 7 files changed, 992 insertions(+), 186 deletions(-) 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 diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index e5d4257a8..f3899a998 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -27,10 +27,6 @@ group("unittest") { ":UTTest_dm_device_state_manager", ":UTTest_device_manager_service_listener", ":UTTest_dm_device_info_manager", - ":UTTest_device_message", - ":UTTest_auth_response_state", - ":UTTest_auth_request_state", - ":UTTest_dm_auth_manager", ] } @@ -66,6 +62,10 @@ ohos_unittest("UTTest_hichain_connector") { } ## UnitTest UTTest_hichain_connector }}} + + + + ## UnitTest UTTest_dm_device_info_manager {{{ ohos_unittest("UTTest_dm_device_info_manager") { module_out_path = module_out_path @@ -76,6 +76,16 @@ ohos_unittest("UTTest_dm_device_info_manager") { } ## UnitTest UTTest_dm_device_info_manager }}} + + + + + + + + + + ## UnitTest UTTest_softbus_connector {{{ ohos_unittest("UTTest_softbus_connector") { module_out_path = module_out_path @@ -101,18 +111,19 @@ ohos_unittest("UTTest_dm_device_state_manager") { module_out_path = module_out_path sources = [ "UTTest_dm_device_state_manager.cpp", - "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/discovery/dm_discovery_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/test/unittest/mock/ipc_server_listener.cpp", +"//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp", "//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/test/unittest/mock/parameter.cpp", ] + deps = [ ":device_manager_test" ] } @@ -126,6 +137,7 @@ ohos_unittest("UTTest_device_manager_service_listener") { "UTTest_device_manager_service_listener.cpp", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", + ] deps = [ ":device_manager_test" ] @@ -133,51 +145,15 @@ ohos_unittest("UTTest_device_manager_service_listener") { ## UnitTest UTTest_device_manager_service_listener }}} -## UnitTest UTTest_device_message {{{ -ohos_unittest("UTTest_device_message") { - module_out_path = module_out_path - sources = [ "UTTest_device_message.cpp" ] - deps = [ ":device_manager_test_common" ] -} -## UTTest_device_message }}} - -## UnitTest UTTest_auth_response_state {{{ -ohos_unittest("UTTest_auth_response_state") { - module_out_path = module_out_path - sources = [ "UTTest_auth_response_state.cpp" ] - - deps = [ ":device_manager_test_common" ] -} -## UTTest_auth_response_state }}} - -## UnitTest UTTest_auth_request_state {{{ -ohos_unittest("UTTest_auth_request_state") { - module_out_path = module_out_path - - sources = [ "UTTest_auth_request_state.cpp"] - - deps = [ ":device_manager_test_common" ] -} -## UTTest_auth_request_state }}} - -## UnitTest UTTest_dm_auth_manager {{{ -ohos_unittest("UTTest_dm_auth_manager") { - module_out_path = module_out_path - - sources = [ "UTTest_dm_auth_manager.cpp" ] - - deps = [ ":device_manager_test_common" ] -} -## UTTest_dm_auth_manager }}} ## UnitTest UTTest_dm_discovery_manager {{{ ohos_unittest("UTTest_dm_discovery_manager") { module_out_path = module_out_path - sources = [ + sources = [ "UTTest_dm_discovery_manager.cpp", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp", "//foundation/distributedhardware/devicemanager/test/unittest/mock/ipc_server_listener.cpp", @@ -188,7 +164,7 @@ ohos_unittest("UTTest_dm_discovery_manager") { "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/src/device_manager_service_listener.cpp", ] - deps = [ ":device_manager_test_common" ] + deps = [ ":device_manager_test" ] } ## UnitTest UTTest_dm_discovery_manager }}} @@ -212,9 +188,11 @@ config("device_manager_test_common_public_config") { "${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", @@ -225,10 +203,8 @@ config("device_manager_test_common_public_config") { "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/deviceinfo/", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/devicestate", "//foundation/distributedhardware/devicemanager/test/unittest/mock", - "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ability", "//base/security/deviceauth/interfaces/innerkits", - "//foundation/communication/dsoftbus/interfaces/kits/bus_center", - "//foundation/communication/dsoftbus/interfaces/kits/discovery", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ability", "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/config", ] @@ -288,8 +264,10 @@ config("device_manager_test_common_public") { "${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", @@ -301,8 +279,8 @@ config("device_manager_test_common_public") { "//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", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/ability", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/config", ] cflags = [ @@ -360,4 +338,4 @@ ohos_static_library("device_manager_test") { "samgr_standard:samgr_proxy", ] } -## Build device_manager_test.a }}} +## Build device_manager_test.a }}} \ 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 index 81d163510..db28b4607 100644 --- a/test/unittest/UTTest_hichain_connector.cpp +++ b/test/unittest/UTTest_hichain_connector.cpp @@ -1,72 +1,88 @@ -#include "UTTest_hichain_connector.h" - -#include +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_constants.h" #include "dm_log.h" +#include "dm_constants.h" #include "dm_random.h" +#include "UTTest_hichain_connector.h" #include "hichain_connector.h" -#include "hichain_connector_callback.h" -#include "nlohmann/json.hpp" -#include "parameter.h" -namespace OHOS { -namespace DistributedHardware { -void DeviceManagerImplTest::SetUp() + +namespace OHOS +{ +namespace DistributedHardware +{ +void HichainConnectorTest::SetUp() { - // DmDiscoveryManage *m_DmDiscoveryManage; } - -void DeviceManagerImplTest::TearDown() +void HichainConnectorTest::TearDown() { } - -void DeviceManagerImplTest::SetUpTestCase() +void HichainConnectorTest::SetUpTestCase() { } - -void DeviceManagerImplTest::TearDownTestCase() +void HichainConnectorTest::TearDownTestCase() { } namespace { - -HWTEST_F(DeviceManagerImplTest, CreateGroup1, testing::ext::TestSize.Level0) +/** + * @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 = "lijia"; - std::shared_ptr hichainConnector = std::make_shared(); - hichainConnector->deviceGroupManager_ = nullptr; + 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); } -HWTEST_F(DeviceManagerImplTest, CreateGroup2, testing::ext::TestSize.Level0) -{ - int64_t requestId = 233444; - std::string groupName; - std::string DM_PKG_NAME = " "; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->CreateGroup(requestId, groupName); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceManagerImplTest, CreateGroup3, testing::ext::TestSize.Level0) +/** + * @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 = "lijia"; - // std::string DM_PKG_NAME = " "; - std::shared_ptr hichainConnector = std::make_shared(); + std::string groupName = "uuiioo"; + std::shared_ptr hichainConnector = std::make_shared(); int ret = hichainConnector->CreateGroup(requestId, groupName); EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, GetGroupInfo1, testing::ext::TestSize.Level0) +/** + * @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::shared_ptr hichainConnector = std::make_shared(); std::string groupName = "dcdkdkd1"; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); @@ -75,19 +91,14 @@ HWTEST_F(DeviceManagerImplTest, GetGroupInfo1, testing::ext::TestSize.Level0) int ret = hichainConnector->GetGroupInfo(queryParams, groupList); EXPECT_EQ(ret, 0); } -HWTEST_F(DeviceManagerImplTest, GetGroupInfo2, testing::ext::TestSize.Level0) -{ - std::shared_ptr hichainConnector = std::make_shared(); - std::string groupName = " "; - 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); -} -HWTEST_F(DeviceManagerImplTest, GetGroupInfo3, testing::ext::TestSize.Level0) +/** + * @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; @@ -97,121 +108,383 @@ HWTEST_F(DeviceManagerImplTest, GetGroupInfo3, testing::ext::TestSize.Level0) aa.groupName = "afa"; std::vector groupList; groupList.push_back(aa); - std::shared_ptr hichainConnector = std::make_shared(); + std::shared_ptr hichainConnector = std::make_shared(); int ret = hichainConnector->GetGroupInfo(queryParams, groupList); - std::cout << "ret= " << ret << std ::endl; EXPECT_EQ(ret, 0); } -HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid1, testing::ext::TestSize.Level0) +/** + * @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.disware.devicemanagersdsdss"; - group.groupType = 1; - group.groupVisibility = -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, true); + EXPECT_EQ(ret, false); } -HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid2, testing::ext::TestSize.Level0) +/** + * @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 = "lijia"; + group.groupName = "test"; group.groupId = 1; - group.groupOwner = "ohos.disware.devicemanagersdsdss"; + 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); -} - -HWTEST_F(DeviceManagerImplTest, IsGroupInfoInvalid3, testing::ext::TestSize.Level0) -{ - GroupInfo group; - group.groupName = "lijia"; - group.groupId = -1; - group.groupName = "ohos.distributedhardware.devicemanager"; - group.groupType = 0; group.groupVisibility = -1; std::shared_ptr hichainConnector = std::make_shared(); bool ret = hichainConnector->IsGroupInfoInvalid(group); EXPECT_EQ(ret, true); } -HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup1, testing::ext::TestSize.Level0) - +/** + * @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 = "1746"; - std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - // dmSubscribeInfo.capability = -1290002262 ; + std::string groupId ; + std::string deviceId; std::shared_ptr hichainConnector = std::make_shared(); - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; - - if (SoftbusConnector::discoveryDeviceInfoMap_.count(pkgName) > 0) { - deviceId = SoftbusConnector::discoveryDeviceInfoMap_[pkgName]->devId; - } int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup2, testing::ext::TestSize.Level0) - +/** + * @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(); + std::shared_ptr hichainConnector = std::make_shared(); int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, DelMemberFromGroup3, testing::ext::TestSize.Level0) +/** + * @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 groupId = "123445"; std::string pkgName = "com.softbus.test"; - int32_t freq = 2; - int32_t mode = 170; - int32_t medium = 0; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 1737; - dmSubscribeInfo.mode = (DmDiscoverMode)mode; - dmSubscribeInfo.medium = (DmExchangeMedium)medium; - dmSubscribeInfo.freq = (DmExchangeFreq)freq; - dmSubscribeInfo.isSameAccount = 0; - dmSubscribeInfo.isWakeRemote = 1; - // dmSubscribeInfo.capability = -1290002262 ; + 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(); - static std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SoftbusConnector::StartDiscovery(dmSubscribeInfo); - std::string deviceId = ""; - int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); - EXPECT_EQ(ret, 0); + 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); } -HWTEST_F(DeviceManagerImplTest, GenRequestId1, testing::ext::TestSize.Level0) + +/** + * @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(); - int ret = hichainConnector->GenRequestId(); - std::cout << "ret= " << ret << std ::endl; - EXPECT_TRUE(ret != 0); + 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); } -} // namespace +/** + * @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); +} +} +} +} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_hichain_connector.h b/test/unittest/UTTest_hichain_connector.h index b6aff2d17..29b1ac99d 100644 --- a/test/unittest/UTTest_hichain_connector.h +++ b/test/unittest/UTTest_hichain_connector.h @@ -1,35 +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 #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 "dm_discovery_manager.h" -#include "hichain_connector_callback.h" -#include "nlohmann/json.hpp" -#include "single_instance.h" +#include "hichain_connector.h" -namespace OHOS { -namespace DistributedHardware { -class DeviceManagerImplTest : public testing::Test { +namespace OHOS +{ +namespace DistributedHardware +{ +class HichainConnectorTest : 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 // OHOS_HICHAIN_CONNECTOR_H -- Gitee From 458b7e5c2732c5f714d382d3809aa06cca35569d Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Tue, 11 Jan 2022 22:17:06 +0800 Subject: [PATCH 104/110] modify bug --- .../include/authentication/dm_auth_manager.h | 1 + .../dependency/softbus/softbus_session_callback.h | 1 + .../src/authentication/dm_auth_manager.cpp | 13 +++++++++++-- .../src/dependency/softbus/softbus_session.cpp | 5 ++++- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 5bf2d4a04..e0710f180 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -148,6 +148,7 @@ public: void JoinNetwork(); void AuthenticateFinish(); void GetIsCryptoSupport(bool &isCryptoSupport); + bool GetAuthState(); void SetAuthRequestState(std::shared_ptr authRequestState); void SetAuthResponseState(std::shared_ptr authResponseState); int32_t GetPinCode(); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h index 9569a3313..502956a48 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h @@ -25,6 +25,7 @@ public: 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; + virtual bool GetAuthState() = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index f90418f25..5026918a8 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -337,7 +337,6 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); return; } - authResponseState_->TransitionTo(std::shared_ptr(new AuthResponseShowState())); authResponseContext_->groupId = groupId; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); @@ -595,7 +594,6 @@ void DmAuthManager::AuthenticateFinish() } authRequestContext_ = nullptr; authResponseContext_ = nullptr; - hiChainConnector_ = nullptr; authRequestState_ = nullptr; authMessageProcessor_ = nullptr; } @@ -650,6 +648,17 @@ void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) isCryptoSupport = isCryptoSupport_; } +bool DmAuthManager::GetAuthState() +{ + LOGI("DmAuthManager::GetAuthState start"); + if (authRequestState_ == nullptr && authResponseState_ == nullptr) { + LOGI("DmAuthManager::GetAuthState start1"); + return false; + } + LOGI("DmAuthManager::GetAuthState start2"); + return true; +} + void DmAuthManager::SetAuthRequestState(std::shared_ptr authRequestState) { authRequestState_ = authRequestState; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 7e31b7a3e..9c1f1f8f1 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -154,7 +154,10 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 } std::string message = std::string((const char *)data, dataLen); for (auto &iter : sessionCallbackMap_) { - iter.second->OnDataReceived(iter.first, sessionId, message); + + if (iter.second->GetAuthState()){ + iter.second->OnDataReceived(iter.first, sessionId, message); + } } LOGI("OnBytesReceived completed"); } -- Gitee From a3f399d5525782240b697c4f790e4c3996ab0996 Mon Sep 17 00:00:00 2001 From: puhui Date: Tue, 11 Jan 2022 22:54:58 +0800 Subject: [PATCH 105/110] =?UTF-8?q?=E6=B3=A8=E9=87=8Asyspara=5Fwatchagent?= =?UTF-8?q?=E9=83=A8=E4=BB=B6=EF=BC=8C=E8=A7=A3=E5=86=B3STD=E4=BB=93?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- services/devicemanagerservice/BUILD.gn | 2 +- .../src/dependency/softbus/softbus_connector.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 15d59a3d6..17a069332 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -193,7 +193,7 @@ if (defined(ohos_lite)) { "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "startup_l2:syspara", - "startup_l2:syspara_watchagent", +# "startup_l2:syspara_watchagent", ] subsystem_name = "distributedhardware" diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 1f78a2c18..53f943b9b 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -110,7 +110,7 @@ int32_t SoftbusConnector::Init() LOGI("service unpublish result is : %d", ret); } - ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); +// ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); LOGI("register Watch Parameter result is : %d"); return ret; } -- Gitee From a3a77d6ce7f967557ed5094aa69dc87e3ce23002 Mon Sep 17 00:00:00 2001 From: puhui Date: Wed, 12 Jan 2022 09:19:22 +0800 Subject: [PATCH 106/110] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=8A=E5=BA=93?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- BUILD.gn | 4 +-- ext/pin_auth/BUILD.gn | 3 +- ext/profile/BUILD.gn | 10 +++--- interfaces/inner_kits/native_cpp/BUILD.gn | 4 +-- interfaces/kits/js/BUILD.gn | 2 +- services/devicemanagerservice/BUILD.gn | 43 +++++++++++------------ test/BUILD.gn | 2 +- utils/BUILD.gn | 9 ++--- 8 files changed, 35 insertions(+), 42 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 9a9e3a176..3fc86faf2 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -13,7 +13,7 @@ import("//build/lite/config/component/lite_component.gni") -if (defined(ohos_lite)) { +if (defined(ohos_lite)) { lite_component("devicemanager_lite") { if (ohos_kernel_type == "liteos_m") { } else { @@ -24,4 +24,4 @@ if (defined(ohos_lite)) { ] } } -} +} \ No newline at end of file diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index 8f9c21897..cc8cfcefc 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -20,7 +20,6 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - } else { ohos_shared_library("devicemanagerext_pin_auth") { include_dirs = [ @@ -33,9 +32,9 @@ if (defined(ohos_lite)) { ] sources = [ + "src/ability/standard/dm_ability_manager.cpp", "src/pin_auth.cpp", "src/pin_auth_ui.cpp", - "src/ability/standard/dm_ability_manager.cpp", ] deps = [ diff --git a/ext/profile/BUILD.gn b/ext/profile/BUILD.gn index 6c3ff6d4d..4ac238c37 100644 --- a/ext/profile/BUILD.gn +++ b/ext/profile/BUILD.gn @@ -20,7 +20,6 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - } else { ohos_shared_library("devicemanagerext_profile") { include_dirs = [ @@ -50,17 +49,17 @@ if (defined(ohos_lite)) { "src/device_profile_adapter.cpp", "src/profile_connector.cpp", ] - + deps = [ + "${services_path}:devicemanagerservice", "${utils_path}:devicemanagerutils", "//utils/native/base:utils", - "${services_path}:devicemanagerservice", ] external_deps = [ + "device_profile_core:distributed_device_profile_client", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "device_profile_core:distributed_device_profile_client", ] defines = [ @@ -73,5 +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 227c2d711..2dbc348fd 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -99,8 +99,8 @@ if (defined(ohos_lite)) { deps = [ "${utils_path}:devicemanagerutils", - "//utils/native/base:utils", "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//utils/native/base:utils", ] defines = [ @@ -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 ca930a219..9bbe372f6 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 17a069332..799bb65ad 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -62,22 +62,22 @@ if (defined(ohos_lite)) { ] sources = [ - "src/device_manager_service.cpp", - "src/device_manager_service_listener.cpp", - "src/adapter/lite/dm_adapter_manager.cpp", - "src/authentication/dm_auth_manager.cpp", "src/ability/lite/dm_ability_manager.cpp", + "src/adapter/lite/dm_adapter_manager.cpp", "src/authentication/auth_message_processor.cpp", - "src/authentication/auth_ui.cpp", "src/authentication/auth_request_state.cpp", "src/authentication/auth_response_state.cpp", - "src/deviceinfo/dm_device_info_manager.cpp", - "src/devicestate/dm_device_state_manager.cpp", - "src/discovery/dm_discovery_manager.cpp", - "src/dependency/timer/dm_timer.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", @@ -141,27 +141,27 @@ if (defined(ohos_lite)) { ] sources = [ - "src/config/config_manager.cpp", - "src/device_manager_service.cpp", "src/ability/standard/dm_ability_manager.cpp", - "src/device_manager_service_listener.cpp", "src/adapter/standard/dm_adapter_manager.cpp", - "src/authentication/dm_auth_manager.cpp", - "src/authentication/auth_ui.cpp", "src/authentication/auth_message_processor.cpp", "src/authentication/auth_request_state.cpp", "src/authentication/auth_response_state.cpp", - "src/deviceinfo/dm_device_info_manager.cpp", - "src/devicestate/dm_device_state_manager.cpp", - "src/discovery/dm_discovery_manager.cpp", + "src/authentication/auth_ui.cpp", + "src/authentication/dm_auth_manager.cpp", + "src/config/config_manager.cpp", "src/dependency/commonevent/event_manager_adapt.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/standard/ipc_cmd_parser.cpp", - "src/ipc/standard/ipc_server_listener.cpp", "src/ipc/standard/ipc_server_client_proxy.cpp", + "src/ipc/standard/ipc_server_listener.cpp", "src/ipc/standard/ipc_server_stub.cpp", ] @@ -182,22 +182,21 @@ if (defined(ohos_lite)) { ] external_deps = [ - "ces_standard:cesfwk_core", - "ces_standard:cesfwk_innerkits", "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", "startup_l2:syspara", -# "startup_l2:syspara_watchagent", ] subsystem_name = "distributedhardware" part_name = "device_manager_base" } -} +} \ No newline at end of file diff --git a/test/BUILD.gn b/test/BUILD.gn index d29faeb19..ece194320 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 87648c2d6..888ae7f79 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -61,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", @@ -93,8 +90,8 @@ if (defined(ohos_lite)) { ] deps = [ - "//utils/native/base:utils", "//third_party/mbedtls:mbedtls_shared", + "//utils/native/base:utils", ] defines = [ @@ -105,11 +102,11 @@ if (defined(ohos_lite)) { external_deps = [ "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core" + "ipc:ipc_core", ] subsystem_name = "distributedhardware" part_name = "device_manager_base" } -} +} \ No newline at end of file -- Gitee From c5cef65a3d351a706cf68822ae43a46a6192f1d5 Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Wed, 12 Jan 2022 13:59:24 +0800 Subject: [PATCH 107/110] modify --- .../include/authentication/dm_auth_manager.h | 1 - .../softbus/softbus_session_callback.h | 1 - .../src/authentication/dm_auth_manager.cpp | 19 +++++-------------- .../dependency/softbus/softbus_session.cpp | 5 +---- 4 files changed, 6 insertions(+), 20 deletions(-) diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index e0710f180..5bf2d4a04 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -148,7 +148,6 @@ public: void JoinNetwork(); void AuthenticateFinish(); void GetIsCryptoSupport(bool &isCryptoSupport); - bool GetAuthState(); void SetAuthRequestState(std::shared_ptr authRequestState); void SetAuthResponseState(std::shared_ptr authResponseState); int32_t GetPinCode(); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h index 502956a48..9569a3313 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session_callback.h @@ -25,7 +25,6 @@ public: 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; - virtual bool GetAuthState() = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 5026918a8..36bbc679f 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -161,7 +161,6 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st std::string groupId = ""; std::vector groupList; - hiChainConnector_ = std::make_shared(); hiChainConnector_->GetRelatedGroups(deviceUdid, groupList); if (groupList.size() > 0) { groupId = groupList.front().groupId; @@ -173,7 +172,6 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st return DM_FAILED; } // groupId = authResponseContext_->groupId; - hiChainConnector_ = nullptr; return DM_OK; } @@ -262,6 +260,10 @@ void DmAuthManager::OnSessionClosed(const std::string &pkgName, int32_t sessionI 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 DM_FAILED; + } authResponseContext_->sessionId = sessionId; authMessageProcessor_->SetResponseContext(authResponseContext_); int32_t ret = authMessageProcessor_->ParseMessage(message); @@ -551,7 +553,7 @@ void DmAuthManager::JoinNetwork() void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); - if (authRequestState_ == nullptr) { + if (authResponseState_ != nullptr) { if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { CancelDisplay(); } @@ -648,17 +650,6 @@ void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport) isCryptoSupport = isCryptoSupport_; } -bool DmAuthManager::GetAuthState() -{ - LOGI("DmAuthManager::GetAuthState start"); - if (authRequestState_ == nullptr && authResponseState_ == nullptr) { - LOGI("DmAuthManager::GetAuthState start1"); - return false; - } - LOGI("DmAuthManager::GetAuthState start2"); - return true; -} - void DmAuthManager::SetAuthRequestState(std::shared_ptr authRequestState) { authRequestState_ = authRequestState; diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 9c1f1f8f1..7e31b7a3e 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -154,10 +154,7 @@ void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32 } std::string message = std::string((const char *)data, dataLen); for (auto &iter : sessionCallbackMap_) { - - if (iter.second->GetAuthState()){ - iter.second->OnDataReceived(iter.first, sessionId, message); - } + iter.second->OnDataReceived(iter.first, sessionId, message); } LOGI("OnBytesReceived completed"); } -- Gitee From b5193f04990ed33eda06fbae0566b1f43d1afd80 Mon Sep 17 00:00:00 2001 From: "weidong.liu@thundersoft.com" Date: Wed, 12 Jan 2022 14:36:31 +0800 Subject: [PATCH 108/110] add by weidong.liu@thundersoft.com change: 1.add discovery failed callback js; 2.not change hichain_connector when unAuthDevice for ranxiaocong --- interfaces/kits/js/src/native_devicemanager_js.cpp | 1 + .../devicemanagerservice/src/authentication/dm_auth_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index fe95d2f2c..3a4184de8 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1262,6 +1262,7 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac DiscoveryCallback); if (ret != 0) { LOGE("StartDeviceDiscovery for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); + DiscoveryCallback->OnDiscoveryFailed(subInfo.subscribeId, ret); return result; } diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 36bbc679f..8ecc890a7 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -262,7 +262,7 @@ void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId LOGI("DmAuthManager::OnDataReceived start"); if (authRequestState_ == nullptr && authResponseState_ == nullptr) { LOGI("DmAuthManager::GetAuthState failed"); - return DM_FAILED; + return; } authResponseContext_->sessionId = sessionId; authMessageProcessor_->SetResponseContext(authResponseContext_); -- Gitee From c040fd8a91ef86cce433c8a4c13faf0a35bd01dc Mon Sep 17 00:00:00 2001 From: "xiaocong.ran" Date: Wed, 12 Jan 2022 17:53:36 +0800 Subject: [PATCH 109/110] UT weibo Signed-off-by: xiaocong.ran --- test/unittest/BUILD.gn | 47 +- 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 ++ 5 files changed, 1207 insertions(+), 10 deletions(-) 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 diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index f3899a998..f821f194e 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -27,6 +27,10 @@ group("unittest") { ":UTTest_dm_device_state_manager", ":UTTest_device_manager_service_listener", ":UTTest_dm_device_info_manager", + ":UTTest_auth_response_state", + ":UTTest_auth_request_state", + ":UTTest_dm_auth_manager", + ":UTTest_device_message", ] } @@ -63,28 +67,55 @@ ohos_unittest("UTTest_hichain_connector") { ## UnitTest UTTest_hichain_connector }}} +## UnitTest UTTest_dm_auth_manager {{{ +ohos_unittest("UTTest_dm_auth_manager") { + module_out_path = module_out_path + sources = [ "UTTest_dm_auth_manager.cpp" ] + deps = [ ":device_manager_test_common" ] +} +## UTTest_dm_auth_manager }}} -## UnitTest UTTest_dm_device_info_manager {{{ -ohos_unittest("UTTest_dm_device_info_manager") { +## UnitTest UTTest_device_message {{{ +ohos_unittest("UTTest_device_message") { module_out_path = module_out_path - sources = [ "UTTest_dm_device_info_manager.cpp" ] + sources = [ "UTTest_device_message.cpp" ] deps = [ ":device_manager_test_common" ] } -## UnitTest UTTest_dm_device_info_manager }}} - +## UTTest_device_message }}} +## UnitTest UTTest_auth_response_state {{{ +ohos_unittest("UTTest_auth_response_state") { + module_out_path = module_out_path + sources = [ "UTTest_auth_response_state.cpp" ] + deps = [ ":device_manager_test_common" ] +} +## UTTest_auth_response_state }}} +## UnitTest UTTest_auth_request_state {{{ +ohos_unittest("UTTest_auth_request_state") { + module_out_path = module_out_path + sources = [ "UTTest_auth_request_state.cpp"] + deps = [ ":device_manager_test_common" ] +} +## UTTest_auth_request_state }}} +## 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") { @@ -145,10 +176,6 @@ ohos_unittest("UTTest_device_manager_service_listener") { ## UnitTest UTTest_device_manager_service_listener }}} - - - - ## UnitTest UTTest_dm_discovery_manager {{{ ohos_unittest("UTTest_dm_discovery_manager") { module_out_path = module_out_path @@ -338,4 +365,4 @@ ohos_static_library("device_manager_test") { "samgr_standard:samgr_proxy", ] } -## Build device_manager_test.a }}} \ No newline at end of file +## Build device_manager_test.a }}} 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 -- Gitee From dac8f44e7f6c7714d6f17dd5fa6de68d9e43e0cf Mon Sep 17 00:00:00 2001 From: puhui Date: Wed, 12 Jan 2022 18:52:10 +0800 Subject: [PATCH 110/110] =?UTF-8?q?=E5=88=B7=E6=96=B0unittest=20Build.gn?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: puhui --- ...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 + test/unittest/BUILD.gn | 191 +++---- 14 files changed, 1353 insertions(+), 116 deletions(-) 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 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